Debian Codegraph @

main/manager.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2006, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
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 <[email protected]>
24 *
25 * OpenSSL http://www.openssl.org - for AMI/SSL
26 *
27 * At the moment this file contains a number of functions, namely:
28 *
29 * - data structures storing AMI state
30 * - AMI-related API functions, used by internal asterisk components
31 * - handlers for AMI-related CLI functions
32 * - handlers for AMI functions (available through the AMI socket)
33 * - the code for the main AMI listener thread and individual session threads
34 * - the http handlers invoked for AMI-over-HTTP by the threads in main/http.c
35 *
36 * \ref amiconf
37 */
38
39 /*! \li \ref manager.c uses the configuration file \ref manager.conf and \ref users.conf
40 * \addtogroup configuration_file
41 */
42
43 /*! \page manager.conf manager.conf
44 * \verbinclude manager.conf.sample
45 */
46
47 /*! \page users.conf users.conf
48 * \verbinclude users.conf.sample
49 */
50
51 /*** MODULEINFO
52 <support_level>core</support_level>
53 ***/
54
55 #include "asterisk.h"
56
57 #include "asterisk/paths.h" /* use various ast_config_AST_* */
58 #include <ctype.h>
59 #include <sys/time.h>
60 #include <signal.h>
61 #include <sys/mman.h>
62 #include <sys/types.h>
63 #include <regex.h>
64
65 #include "asterisk/channel.h"
66 #include "asterisk/file.h"
67 #include "asterisk/manager.h"
68 #include "asterisk/module.h"
69 #include "asterisk/config.h"
70 #include "asterisk/callerid.h"
71 #include "asterisk/core_local.h"
72 #include "asterisk/lock.h"
73 #include "asterisk/cli.h"
74 #include "asterisk/app.h"
75 #include "asterisk/mwi.h"
76 #include "asterisk/pbx.h"
77 #include "asterisk/md5.h"
78 #include "asterisk/acl.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/tcptls.h"
81 #include "asterisk/http.h"
82 #include "asterisk/ast_version.h"
83 #include "asterisk/threadstorage.h"
84 #include "asterisk/linkedlists.h"
85 #include "asterisk/term.h"
86 #include "asterisk/astobj2.h"
87 #include "asterisk/features.h"
88 #include "asterisk/security_events.h"
89 #include "asterisk/aoc.h"
90 #include "asterisk/strings.h"
91 #include "asterisk/stringfields.h"
92 #include "asterisk/presencestate.h"
93 #include "asterisk/stasis_message_router.h"
94 #include "asterisk/stasis_channels.h"
95 #include "asterisk/stasis_bridges.h"
96 #include "asterisk/test.h"
97 #include "asterisk/json.h"
98 #include "asterisk/bridge.h"
99 #include "asterisk/bridge_after.h"
100 #include "asterisk/features_config.h"
101 #include "asterisk/rtp_engine.h"
102 #include "asterisk/format_cache.h"
103 #include "asterisk/translate.h"
104 #include "asterisk/taskprocessor.h"
105 #include "asterisk/message.h"
106
107 /*! \addtogroup Group_AMI AMI functions
108 */
109 /*! @{
110 Doxygen group */
111
112 enum error_type {
113 UNKNOWN_ACTION = 1,
114 UNKNOWN_CATEGORY,
115 UNSPECIFIED_CATEGORY,
116 UNSPECIFIED_ARGUMENT,
117 FAILURE_ALLOCATION,
118 FAILURE_NEWCAT,
119 FAILURE_DELCAT,
120 FAILURE_EMPTYCAT,
121 FAILURE_UPDATE,
122 FAILURE_DELETE,
123 FAILURE_APPEND,
124 FAILURE_TEMPLATE
125 };
126
127 enum add_filter_result {
128 FILTER_SUCCESS = 0,
129 FILTER_ALLOC_FAILED,
130 FILTER_COMPILE_FAIL,
131 FILTER_FORMAT_ERROR,
132 };
133
134 /*!
135 * Linked list of events.
136 * Global events are appended to the list by append_event().
137 * The usecount is the number of stored pointers to the element,
138 * excluding the list pointers. So an element that is only in
139 * the list has a usecount of 0, not 1.
140 *
141 * Clients have a pointer to the last event processed, and for each
142 * of these clients we track the usecount of the elements.
143 * If we have a pointer to an entry in the list, it is safe to navigate
144 * it forward because elements will not be deleted, but only appended.
145 * The worst that can happen is seeing the pointer still NULL.
146 *
147 * When the usecount of an element drops to 0, and the element is the
148 * first in the list, we can remove it. Removal is done within the
149 * main thread, which is woken up for the purpose.
150 *
151 * For simplicity of implementation, we make sure the list is never empty.
152 */
153 struct eventqent {
154 int usecount; /*!< # of clients who still need the event */
155 int category;
156 unsigned int seq; /*!< sequence number */
157 struct timeval tv; /*!< When event was allocated */
158 int event_name_hash;
159 AST_RWLIST_ENTRY(eventqent) eq_next;
160 char eventdata[1]; /*!< really variable size, allocated by append_event() */
161 };
162
163 static AST_RWLIST_HEAD_STATIC(all_events, eventqent);
164
165 static int displayconnects = 1;
166 static int allowmultiplelogin = 1;
167 static int timestampevents;
168 static int httptimeout = 60;
169 static int broken_events_action = 0;
170 static int manager_enabled = 0;
171 static int subscribed = 0;
172 static int webmanager_enabled = 0;
173 static int manager_debug = 0; /*!< enable some debugging code in the manager */
174 static int authtimeout;
175 static int authlimit;
176 static char *manager_channelvars;
177 static char *manager_disabledevents;
178
179 #define DEFAULT_REALM "asterisk"
180 static char global_realm[MAXHOSTNAMELEN]; /*!< Default realm */
181
182 static int unauth_sessions = 0;
183 static struct stasis_subscription *acl_change_sub;
184
185 /*! \brief A \ref stasis_topic that all topics AMI cares about will be forwarded to */
186 static struct stasis_topic *manager_topic;
187
188 /*! \brief The \ref stasis_message_router for all \ref stasis messages */
189 static struct stasis_message_router *stasis_router;
190
191 /*! \brief The \ref stasis_subscription for forwarding the RTP topic to the AMI topic */
192 static struct stasis_forward *rtp_topic_forwarder;
193
194 /*! \brief The \ref stasis_subscription for forwarding the Security topic to the AMI topic */
195 static struct stasis_forward *security_topic_forwarder;
196
197 /*!
198 * \brief Set to true (non-zero) to globally allow all dangerous AMI actions to run
199 */
200 static int live_dangerously;
201
202 #ifdef TEST_FRAMEWORK
203 /*! \brief The \ref stasis_subscription for forwarding the Test topic to the AMI topic */
204 static struct stasis_forward *test_suite_forwarder;
205 #endif
206
207 #define MGR_SHOW_TERMINAL_WIDTH 80
208
209 #define MAX_VARS 128
210
211 /*! \brief Fake event class used to end sessions at shutdown */
212 #define EVENT_FLAG_SHUTDOWN -1
213
214 /*! \brief
215 * Descriptor for a manager session, either on the AMI socket or over HTTP.
216 *
217 * \note
218 * AMI session have managerid == 0; the entry is created upon a connect,
219 * and destroyed with the socket.
220 * HTTP sessions have managerid != 0, the value is used as a search key
221 * to lookup sessions (using the mansession_id cookie, or nonce key from
222 * Digest Authentication http header).
223 */
224 #define MAX_BLACKLIST_CMD_LEN 2
225 static const struct {
226 const char *words[AST_MAX_CMD_LEN];
227 } command_blacklist[] = {
228 {{ "module", "load", NULL }},
229 {{ "module", "unload", NULL }},
230 {{ "restart", "gracefully", NULL }},
231 };
232
233 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
234
235 static void acl_change_stasis_subscribe(void)
236 {
237 if (!acl_change_sub) {
238 acl_change_sub = stasis_subscribe(ast_security_topic(),
239 acl_change_stasis_cb, NULL);
240 stasis_subscription_accept_message_type(acl_change_sub, ast_named_acl_change_type());
241 stasis_subscription_set_filter(acl_change_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
242 }
243 }
244
245 static void acl_change_stasis_unsubscribe(void)
246 {
247 acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
248 }
249
250 /* In order to understand what the heck is going on with the
251 * mansession_session and mansession structs, we need to have a bit of a history
252 * lesson.
253 *
254 * In the beginning, there was the mansession. The mansession contained data that was
255 * intrinsic to a manager session, such as the time that it started, the name of the logged-in
256 * user, etc. In addition to these parameters were the f and fd parameters. For typical manager
257 * sessions, these were used to represent the TCP socket over which the AMI session was taking
258 * place. It makes perfect sense for these fields to be a part of the session-specific data since
259 * the session actually defines this information.
260 *
261 * Then came the HTTP AMI sessions. With these, the f and fd fields need to be opened and closed
262 * for every single action that occurs. Thus the f and fd fields aren't really specific to the session
263 * but rather to the action that is being executed. Because a single session may execute many commands
264 * at once, some sort of safety needed to be added in order to be sure that we did not end up with fd
265 * leaks from one action overwriting the f and fd fields used by a previous action before the previous action
266 * has had a chance to properly close its handles.
267 *
268 * The initial idea to solve this was to use thread synchronization, but this prevented multiple actions
269 * from being run at the same time in a single session. Some manager actions may block for a long time, thus
270 * creating a large queue of actions to execute. In addition, this fix did not address the basic architectural
271 * issue that for HTTP manager sessions, the f and fd variables are not really a part of the session, but are
272 * part of the action instead.
273 *
274 * The new idea was to create a structure on the stack for each HTTP Manager action. This structure would
275 * contain the action-specific information, such as which file to write to. In order to maintain expectations
276 * of action handlers and not have to change the public API of the manager code, we would need to name this
277 * new stacked structure 'mansession' and contain within it the old mansession struct that we used to use.
278 * We renamed the old mansession struct 'mansession_session' to hopefully convey that what is in this structure
279 * is session-specific data. The structure that it is wrapped in, called a 'mansession' really contains action-specific
280 * data.
281 */
282 struct mansession_session {
283 /*! \todo XXX need to document which fields it is protecting */
284 struct ast_sockaddr addr; /*!< address we are connecting from */
285 struct ast_iostream *stream; /*!< AMI stream */
286 int inuse; /*!< number of HTTP sessions using this entry */
287 int needdestroy; /*!< Whether an HTTP session should be destroyed */
288 pthread_t waiting_thread; /*!< Sleeping thread using this descriptor */
289 uint32_t managerid; /*!< Unique manager identifier, 0 for AMI sessions */
290 time_t sessionstart; /*!< Session start time */
291 struct timeval sessionstart_tv; /*!< Session start time */
292 time_t sessiontimeout; /*!< Session timeout if HTTP */
293 char username[80]; /*!< Logged in username */
294 char challenge[10]; /*!< Authentication challenge */
295 int authenticated; /*!< Authentication status */
296 int readperm; /*!< Authorization for reading */
297 int writeperm; /*!< Authorization for writing */
298 char inbuf[1025]; /*!< Buffer - we use the extra byte to add a '\\0' and simplify parsing */
299 int inlen; /*!< number of buffered bytes */
300 struct ao2_container *includefilters; /*!< Manager event filters - include list */
301 struct ao2_container *excludefilters; /*!< Manager event filters - exclude list */
302 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
303 int send_events; /*!< XXX what ? */
304 struct eventqent *last_ev; /*!< last event processed. */
305 int writetimeout; /*!< Timeout for ast_carefulwrite() */
306 time_t authstart;
307 int pending_event; /*!< Pending events indicator in case when waiting_thread is NULL */
308 time_t noncetime; /*!< Timer for nonce value expiration */
309 unsigned long oldnonce; /*!< Stale nonce value */
310 unsigned long nc; /*!< incremental nonce counter */
311 unsigned int kicked:1; /*!< Flag set if session is forcibly kicked */
312 ast_mutex_t notify_lock; /*!< Lock for notifying this session of events */
313 AST_LIST_HEAD_NOLOCK(mansession_datastores, ast_datastore) datastores; /*!< Data stores on the session */
314 AST_LIST_ENTRY(mansession_session) list;
315 };
316
317 enum mansession_message_parsing {
318 MESSAGE_OKAY,
319 MESSAGE_LINE_TOO_LONG
320 };
321
322 /*! \brief In case you didn't read that giant block of text above the mansession_session struct, the
323 * \ref mansession is named this solely to keep the API the same in Asterisk. This structure really
324 * represents data that is different from Manager action to Manager action. The mansession_session pointer
325 * contained within points to session-specific data.
326 */
327 struct mansession {
328 struct mansession_session *session;
329 struct ast_iostream *stream;
330 struct ast_tcptls_session_instance *tcptls_session;
331 enum mansession_message_parsing parsing;
332 unsigned int write_error:1;
333 struct manager_custom_hook *hook;
334 ast_mutex_t lock;
335 };
336
337 /*! Active manager connection sessions container. */
338 static AO2_GLOBAL_OBJ_STATIC(mgr_sessions);
339
340 /*! \brief user descriptor, as read from the config file.
341 *
342 * \note It is still missing some fields -- e.g. we can have multiple permit and deny
343 * lines which are not supported here, and readperm/writeperm/writetimeout
344 * are not stored.
345 */
346 struct ast_manager_user {
347 char username[80];
348 char *secret; /*!< Secret for logging in */
349 int readperm; /*!< Authorization for reading */
350 int writeperm; /*!< Authorization for writing */
351 int writetimeout; /*!< Per user Timeout for ast_carefulwrite() */
352 int displayconnects; /*!< XXX unused */
353 int allowmultiplelogin; /*!< Per user option*/
354 int keep; /*!< mark entries created on a reload */
355 struct ao2_container *includefilters; /*!< Manager event filters - include list */
356 struct ao2_container *excludefilters; /*!< Manager event filters - exclude list */
357 struct ast_acl_list *acl; /*!< ACL setting */
358 char *a1_hash; /*!< precalculated A1 for Digest auth */
359 struct ast_variable *chanvars; /*!< Channel variables to set for originate */
360 AST_RWLIST_ENTRY(ast_manager_user) list;
361 };
362
363 /*! \brief list of users found in the config file */
364 static AST_RWLIST_HEAD_STATIC(users, ast_manager_user);
365
366 /*! \brief list of actions registered */
367 static AST_RWLIST_HEAD_STATIC(actions, manager_action);
368
369 /*! \brief list of hooks registered */
370 static AST_RWLIST_HEAD_STATIC(manager_hooks, manager_custom_hook);
371
372 #ifdef AST_XML_DOCS
373 /*! \brief A container of event documentation nodes */
374 static AO2_GLOBAL_OBJ_STATIC(event_docs);
375 #endif
376
377 static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
378 struct ao2_container *sessions,
379 int category,
380 const char *event,
381 int chancount,
382 struct ast_channel **chans,
383 const char *file,
384 int line,
385 const char *func,
386 const char *fmt,
387 ...);
388
389 enum event_filter_match_type {
390 FILTER_MATCH_REGEX = 0,
391 FILTER_MATCH_EXACT,
392 FILTER_MATCH_STARTS_WITH,
393 FILTER_MATCH_ENDS_WITH,
394 FILTER_MATCH_CONTAINS,
395 FILTER_MATCH_NONE,
396 };
397
398 static char *match_type_names[] = {
399 [FILTER_MATCH_REGEX] = "regex",
400 [FILTER_MATCH_EXACT] = "exact",
401 [FILTER_MATCH_STARTS_WITH] = "starts_with",
402 [FILTER_MATCH_ENDS_WITH] = "ends_with",
403 [FILTER_MATCH_CONTAINS] = "contains",
404 [FILTER_MATCH_NONE] = "none",
405 };
406
407 struct event_filter_entry {
408 enum event_filter_match_type match_type;
409 regex_t *regex_filter;
410 char *string_filter;
411 char *event_name;
412 unsigned int event_name_hash;
413 char *header_name;
414 int is_excludefilter;
415 };
416
417 static enum add_filter_result manager_add_filter(const char *criteria,
418 const char *filter_pattern, struct ao2_container *includefilters,
419 struct ao2_container *excludefilters);
420
421 static int should_send_event(struct ao2_container *includefilters,
422 struct ao2_container *excludefilters, struct eventqent *eqe);
423
424 /*!
425 * @{ \brief Define AMI message types.
426 */
427 STASIS_MESSAGE_TYPE_DEFN(ast_manager_get_generic_type);
428 /*! @} */
429
430 /*!
431 * \internal
432 * \brief Find a registered action object.
433 *
434 * \param name Name of AMI action to find.
435 *
436 * \return Reffed action found or NULL
437 */
438 static struct manager_action *action_find(const char *name)
439 {
440 struct manager_action *act;
441
442 AST_RWLIST_RDLOCK(&actions);
443 AST_RWLIST_TRAVERSE(&actions, act, list) {
444 if (!strcasecmp(name, act->action)) {
445 ao2_t_ref(act, +1, "found action object");
446 break;
447 }
448 }
449 AST_RWLIST_UNLOCK(&actions);
450
451 return act;
452 }
453
454 struct stasis_topic *ast_manager_get_topic(void)
455 {
456 return manager_topic;
457 }
458
459 struct stasis_message_router *ast_manager_get_message_router(void)
460 {
461 return stasis_router;
462 }
463
464 static void manager_json_value_str_append(struct ast_json *value, const char *key,
465 struct ast_str **res)
466 {
467 switch (ast_json_typeof(value)) {
468 case AST_JSON_STRING:
469 ast_str_append(res, 0, "%s: %s\r\n", key, ast_json_string_get(value));
470 break;
471 case AST_JSON_INTEGER:
472 ast_str_append(res, 0, "%s: %jd\r\n", key, ast_json_integer_get(value));
473 break;
474 case AST_JSON_TRUE:
475 ast_str_append(res, 0, "%s: True\r\n", key);
476 break;
477 case AST_JSON_FALSE:
478 ast_str_append(res, 0, "%s: False\r\n", key);
479 break;
480 default:
481 ast_str_append(res, 0, "%s: \r\n", key);
482 break;
483 }
484 }
485
486 static void manager_json_to_ast_str(struct ast_json *obj, const char *key,
487 struct ast_str **res, key_exclusion_cb exclusion_cb);
488
489 static void manager_json_array_with_key(struct ast_json *obj, const char* key,
490 size_t index, struct ast_str **res,
491 key_exclusion_cb exclusion_cb)
492 {
493 struct ast_str *key_str = ast_str_alloca(64);
494 ast_str_set(&key_str, 0, "%s(%zu)", key, index);
495 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
496 res, exclusion_cb);
497 }
498
499 static void manager_json_obj_with_key(struct ast_json *obj, const char* key,
500 const char *parent_key, struct ast_str **res,
501 key_exclusion_cb exclusion_cb)
502 {
503 if (parent_key) {
504 struct ast_str *key_str = ast_str_alloca(64);
505 ast_str_set(&key_str, 0, "%s/%s", parent_key, key);
506 manager_json_to_ast_str(obj, ast_str_buffer(key_str),
507 res, exclusion_cb);
508 return;
509 }
510
511 manager_json_to_ast_str(obj, key, res, exclusion_cb);
512 }
513
514 void manager_json_to_ast_str(struct ast_json *obj, const char *key,
515 struct ast_str **res, key_exclusion_cb exclusion_cb)
516 {
517 struct ast_json_iter *i;
518
519 /* If obj or res is not given, just return */
520 if (!obj || !res) {
521 return;
522 }
523
524 if (!*res && !(*res = ast_str_create(1024))) {
525 return;
526 }
527
528 if (exclusion_cb && key && exclusion_cb(key)) {
529 return;
530 }
531
532 if (ast_json_typeof(obj) != AST_JSON_OBJECT &&
533 ast_json_typeof(obj) != AST_JSON_ARRAY) {
534 manager_json_value_str_append(obj, key, res);
535 return;
536 }
537
538 if (ast_json_typeof(obj) == AST_JSON_ARRAY) {
539 size_t j;
540 for (j = 0; j < ast_json_array_size(obj); ++j) {
541 manager_json_array_with_key(ast_json_array_get(obj, j),
542 key, j, res, exclusion_cb);
543 }
544 return;
545 }
546
547 for (i = ast_json_object_iter(obj); i;
548 i = ast_json_object_iter_next(obj, i)) {
549 manager_json_obj_with_key(ast_json_object_iter_value(i),
550 ast_json_object_iter_key(i),
551 key, res, exclusion_cb);
552 }
553 }
554
555 struct ast_str *ast_manager_str_from_json_object(struct ast_json *blob, key_exclusion_cb exclusion_cb)
556 {
557 struct ast_str *res = ast_str_create(1024);
558
559 if (!ast_json_is_null(blob)) {
560 manager_json_to_ast_str(blob, NULL, &res, exclusion_cb);
561 }
562
563 return res;
564 }
565
566 #define manager_event_sessions(sessions, category, event, contents , ...) \
567 __manager_event_sessions(sessions, category, event, 0, NULL, __FILE__, __LINE__, __PRETTY_FUNCTION__, contents , ## __VA_ARGS__)
568
569 #define any_manager_listeners(sessions) \
570 ((sessions && ao2_container_count(sessions)) || !AST_RWLIST_EMPTY(&manager_hooks))
571
572 static void manager_default_msg_cb(void *data, struct stasis_subscription *sub,
573 struct stasis_message *message)
574 {
575 struct ao2_container *sessions = data;
576 struct ast_manager_event_blob *ev;
577
578 /*
579 * This callback only receives messages that can be turned into AMI events, so
580 * no need to check that the message can be turned into an event before checking for listeners.
581 */
582 if (!any_manager_listeners(sessions)) {
583 /* Nobody is listening */
584 return;
585 }
586
587 ev = stasis_message_to_ami(message);
588 if (!ev) {
589 /* Conversion failure */
590 return;
591 }
592
593 manager_event_sessions(sessions, ev->event_flags, ev->manager_event,
594 "%s", ev->extra_fields);
595 ao2_ref(ev, -1);
596 }
597
598 static void manager_generic_msg_cb(void *data, struct stasis_subscription *sub,
599 struct stasis_message *message)
600 {
601 struct ast_json_payload *payload;
602 int class_type;
603 const char *type;
604 struct ast_json *event;
605 struct ast_str *event_buffer;
606 struct ao2_container *sessions = data;
607
608 if (!any_manager_listeners(sessions)) {
609 /* Nobody is listening */
610 return;
611 }
612
613 payload = stasis_message_data(message);
614 class_type = ast_json_integer_get(ast_json_object_get(payload->json, "class_type"));
615 type = ast_json_string_get(ast_json_object_get(payload->json, "type"));
616 event = ast_json_object_get(payload->json, "event");
617
618 event_buffer = ast_manager_str_from_json_object(event, NULL);
619 if (!event_buffer) {
620 ast_log(AST_LOG_WARNING, "Error while creating payload for event %s\n", type);
621 return;
622 }
623
624 manager_event_sessions(sessions, class_type, type,
625 "%s", ast_str_buffer(event_buffer));
626 ast_free(event_buffer);
627 }
628
629 /*!
630 * \brief Callback for subscription change messages
631 * \param userdata The subscription user data (in our case a pointer to the sessions container)
632 * \param sub The subscription
633 * \param message The message
634 */
635 static void manager_subscription_change_msg_cb(void *userdata, struct stasis_subscription *sub,
636 struct stasis_message *message)
637 {
638 /*
639 * When the subscription unsubscribes a final message is sent to the subscription
640 * to indicate it. We use this to manage the lifetime of the sessions container
641 * pointer stored with the subscription. When the subscription is done we drop
642 * the reference to the sessions container (userdata) so it can be cleaned up
643 * if needed.
644 */
645 if (stasis_subscription_final_message(sub, message)) {
646 ao2_cleanup(userdata);
647 }
648 }
649
650 void ast_manager_publish_event(const char *type, int class_type, struct ast_json *obj)
651 {
652 RAII_VAR(struct ast_json *, event_info, NULL, ast_json_unref);
653 RAII_VAR(struct ast_json_payload *, payload, NULL, ao2_cleanup);
654 RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
655
656 if (!obj || !ast_manager_get_generic_type()) {
657 return;
658 }
659
660 ast_json_ref(obj);
661 event_info = ast_json_pack("{s: s, s: i, s: o}",
662 "type", type,
663 "class_type", class_type,
664 "event", obj);
665 if (!event_info) {
666 return;
667 }
668
669 payload = ast_json_payload_create(event_info);
670 if (!payload) {
671 return;
672 }
673 message = stasis_message_create(ast_manager_get_generic_type(), payload);
674 if (!message) {
675 return;
676 }
677 stasis_publish(ast_manager_get_topic(), message);
678 }
679
680 /*! \brief Add a custom hook to be called when an event is fired */
681 void ast_manager_register_hook(struct manager_custom_hook *hook)
682 {
683 AST_RWLIST_WRLOCK(&manager_hooks);
684 AST_RWLIST_INSERT_TAIL(&manager_hooks, hook, list);
685 AST_RWLIST_UNLOCK(&manager_hooks);
686 }
687
688 /*! \brief Delete a custom hook to be called when an event is fired */
689 void ast_manager_unregister_hook(struct manager_custom_hook *hook)
690 {
691 AST_RWLIST_WRLOCK(&manager_hooks);
692 AST_RWLIST_REMOVE(&manager_hooks, hook, list);
693 AST_RWLIST_UNLOCK(&manager_hooks);
694 }
695
696 int ast_manager_check_enabled(void)
697 {
698 return manager_enabled;
699 }
700
701 int ast_webmanager_check_enabled(void)
702 {
703 return (webmanager_enabled && manager_enabled);
704 }
705
706 /*!
707 * Grab a reference to the last event, update usecount as needed.
708 * Can handle a NULL pointer.
709 */
710 static struct eventqent *grab_last(void)
711 {
712 struct eventqent *ret;
713
714 AST_RWLIST_WRLOCK(&all_events);
715 ret = AST_RWLIST_LAST(&all_events);
716 /* the list is never empty now, but may become so when
717 * we optimize it in the future, so be prepared.
718 */
719 if (ret) {
720 ast_atomic_fetchadd_int(&ret->usecount, 1);
721 }
722 AST_RWLIST_UNLOCK(&all_events);
723 return ret;
724 }
725
726 /*!
727 * Purge unused events. Remove elements from the head
728 * as long as their usecount is 0 and there is a next element.
729 */
730 static void purge_events(void)
731 {
732 struct eventqent *ev;
733 struct timeval now = ast_tvnow();
734
735 AST_RWLIST_WRLOCK(&all_events);
736 while ( (ev = AST_RWLIST_FIRST(&all_events)) &&
737 ev->usecount == 0 && AST_RWLIST_NEXT(ev, eq_next)) {
738 AST_RWLIST_REMOVE_HEAD(&all_events, eq_next);
739 ast_free(ev);
740 }
741
742 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&all_events, ev, eq_next) {
743 /* Never release the last event */
744 if (!AST_RWLIST_NEXT(ev, eq_next)) {
745 break;
746 }
747
748 /* 2.5 times whatever the HTTP timeout is (maximum 2.5 hours) is the maximum time that we will definitely cache an event */
749 if (ev->usecount == 0 && ast_tvdiff_sec(now, ev->tv) > (httptimeout > 3600 ? 3600 : httptimeout) * 2.5) {
750 AST_RWLIST_REMOVE_CURRENT(eq_next);
751 ast_free(ev);
752 }
753 }
754 AST_RWLIST_TRAVERSE_SAFE_END;
755 AST_RWLIST_UNLOCK(&all_events);
756 }
757
758 /*!
759 * helper functions to convert back and forth between
760 * string and numeric representation of set of flags
761 */
762 static const struct permalias {
763 int num;
764 const char *label;
765 } perms[] = {
766 { EVENT_FLAG_SYSTEM, "system" },
767 { EVENT_FLAG_CALL, "call" },
768 { EVENT_FLAG_LOG, "log" },
769 { EVENT_FLAG_VERBOSE, "verbose" },
770 { EVENT_FLAG_COMMAND, "command" },
771 { EVENT_FLAG_AGENT, "agent" },
772 { EVENT_FLAG_USER, "user" },
773 { EVENT_FLAG_CONFIG, "config" },
774 { EVENT_FLAG_DTMF, "dtmf" },
775 { EVENT_FLAG_REPORTING, "reporting" },
776 { EVENT_FLAG_CDR, "cdr" },
777 { EVENT_FLAG_DIALPLAN, "dialplan" },
778 { EVENT_FLAG_ORIGINATE, "originate" },
779 { EVENT_FLAG_AGI, "agi" },
780 { EVENT_FLAG_CC, "cc" },
781 { EVENT_FLAG_AOC, "aoc" },
782 { EVENT_FLAG_TEST, "test" },
783 { EVENT_FLAG_SECURITY, "security" },
784 { EVENT_FLAG_MESSAGE, "message" },
785 { INT_MAX, "all" },
786 { 0, "none" },
787 };
788
789 /*! Maximum string length of the AMI authority permission string buildable from perms[]. */
790 #define MAX_AUTH_PERM_STRING 150
791
792 /*! \brief Checks to see if a string which can be used to evaluate functions should be rejected */
793 static int function_capable_string_allowed_with_auths(const char *evaluating, int writepermlist)
794 {
795 if (!(writepermlist & EVENT_FLAG_SYSTEM)
796 && (
797 strstr(evaluating, "SHELL") || /* NoOp(${SHELL(rm -rf /)}) */
798 strstr(evaluating, "EVAL") /* NoOp(${EVAL(${some_var_containing_SHELL})}) */
799 )) {
800 return 0;
801 }
802 return 1;
803 }
804
805 /*! \brief Convert authority code to a list of options for a user. This will only
806 * display those authority codes that have an explicit match on authority */
807 static const char *user_authority_to_str(int authority, struct ast_str **res)
808 {
809 int i;
810 char *sep = "";
811
812 ast_str_reset(*res);
813 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
814 if ((authority & perms[i].num) == perms[i].num) {
815 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
816 sep = ",";
817 }
818 }
819
820 if (ast_str_strlen(*res) == 0) {
821 /* replace empty string with something sensible */
822 ast_str_append(res, 0, "<none>");
823 }
824
825 return ast_str_buffer(*res);
826 }
827
828
829 /*! \brief Convert authority code to a list of options. Note that the EVENT_FLAG_ALL
830 * authority will always be returned. */
831 static const char *authority_to_str(int authority, struct ast_str **res)
832 {
833 int i;
834 char *sep = "";
835
836 ast_str_reset(*res);
837 if (authority != EVENT_FLAG_SHUTDOWN) {
838 for (i = 0; i < ARRAY_LEN(perms) - 1; i++) {
839 if (authority & perms[i].num) {
840 ast_str_append(res, 0, "%s%s", sep, perms[i].label);
841 sep = ",";
842 }
843 }
844 }
845
846 if (ast_str_strlen(*res) == 0) {
847 /* replace empty string with something sensible */
848 ast_str_append(res, 0, "<none>");
849 }
850
851 return ast_str_buffer(*res);
852 }
853
854 /*! Tells you if smallstr exists inside bigstr
855 which is delim by delim and uses no buf or stringsep
856 ast_instring("this|that|more","this",'|') == 1;
857
858 feel free to move this to app.c -anthm */
859 static int ast_instring(const char *bigstr, const char *smallstr, const char delim)
860 {
861 const char *val = bigstr, *next;
862
863 do {
864 if ((next = strchr(val, delim))) {
865 if (!strncmp(val, smallstr, (next - val))) {
866 return 1;
867 } else {
868 continue;
869 }
870 } else {
871 return !strcmp(smallstr, val);
872 }
873 } while (*(val = (next + 1)));
874
875 return 0;
876 }
877
878 static int get_perm(const char *instr)
879 {
880 int x = 0, ret = 0;
881
882 if (!instr) {
883 return 0;
884 }
885
886 for (x = 0; x < ARRAY_LEN(perms); x++) {
887 if (ast_instring(instr, perms[x].label, ',')) {
888 ret |= perms[x].num;
889 }
890 }
891
892 return ret;
893 }
894
895 /*!
896 * A number returns itself, false returns 0, true returns all flags,
897 * other strings return the flags that are set.
898 */
899 static int strings_to_mask(const char *string)
900 {
901 const char *p;
902
903 if (ast_strlen_zero(string)) {
904 return -1;
905 }
906
907 for (p = string; *p; p++) {
908 if (*p < '0' || *p > '9') {
909 break;
910 }
911 }
912 if (!*p) { /* all digits */
913 return atoi(string);
914 }
915 if (ast_false(string)) {
916 return 0;
917 }
918 if (ast_true(string)) { /* all permissions */
919 int x, ret = 0;
920 for (x = 0; x < ARRAY_LEN(perms); x++) {
921 ret |= perms[x].num;
922 }
923 return ret;
924 }
925 return get_perm(string);
926 }
927
928 /*! \brief Unreference manager session object.
929 If no more references, then go ahead and delete it */
930 static struct mansession_session *unref_mansession(struct mansession_session *s)
931 {
932 int refcount = ao2_ref(s, -1);
933 if (manager_debug) {
934 ast_debug(1, "Mansession: %p refcount now %d\n", s, refcount - 1);
935 }
936 return NULL;
937 }
938
939 static void event_filter_destructor(void *obj)
940 {
941 struct event_filter_entry *entry = obj;
942 if (entry->regex_filter) {
943 regfree(entry->regex_filter);
944 ast_free(entry->regex_filter);
945 }
946 ast_free(entry->event_name);
947 ast_free(entry->header_name);
948 ast_free(entry->string_filter);
949 }
950
951 static void session_destructor(void *obj)
952 {
953 struct mansession_session *session = obj;
954 struct eventqent *eqe = session->last_ev;
955 struct ast_datastore *datastore;
956
957 /* Get rid of each of the data stores on the session */
958 while ((datastore = AST_LIST_REMOVE_HEAD(&session->datastores, entry))) {
959 /* Free the data store */
960 ast_datastore_free(datastore);
961 }
962
963 if (eqe) {
964 ast_atomic_fetchadd_int(&eqe->usecount, -1);
965 }
966 if (session->chanvars) {
967 ast_variables_destroy(session->chanvars);
968 }
969
970 if (session->includefilters) {
971 ao2_t_ref(session->includefilters, -1, "decrement ref for include container, should be last one");
972 }
973
974 if (session->excludefilters) {
975 ao2_t_ref(session->excludefilters, -1, "decrement ref for exclude container, should be last one");
976 }
977
978 ast_mutex_destroy(&session->notify_lock);
979 }
980
981 /*! \brief Allocate manager session structure and add it to the list of sessions */
982 static struct mansession_session *build_mansession(const struct ast_sockaddr *addr)
983 {
984 struct ao2_container *sessions;
985 struct mansession_session *newsession;
986
987 newsession = ao2_alloc(sizeof(*newsession), session_destructor);
988 if (!newsession) {
989 return NULL;
990 }
991
992 newsession->includefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
993 newsession->excludefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
994 if (!newsession->includefilters || !newsession->excludefilters) {
995 ao2_ref(newsession, -1);
996 return NULL;
997 }
998
999 newsession->waiting_thread = AST_PTHREADT_NULL;
1000 newsession->writetimeout = 100;
1001 newsession->send_events = -1;
1002 ast_sockaddr_copy(&newsession->addr, addr);
1003
1004 ast_mutex_init(&newsession->notify_lock);
1005
1006 sessions = ao2_global_obj_ref(mgr_sessions);
1007 if (sessions) {
1008 ao2_link(sessions, newsession);
1009 ao2_ref(sessions, -1);
1010 }
1011
1012 return newsession;
1013 }
1014
1015 static int mansession_cmp_fn(void *obj, void *arg, int flags)
1016 {
1017 struct mansession_session *s = obj;
1018 char *str = arg;
1019 return !strcasecmp(s->username, str) ? CMP_MATCH : 0;
1020 }
1021
1022 static void session_destroy(struct mansession_session *s)
1023 {
1024 struct ao2_container *sessions;
1025
1026 sessions = ao2_global_obj_ref(mgr_sessions);
1027 if (sessions) {
1028 ao2_unlink(sessions, s);
1029 ao2_ref(sessions, -1);
1030 }
1031 unref_mansession(s);
1032 }
1033
1034
1035 static int check_manager_session_inuse(const char *name)
1036 {
1037 struct ao2_container *sessions;
1038 struct mansession_session *session;
1039 int inuse = 0;
1040
1041 sessions = ao2_global_obj_ref(mgr_sessions);
1042 if (sessions) {
1043 session = ao2_find(sessions, (char *) name, 0);
1044 ao2_ref(sessions, -1);
1045 if (session) {
1046 unref_mansession(session);
1047 inuse = 1;
1048 }
1049 }
1050 return inuse;
1051 }
1052
1053
1054 /*!
1055 * lookup an entry in the list of registered users.
1056 * must be called with the list lock held.
1057 */
1058 static struct ast_manager_user *get_manager_by_name_locked(const char *name)
1059 {
1060 struct ast_manager_user *user = NULL;
1061
1062 AST_RWLIST_TRAVERSE(&users, user, list) {
1063 if (!strcasecmp(user->username, name)) {
1064 break;
1065 }
1066 }
1067
1068 return user;
1069 }
1070
1071 /*! \brief Get displayconnects config option.
1072 * \param session manager session to get parameter from.
1073 * \return displayconnects config option value.
1074 */
1075 static int manager_displayconnects(struct mansession_session *session)
1076 {
1077 struct ast_manager_user *user = NULL;
1078 int ret = 0;
1079
1080 AST_RWLIST_RDLOCK(&users);
1081 if ((user = get_manager_by_name_locked(session->username))) {
1082 ret = user->displayconnects;
1083 }
1084 AST_RWLIST_UNLOCK(&users);
1085
1086 return ret;
1087 }
1088
1089 #ifdef AST_XML_DOCS
1090 static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance);
1091 #endif
1092
1093 static char *handle_showmancmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1094 {
1095 struct manager_action *cur;
1096 struct ast_str *authority;
1097 int num;
1098 int l;
1099 const char *auth_str;
1100
1101 switch (cmd) {
1102 case CLI_INIT:
1103 e->command = "manager show command";
1104 e->usage =
1105 "Usage: manager show command <actionname> [<actionname> [<actionname> [...]]]\n"
1106 " Shows the detailed description for a specific Asterisk manager interface command.\n";
1107 return NULL;
1108 case CLI_GENERATE:
1109 l = strlen(a->word);
1110 AST_RWLIST_RDLOCK(&actions);
1111 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1112 if (!strncasecmp(a->word, cur->action, l)) {
1113 if (ast_cli_completion_add(ast_strdup(cur->action))) {
1114 break;
1115 }
1116 }
1117 }
1118 AST_RWLIST_UNLOCK(&actions);
1119 return NULL;
1120 }
1121 if (a->argc < 4) {
1122 return CLI_SHOWUSAGE;
1123 }
1124
1125 authority = ast_str_alloca(MAX_AUTH_PERM_STRING);
1126
1127 AST_RWLIST_RDLOCK(&actions);
1128 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1129 for (num = 3; num < a->argc; num++) {
1130 if (!strcasecmp(cur->action, a->argv[num])) {
1131 auth_str = authority_to_str(cur->authority, &authority);
1132
1133 #ifdef AST_XML_DOCS
1134 if (cur->docsrc == AST_XML_DOC) {
1135 char *synopsis = ast_xmldoc_printable(S_OR(cur->synopsis, "Not available"), 1);
1136 char *provided_by = ast_xmldoc_printable(S_OR(cur->provided_by, "Not available"), 1);
1137 char *since = ast_xmldoc_printable(S_OR(cur->since, "Not available"), 1);
1138 char *description = ast_xmldoc_printable(S_OR(cur->description, "Not available"), 1);
1139 char *syntax = ast_xmldoc_printable(S_OR(cur->syntax, "Not available"), 1);
1140 char *arguments = ast_xmldoc_printable(S_OR(cur->arguments, "Not available"), 1);
1141 char *privilege = ast_xmldoc_printable(S_OR(auth_str, "Not available"), 1);
1142 char *seealso = ast_xmldoc_printable(S_OR(cur->seealso, "Not available"), 1);
1143 char *responses = ast_xmldoc_printable("None", 1);
1144
1145 if (!synopsis || !provided_by || !since || !description || !syntax || !arguments
1146 || !privilege || !seealso || !responses) {
1147 ast_free(synopsis);
1148 ast_free(provided_by);
1149 ast_free(since);
1150 ast_free(description);
1151 ast_free(syntax);
1152 ast_free(arguments);
1153 ast_free(privilege);
1154 ast_free(seealso);
1155 ast_free(responses);
1156 ast_cli(a->fd, "Allocation failure.\n");
1157 AST_RWLIST_UNLOCK(&actions);
1158
1159 return CLI_FAILURE;
1160 }
1161
1162 ast_cli(a->fd, "\n"
1163 "%s -= Info about Manager Command '%s' =- %s\n\n"
1164 COLORIZE_FMT "\n"
1165 "%s\n\n"
1166 COLORIZE_FMT "\n"
1167 "%s\n\n"
1168 COLORIZE_FMT "\n"
1169 "%s\n\n"
1170 COLORIZE_FMT "\n"
1171 "%s\n\n"
1172 COLORIZE_FMT "\n"
1173 "%s\n\n"
1174 COLORIZE_FMT "\n"
1175 "%s\n\n"
1176 COLORIZE_FMT "\n"
1177 "%s\n\n"
1178 COLORIZE_FMT "\n"
1179 "%s\n\n"
1180 COLORIZE_FMT "\n",
1181 ast_term_color(COLOR_MAGENTA, 0), cur->action, ast_term_reset(),
1182 COLORIZE(COLOR_MAGENTA, 0, "[Synopsis]"), synopsis,
1183 COLORIZE(COLOR_MAGENTA, 0, "[Provided By]"), provided_by,
1184 COLORIZE(COLOR_MAGENTA, 0, "[Since]"), since,
1185 COLORIZE(COLOR_MAGENTA, 0, "[Description]"), description,
1186 COLORIZE(COLOR_MAGENTA, 0, "[Syntax]"), syntax,
1187 COLORIZE(COLOR_MAGENTA, 0, "[Arguments]"), arguments,
1188 COLORIZE(COLOR_MAGENTA, 0, "[Privilege]"), privilege,
1189 COLORIZE(COLOR_MAGENTA, 0, "[See Also]"), seealso,
1190 COLORIZE(COLOR_MAGENTA, 0, "[List Responses]")
1191 );
1192
1193 if (!cur->list_responses) {
1194 ast_cli(a->fd, "%s\n\n", responses);
1195 } else {
1196 struct ast_xml_doc_item *temp;
1197 for (temp = cur->list_responses; temp; temp = AST_LIST_NEXT(temp, next)) {
1198 ast_cli(a->fd, "Event: %s\n", temp->name);
1199 print_event_instance(a, temp);
1200 }
1201 }
1202 ast_cli(a->fd,
1203 COLORIZE_FMT "\n",
1204 COLORIZE(COLOR_MAGENTA, 0, "[End List Responses]")
1205 );
1206
1207 ast_cli(a->fd, "\n"
1208 COLORIZE_FMT "\n",
1209 COLORIZE(COLOR_MAGENTA, 0, "[Final Response]")
1210 );
1211 if (!cur->final_response) {
1212 ast_cli(a->fd, "%s\n\n", responses);
1213 } else {
1214 ast_cli(a->fd, "Event: %s\n", cur->final_response->name);
1215 print_event_instance(a, cur->final_response);
1216 }
1217 ast_cli(a->fd,
1218 COLORIZE_FMT "\n",
1219 COLORIZE(COLOR_MAGENTA, 0, "[End Final Response]")
1220 );
1221
1222 ast_free(synopsis);
1223 ast_free(provided_by);
1224 ast_free(since);
1225 ast_free(description);
1226 ast_free(syntax);
1227 ast_free(arguments);
1228 ast_free(privilege);
1229 ast_free(seealso);
1230 ast_free(responses);
1231 } else
1232 #endif
1233 {
1234 ast_cli(a->fd, "Action: %s\nSynopsis: %s\nPrivilege: %s\n%s\n",
1235 cur->action, cur->synopsis,
1236 auth_str,
1237 S_OR(cur->description, ""));
1238 }
1239 }
1240 }
1241 }
1242 AST_RWLIST_UNLOCK(&actions);
1243
1244 return CLI_SUCCESS;
1245 }
1246
1247 static char *handle_mandebug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1248 {
1249 switch (cmd) {
1250 case CLI_INIT:
1251 e->command = "manager set debug [on|off]";
1252 e->usage = "Usage: manager set debug [on|off]\n Show, enable, disable debugging of the manager code.\n";
1253 return NULL;
1254 case CLI_GENERATE:
1255 return NULL;
1256 }
1257
1258 if (a->argc == 3) {
1259 ast_cli(a->fd, "manager debug is %s\n", manager_debug? "on" : "off");
1260 } else if (a->argc == 4) {
1261 if (!strcasecmp(a->argv[3], "on")) {
1262 manager_debug = 1;
1263 } else if (!strcasecmp(a->argv[3], "off")) {
1264 manager_debug = 0;
1265 } else {
1266 return CLI_SHOWUSAGE;
1267 }
1268 }
1269 return CLI_SUCCESS;
1270 }
1271
1272 static char *handle_showmanager(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1273 {
1274 struct ast_manager_user *user = NULL;
1275 int l;
1276 struct ast_str *rauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
1277 struct ast_str *wauthority = ast_str_alloca(MAX_AUTH_PERM_STRING);
1278 struct ast_variable *v;
1279
1280 switch (cmd) {
1281 case CLI_INIT:
1282 e->command = "manager show user";
1283 e->usage =
1284 " Usage: manager show user <user>\n"
1285 " Display all information related to the manager user specified.\n";
1286 return NULL;
1287 case CLI_GENERATE:
1288 l = strlen(a->word);
1289 if (a->pos != 3) {
1290 return NULL;
1291 }
1292 AST_RWLIST_RDLOCK(&users);
1293 AST_RWLIST_TRAVERSE(&users, user, list) {
1294 if (!strncasecmp(a->word, user->username, l)) {
1295 if (ast_cli_completion_add(ast_strdup(user->username))) {
1296 break;
1297 }
1298 }
1299 }
1300 AST_RWLIST_UNLOCK(&users);
1301 return NULL;
1302 }
1303
1304 if (a->argc != 4) {
1305 return CLI_SHOWUSAGE;
1306 }
1307
1308 AST_RWLIST_RDLOCK(&users);
1309
1310 if (!(user = get_manager_by_name_locked(a->argv[3]))) {
1311 ast_cli(a->fd, "There is no manager called %s\n", a->argv[3]);
1312 AST_RWLIST_UNLOCK(&users);
1313 return CLI_SUCCESS;
1314 }
1315
1316 ast_cli(a->fd, "\n");
1317 ast_cli(a->fd,
1318 " username: %s\n"
1319 " secret: %s\n"
1320 " ACL: %s\n"
1321 " read perm: %s\n"
1322 " write perm: %s\n"
1323 " displayconnects: %s\n"
1324 "allowmultiplelogin: %s\n",
1325 S_OR(user->username, "(N/A)"),
1326 (user->secret ? "<Set>" : "(N/A)"),
1327 ((user->acl && !ast_acl_list_is_empty(user->acl)) ? "yes" : "no"),
1328 user_authority_to_str(user->readperm, &rauthority),
1329 user_authority_to_str(user->writeperm, &wauthority),
1330 (user->displayconnects ? "yes" : "no"),
1331 (user->allowmultiplelogin ? "yes" : "no"));
1332 ast_cli(a->fd, " Variables: \n");
1333 for (v = user->chanvars ; v ; v = v->next) {
1334 ast_cli(a->fd, " %s = %s\n", v->name, v->value);
1335 }
1336 if (!ast_acl_list_is_empty(user->acl)) {
1337 ast_acl_output(a->fd, user->acl, NULL);
1338 }
1339
1340 AST_RWLIST_UNLOCK(&users);
1341
1342 return CLI_SUCCESS;
1343 }
1344
1345 static char *handle_showmanagers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1346 {
1347 struct ast_manager_user *user = NULL;
1348 int count_amu = 0;
1349 switch (cmd) {
1350 case CLI_INIT:
1351 e->command = "manager show users";
1352 e->usage =
1353 "Usage: manager show users\n"
1354 " Prints a listing of all managers that are currently configured on that\n"
1355 " system.\n";
1356 return NULL;
1357 case CLI_GENERATE:
1358 return NULL;
1359 }
1360 if (a->argc != 3) {
1361 return CLI_SHOWUSAGE;
1362 }
1363
1364 AST_RWLIST_RDLOCK(&users);
1365
1366 /* If there are no users, print out something along those lines */
1367 if (AST_RWLIST_EMPTY(&users)) {
1368 ast_cli(a->fd, "There are no manager users.\n");
1369 AST_RWLIST_UNLOCK(&users);
1370 return CLI_SUCCESS;
1371 }
1372
1373 ast_cli(a->fd, "\nusername\n--------\n");
1374
1375 AST_RWLIST_TRAVERSE(&users, user, list) {
1376 ast_cli(a->fd, "%s\n", user->username);
1377 count_amu++;
1378 }
1379
1380 AST_RWLIST_UNLOCK(&users);
1381
1382 ast_cli(a->fd,"-------------------\n"
1383 "%d manager users configured.\n", count_amu);
1384 return CLI_SUCCESS;
1385 }
1386
1387 /*! \brief CLI command manager list commands */
1388 static char *handle_showmancmds(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1389 {
1390 struct manager_action *cur;
1391 int name_len = 1;
1392 int space_remaining;
1393 #define HSMC_FORMAT " %-*.*s %-.*s\n"
1394 switch (cmd) {
1395 case CLI_INIT:
1396 e->command = "manager show commands";
1397 e->usage =
1398 "Usage: manager show commands\n"
1399 " Prints a listing of all the available Asterisk manager interface commands.\n";
1400 return NULL;
1401 case CLI_GENERATE:
1402 return NULL;
1403 }
1404
1405 AST_RWLIST_RDLOCK(&actions);
1406 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1407 int incoming_len = strlen(cur->action);
1408 if (incoming_len > name_len) {
1409 name_len = incoming_len;
1410 }
1411 }
1412
1413 space_remaining = MGR_SHOW_TERMINAL_WIDTH - name_len - 4;
1414 if (space_remaining < 0) {
1415 space_remaining = 0;
1416 }
1417
1418 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "Action", space_remaining, "Synopsis");
1419 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, "------", space_remaining, "--------");
1420
1421 AST_RWLIST_TRAVERSE(&actions, cur, list) {
1422 ast_cli(a->fd, HSMC_FORMAT, name_len, name_len, cur->action, space_remaining, cur->synopsis);
1423 }
1424 AST_RWLIST_UNLOCK(&actions);
1425
1426 return CLI_SUCCESS;
1427 }
1428
1429 /*! \brief CLI command manager kick session */
1430 static char *handle_kickmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1431 {
1432 struct ao2_container *sessions;
1433 struct mansession_session *session;
1434 struct ao2_iterator i;
1435 int fd = -1;
1436 int found = 0;
1437
1438 switch (cmd) {
1439 case CLI_INIT:
1440 e->command = "manager kick session";
1441 e->usage =
1442 "Usage: manager kick session <file descriptor>\n"
1443 " Kick an active Asterisk Manager Interface session\n";
1444 return NULL;
1445 case CLI_GENERATE:
1446 return NULL;
1447 }
1448
1449 if (a->argc != 4) {
1450 return CLI_SHOWUSAGE;
1451 }
1452
1453 fd = atoi(a->argv[3]);
1454 if (fd <= 0) { /* STDOUT won't be a valid AMI fd either */
1455 ast_cli(a->fd, "Invalid AMI file descriptor: %s\n", a->argv[3]);
1456 return CLI_FAILURE;
1457 }
1458
1459 sessions = ao2_global_obj_ref(mgr_sessions);
1460 if (sessions) {
1461 i = ao2_iterator_init(sessions, 0);
1462 ao2_ref(sessions, -1);
1463 while ((session = ao2_iterator_next(&i))) {
1464 ao2_lock(session);
1465 if (session->stream) {
1466 if (ast_iostream_get_fd(session->stream) == fd) {
1467 if (session->kicked) {
1468 ast_cli(a->fd, "Manager session using file descriptor %d has already been kicked\n", fd);
1469 ao2_unlock(session);
1470 unref_mansession(session);
1471 break;
1472 }
1473 fd = ast_iostream_get_fd(session->stream);
1474 found = fd;
1475 ast_cli(a->fd, "Kicking manager session connected using file descriptor %d\n", fd);
1476 ast_mutex_lock(&session->notify_lock);
1477 session->kicked = 1;
1478 if (session->waiting_thread != AST_PTHREADT_NULL) {
1479 pthread_kill(session->waiting_thread, SIGURG);
1480 }
1481 ast_mutex_unlock(&session->notify_lock);
1482 ao2_unlock(session);
1483 unref_mansession(session);
1484 break;
1485 }
1486 }
1487 ao2_unlock(session);
1488 unref_mansession(session);
1489 }
1490 ao2_iterator_destroy(&i);
1491 }
1492
1493 if (!found) {
1494 ast_cli(a->fd, "No manager session found using file descriptor %d\n", fd);
1495 }
1496 return CLI_SUCCESS;
1497 }
1498
1499 /*! \brief CLI command manager list connected */
1500 static char *handle_showmanconn(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1501 {
1502 struct ao2_container *sessions;
1503 struct mansession_session *session;
1504 time_t now = time(NULL);
1505 #define HSMCONN_FORMAT1 " %-15.15s %-55.55s %-10.10s %-10.10s %-8.8s %-8.8s %-10.10s %-10.10s\n"
1506 #define HSMCONN_FORMAT2 " %-15.15s %-55.55s %-10d %-10d %-8d %-8d %-10.10d %-10.10d\n"
1507 int count = 0;
1508 struct ao2_iterator i;
1509
1510 switch (cmd) {
1511 case CLI_INIT:
1512 e->command = "manager show connected";
1513 e->usage =
1514 "Usage: manager show connected\n"
1515 " Prints a listing of the users that are currently connected to the\n"
1516 "Asterisk manager interface.\n";
1517 return NULL;
1518 case CLI_GENERATE:
1519 return NULL;
1520 }
1521
1522 ast_cli(a->fd, HSMCONN_FORMAT1, "Username", "IP Address", "Start", "Elapsed", "FileDes", "HttpCnt", "ReadPerms", "WritePerms");
1523
1524 sessions = ao2_global_obj_ref(mgr_sessions);
1525 if (sessions) {
1526 i = ao2_iterator_init(sessions, 0);
1527 ao2_ref(sessions, -1);
1528 while ((session = ao2_iterator_next(&i))) {
1529 ao2_lock(session);
1530 ast_cli(a->fd, HSMCONN_FORMAT2, session->username,
1531 ast_sockaddr_stringify_addr(&session->addr),
1532 (int) (session->sessionstart),
1533 (int) (now - session->sessionstart),
1534 session->stream ? ast_iostream_get_fd(session->stream) : -1,
1535 session->inuse,
1536 session->readperm,
1537 session->writeperm);
1538 count++;
1539 ao2_unlock(session);
1540 unref_mansession(session);
1541 }
1542 ao2_iterator_destroy(&i);
1543 }
1544 ast_cli(a->fd, "%d users connected.\n", count);
1545
1546 return CLI_SUCCESS;
1547 }
1548
1549 /*! \brief CLI command manager list eventq */
1550 /* Should change to "manager show connected" */
1551 static char *handle_showmaneventq(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1552 {
1553 struct eventqent *s;
1554 switch (cmd) {
1555 case CLI_INIT:
1556 e->command = "manager show eventq";
1557 e->usage =
1558 "Usage: manager show eventq\n"
1559 " Prints a listing of all events pending in the Asterisk manger\n"
1560 "event queue.\n";
1561 return NULL;
1562 case CLI_GENERATE:
1563 return NULL;
1564 }
1565 AST_RWLIST_RDLOCK(&all_events);
1566 AST_RWLIST_TRAVERSE(&all_events, s, eq_next) {
1567 ast_cli(a->fd, "Usecount: %d\n", s->usecount);
1568 ast_cli(a->fd, "Category: %d\n", s->category);
1569 ast_cli(a->fd, "Event:\n%s", s->eventdata);
1570 }
1571 AST_RWLIST_UNLOCK(&all_events);
1572
1573 return CLI_SUCCESS;
1574 }
1575
1576 static int reload_module(void);
1577
1578 /*! \brief CLI command manager reload */
1579 static char *handle_manager_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1580 {
1581 switch (cmd) {
1582 case CLI_INIT:
1583 e->command = "manager reload";
1584 e->usage =
1585 "Usage: manager reload\n"
1586 " Reloads the manager configuration.\n";
1587 return NULL;
1588 case CLI_GENERATE:
1589 return NULL;
1590 }
1591 if (a->argc > 2) {
1592 return CLI_SHOWUSAGE;
1593 }
1594 reload_module();
1595 return CLI_SUCCESS;
1596 }
1597
1598 static struct eventqent *advance_event(struct eventqent *e)
1599 {
1600 struct eventqent *next;
1601
1602 AST_RWLIST_RDLOCK(&all_events);
1603 if ((next = AST_RWLIST_NEXT(e, eq_next))) {
1604 ast_atomic_fetchadd_int(&next->usecount, 1);
1605 ast_atomic_fetchadd_int(&e->usecount, -1);
1606 }
1607 AST_RWLIST_UNLOCK(&all_events);
1608 return next;
1609 }
1610
1611 #define GET_HEADER_FIRST_MATCH 0
1612 #define GET_HEADER_LAST_MATCH 1
1613 #define GET_HEADER_SKIP_EMPTY 2
1614
1615 /*!
1616 * \brief Return a matching header value.
1617 *
1618 * \details
1619 * Generic function to return either the first or the last
1620 * matching header from a list of variables, possibly skipping
1621 * empty strings.
1622 *
1623 * \note At the moment there is only one use of this function in
1624 * this file, so we make it static.
1625 *
1626 * \note Never returns NULL.
1627 */
1628 static const char *__astman_get_header(const struct message *m, char *var, int mode)
1629 {
1630 int x, l = strlen(var);
1631 const char *result = "";
1632
1633 if (!m) {
1634 return result;
1635 }
1636
1637 for (x = 0; x < m->hdrcount; x++) {
1638 const char *h = m->headers[x];
1639 if (!strncasecmp(var, h, l) && h[l] == ':') {
1640 const char *value = h + l + 1;
1641 value = ast_skip_blanks(value); /* ignore leading spaces in the value */
1642 /* found a potential candidate */
1643 if ((mode & GET_HEADER_SKIP_EMPTY) && ast_strlen_zero(value)) {
1644 continue; /* not interesting */
1645 }
1646 if (mode & GET_HEADER_LAST_MATCH) {
1647 result = value; /* record the last match so far */
1648 } else {
1649 return value;
1650 }
1651 }
1652 }
1653
1654 return result;
1655 }
1656
1657 /*!
1658 * \brief Return the first matching variable from an array.
1659 *
1660 * \note This is the legacy function and is implemented in
1661 * therms of __astman_get_header().
1662 *
1663 * \note Never returns NULL.
1664 */
1665 const char *astman_get_header(const struct message *m, char *var)
1666 {
1667 return __astman_get_header(m, var, GET_HEADER_FIRST_MATCH);
1668 }
1669
1670 /*!
1671 * \brief Append additional headers into the message structure from params.
1672 *
1673 * \note You likely want to initialize m->hdrcount to 0 before calling this.
1674 */
1675 static void astman_append_headers(struct message *m, const struct ast_variable *params)
1676 {
1677 const struct ast_variable *v;
1678
1679 for (v = params; v && m->hdrcount < ARRAY_LEN(m->headers); v = v->next) {
1680 if (ast_asprintf((char**)&m->headers[m->hdrcount], "%s: %s", v->name, v->value) > -1) {
1681 ++m->hdrcount;
1682 }
1683 }
1684 }
1685
1686 /*!
1687 * \brief Free headers inside message structure, but not the message structure itself.
1688 */
1689 static void astman_free_headers(struct message *m)
1690 {
1691 while (m->hdrcount) {
1692 --m->hdrcount;
1693 ast_free((void *) m->headers[m->hdrcount]);
1694 m->headers[m->hdrcount] = NULL;
1695 }
1696 }
1697
1698 /*!
1699 * \internal
1700 * \brief Process one "Variable:" header value string.
1701 *
1702 * \param head Current list of AMI variables to get new values added.
1703 * \param hdr_val Header value string to process.
1704 *
1705 * \return New variable list head.
1706 */
1707 static struct ast_variable *man_do_variable_value(struct ast_variable *head, const char *hdr_val)
1708 {
1709 char *parse;
1710 AST_DECLARE_APP_ARGS(args,
1711 AST_APP_ARG(vars)[64];
1712 );
1713
1714 hdr_val = ast_skip_blanks(hdr_val); /* ignore leading spaces in the value */
1715 parse = ast_strdupa(hdr_val);
1716
1717 /* Break the header value string into name=val pair items. */
1718 AST_STANDARD_APP_ARGS(args, parse);
1719 if (args.argc) {
1720 int y;
1721
1722 /* Process each name=val pair item. */
1723 for (y = 0; y < args.argc; y++) {
1724 struct ast_variable *cur;
1725 char *var;
1726 char *val;
1727
1728 if (!args.vars[y]) {
1729 continue;
1730 }
1731 var = val = args.vars[y];
1732 strsep(&val, "=");
1733
1734 /* XXX We may wish to trim whitespace from the strings. */
1735 if (!val || ast_strlen_zero(var)) {
1736 continue;
1737 }
1738
1739 /* Create new variable list node and prepend it to the list. */
1740 cur = ast_variable_new(var, val, "");
1741 if (cur) {
1742 cur->next = head;
1743 head = cur;
1744 }
1745 }
1746 }
1747
1748 return head;
1749 }
1750
1751 struct ast_variable *astman_get_variables(const struct message *m)
1752 {
1753 return astman_get_variables_order(m, ORDER_REVERSE);
1754 }
1755
1756 struct ast_variable *astman_get_variables_order(const struct message *m,
1757 enum variable_orders order)
1758 {
1759 int varlen;
1760 int x;
1761 struct ast_variable *head = NULL;
1762
1763 static const char var_hdr[] = "Variable:";
1764
1765 /* Process all "Variable:" headers. */
1766 varlen = strlen(var_hdr);
1767 for (x = 0; x < m->hdrcount; x++) {
1768 if (strncasecmp(var_hdr, m->headers[x], varlen)) {
1769 continue;
1770 }
1771 head = man_do_variable_value(head, m->headers[x] + varlen);
1772 }
1773
1774 if (order == ORDER_NATURAL) {
1775 head = ast_variables_reverse(head);
1776 }
1777
1778 return head;
1779 }
1780
1781 /*! \brief access for hooks to send action messages to ami */
1782 int ast_hook_send_action(struct manager_custom_hook *hook, const char *msg)
1783 {
1784 const char *action;
1785 int ret = 0;
1786 struct manager_action *act_found;
1787 struct mansession s = {.session = NULL, };
1788 struct message m = { 0 };
1789 char *dup_str;
1790 char *src;
1791 int x = 0;
1792 int curlen;
1793
1794 if (hook == NULL) {
1795 return -1;
1796 }
1797
1798 /* Create our own copy of the AMI action msg string. */
1799 src = dup_str = ast_strdup(msg);
1800 if (!dup_str) {
1801 return -1;
1802 }
1803
1804 /* convert msg string to message struct */
1805 curlen = strlen(src);
1806 for (x = 0; x < curlen; x++) {
1807 int cr; /* set if we have \r */
1808 if (src[x] == '\r' && x+1 < curlen && src[x+1] == '\n')
1809 cr = 2; /* Found. Update length to include \r\n */
1810 else if (src[x] == '\n')
1811 cr = 1; /* also accept \n only */
1812 else
1813 continue;
1814 /* don't keep empty lines */
1815 if (x && m.hdrcount < ARRAY_LEN(m.headers)) {
1816 /* ... but trim \r\n and terminate the header string */
1817 src[x] = '\0';
1818 m.headers[m.hdrcount++] = src;
1819 }
1820 x += cr;
1821 curlen -= x; /* remaining size */
1822 src += x; /* update pointer */
1823 x = -1; /* reset loop */
1824 }
1825
1826 action = astman_get_header(&m, "Action");
1827
1828 do {
1829 if (!strcasecmp(action, "login")) {
1830 break;
1831 }
1832
1833 act_found = action_find(action);
1834 if (!act_found) {
1835 break;
1836 }
1837
1838 /*
1839 * we have to simulate a session for this action request
1840 * to be able to pass it down for processing
1841 * This is necessary to meet the previous design of manager.c
1842 */
1843 s.hook = hook;
1844
1845 ret = -1;
1846 ao2_lock(act_found);
1847 if (act_found->registered && act_found->func) {
1848 struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
1849
1850 ao2_unlock(act_found);
1851 /* If the action is in a module it must be running. */
1852 if (!act_found->module || mod_ref) {
1853 ret = act_found->func(&s, &m);
1854 ast_module_unref(mod_ref);
1855 }
1856 } else {
1857 ao2_unlock(act_found);
1858 }
1859 ao2_t_ref(act_found, -1, "done with found action object");
1860 } while (0);
1861
1862 ast_free(dup_str);
1863 return ret;
1864 }
1865
1866 /*!
1867 * helper function to send a string to the socket.
1868 * Return -1 on error (e.g. buffer full).
1869 */
1870 static int send_string(struct mansession *s, char *string)
1871 {
1872 struct ast_iostream *stream;
1873 int len, res;
1874
1875 /* It's a result from one of the hook's action invocation */
1876 if (s->hook) {
1877 /*
1878 * to send responses, we're using the same function
1879 * as for receiving events. We call the event "HookResponse"
1880 */
1881 s->hook->helper(EVENT_FLAG_HOOKRESPONSE, "HookResponse", string);
1882 return 0;
1883 }
1884
1885 stream = s->stream ? s->stream : s->session->stream;
1886
1887 len = strlen(string);
1888 ast_iostream_set_timeout_inactivity(stream, s->session->writetimeout);
1889 res = ast_iostream_write(stream, string, len);
1890 ast_iostream_set_timeout_disable(stream);
1891
1892 if (res < len) {
1893 s->write_error = 1;
1894 }
1895
1896 return res;
1897 }
1898
1899 /*!
1900 * \brief thread local buffer for astman_append
1901 *
1902 * \note This can not be defined within the astman_append() function
1903 * because it declares a couple of functions that get used to
1904 * initialize the thread local storage key.
1905 */
1906 AST_THREADSTORAGE(astman_append_buf);
1907
1908 AST_THREADSTORAGE(userevent_buf);
1909
1910 /*! \brief initial allocated size for the astman_append_buf and astman_send_*_va */
1911 #define ASTMAN_APPEND_BUF_INITSIZE 256
1912
1913 static void astman_flush(struct mansession *s, struct ast_str *buf)
1914 {
1915 if (s->hook || (s->tcptls_session && s->tcptls_session->stream)) {
1916 send_string(s, ast_str_buffer(buf));
1917 } else {
1918 ast_verbose("No connection stream in astman_append, should not happen\n");
1919 }
1920 }
1921
1922 /*!
1923 * utility functions for creating AMI replies
1924 */
1925 void astman_append(struct mansession *s, const char *fmt, ...)
1926 {
1927 int res;
1928 va_list ap;
1929 struct ast_str *buf;
1930
1931 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
1932 return;
1933 }
1934
1935 va_start(ap, fmt);
1936 res = ast_str_set_va(&buf, 0, fmt, ap);
1937 va_end(ap);
1938 if (res == AST_DYNSTR_BUILD_FAILED) {
1939 return;
1940 }
1941
1942 if (s->hook || (s->tcptls_session != NULL && s->tcptls_session->stream != NULL)) {
1943 send_string(s, ast_str_buffer(buf));
1944 } else {
1945 ast_verbose("No connection stream in astman_append, should not happen\n");
1946 }
1947 }
1948
1949 /*! \note NOTE: XXX this comment is unclear and possibly wrong.
1950 Callers of astman_send_error(), astman_send_response() or astman_send_ack() must EITHER
1951 hold the session lock _or_ be running in an action callback (in which case s->session->busy will
1952 be non-zero). In either of these cases, there is no need to lock-protect the session's
1953 fd, since no other output will be sent (events will be queued), and no input will
1954 be read until either the current action finishes or get_input() obtains the session
1955 lock.
1956 */
1957
1958 /*! \todo XXX MSG_MOREDATA should go to a header file. */
1959 #define MSG_MOREDATA ((char *)astman_send_response)
1960
1961 /*! \brief send a response with an optional message,
1962 * and terminate it with an empty line.
1963 * m is used only to grab the 'ActionID' field.
1964 *
1965 * Use the explicit constant MSG_MOREDATA to remove the empty line.
1966 * XXX MSG_MOREDATA should go to a header file.
1967 */
1968 static void astman_send_response_full(struct mansession *s, const struct message *m, char *resp, char *msg, char *listflag)
1969 {
1970 const char *id = astman_get_header(m, "ActionID");
1971 struct ast_str *buf;
1972
1973 buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE);
1974 if (!buf) {
1975 return;
1976 }
1977
1978 ast_str_set(&buf, 0, "Response: %s\r\n", resp);
1979
1980 if (!ast_strlen_zero(id)) {
1981 ast_str_append(&buf, 0, "ActionID: %s\r\n", id);
1982 }
1983
1984 if (listflag) {
1985 /* Start, complete, cancelled */
1986 ast_str_append(&buf, 0, "EventList: %s\r\n", listflag);
1987 }
1988
1989 if (msg != MSG_MOREDATA) {
1990 if (msg) {
1991 ast_str_append(&buf, 0, "Message: %s\r\n", msg);
1992 }
1993 ast_str_append(&buf, 0, "\r\n");
1994 }
1995
1996 astman_flush(s, buf);
1997 }
1998
1999 void astman_send_response(struct mansession *s, const struct message *m, char *resp, char *msg)
2000 {
2001 astman_send_response_full(s, m, resp, msg, NULL);
2002 }
2003
2004 void astman_send_error(struct mansession *s, const struct message *m, char *error)
2005 {
2006 astman_send_response_full(s, m, "Error", error, NULL);
2007 }
2008
2009 void astman_send_error_va(struct mansession *s, const struct message *m, const char *fmt, ...)
2010 {
2011 int res;
2012 va_list ap;
2013 struct ast_str *buf;
2014 char *msg;
2015
2016 if (!(buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE))) {
2017 return;
2018 }
2019
2020 va_start(ap, fmt);
2021 res = ast_str_set_va(&buf, 0, fmt, ap);
2022 va_end(ap);
2023 if (res == AST_DYNSTR_BUILD_FAILED) {
2024 return;
2025 }
2026
2027 /* astman_append will use the same underlying buffer, so copy the message out
2028 * before sending the response */
2029 msg = ast_str_buffer(buf);
2030 if (msg) {
2031 msg = ast_strdupa(msg);
2032 }
2033 astman_send_response_full(s, m, "Error", msg, NULL);
2034 }
2035
2036 void astman_send_ack(struct mansession *s, const struct message *m, char *msg)
2037 {
2038 astman_send_response_full(s, m, "Success", msg, NULL);
2039 }
2040
2041 static void astman_start_ack(struct mansession *s, const struct message *m)
2042 {
2043 astman_send_response_full(s, m, "Success", MSG_MOREDATA, NULL);
2044 }
2045
2046 void astman_send_listack(struct mansession *s, const struct message *m, char *msg, char *listflag)
2047 {
2048 astman_send_response_full(s, m, "Success", msg, listflag);
2049 }
2050
2051 static struct ast_str *astman_send_list_complete_start_common(struct mansession *s, const struct message *m, const char *event_name, int count)
2052 {
2053 const char *id = astman_get_header(m, "ActionID");
2054 struct ast_str *buf;
2055
2056 buf = ast_str_thread_get(&astman_append_buf, ASTMAN_APPEND_BUF_INITSIZE);
2057 if (!buf) {
2058 return NULL;
2059 }
2060
2061 ast_str_set(&buf, 0, "Event: %s\r\n", event_name);
2062 if (!ast_strlen_zero(id)) {
2063 ast_str_append(&buf, 0, "ActionID: %s\r\n", id);
2064 }
2065 ast_str_append(&buf, 0,
2066 "EventList: Complete\r\n"
2067 "ListItems: %d\r\n",
2068 count);
2069
2070 return buf;
2071 }
2072
2073 static void astman_send_list_complete(struct mansession *s, const struct message *m, const char *event_name, int count)
2074 {
2075 struct ast_str *buf = astman_send_list_complete_start_common(s, m, event_name, count);
2076 if (buf) {
2077 ast_str_append(&buf, 0, "\r\n");
2078 astman_flush(s, buf);
2079 }
2080 }
2081
2082 void astman_send_list_complete_start(struct mansession *s, const struct message *m, const char *event_name, int count)
2083 {
2084 struct ast_str *buf = astman_send_list_complete_start_common(s, m, event_name, count);
2085 if (buf) {
2086 astman_flush(s, buf);
2087 }
2088 }
2089
2090 void astman_send_list_complete_end(struct mansession *s)
2091 {
2092 astman_append(s, "\r\n");
2093 }
2094
2095 /*! \brief Lock the 'mansession' structure. */
2096 static void mansession_lock(struct mansession *s)
2097 {
2098 ast_mutex_lock(&s->lock);
2099 }
2100
2101 /*! \brief Unlock the 'mansession' structure. */
2102 static void mansession_unlock(struct mansession *s)
2103 {
2104 ast_mutex_unlock(&s->lock);
2105 }
2106
2107 /*! \brief
2108 Rather than braindead on,off this now can also accept a specific int mask value
2109 or a ',' delim list of mask strings (the same as manager.conf) -anthm
2110 */
2111 static int set_eventmask(struct mansession *s, const char *eventmask)
2112 {
2113 int maskint = strings_to_mask(eventmask);
2114
2115 ao2_lock(s->session);
2116 if (maskint >= 0) {
2117 s->session->send_events = maskint;
2118 }
2119 ao2_unlock(s->session);
2120
2121 return maskint;
2122 }
2123
2124 static enum ast_transport mansession_get_transport(const struct mansession *s)
2125 {
2126 return s->tcptls_session->parent->tls_cfg ? AST_TRANSPORT_TLS :
2127 AST_TRANSPORT_TCP;
2128 }
2129
2130 static void report_invalid_user(const struct mansession *s, const char *username)
2131 {
2132 char session_id[32];
2133 struct ast_security_event_inval_acct_id inval_acct_id = {
2134 .common.event_type = AST_SECURITY_EVENT_INVAL_ACCT_ID,
2135 .common.version = AST_SECURITY_EVENT_INVAL_ACCT_ID_VERSION,
2136 .common.service = "AMI",
2137 .common.account_id = username,
2138 .common.session_tv = &s->session->sessionstart_tv,
2139 .common.local_addr = {
2140 .addr = &s->tcptls_session->parent->local_address,
2141 .transport = mansession_get_transport(s),
2142 },
2143 .common.remote_addr = {
2144 .addr = &s->session->addr,
2145 .transport = mansession_get_transport(s),
2146 },
2147 .common.session_id = session_id,
2148 };
2149
2150 snprintf(session_id, sizeof(session_id), "%p", s);
2151
2152 ast_security_event_report(AST_SEC_EVT(&inval_acct_id));
2153 }
2154
2155 static void report_failed_acl(const struct mansession *s, const char *username)
2156 {
2157 char session_id[32];
2158 struct ast_security_event_failed_acl failed_acl_event = {
2159 .common.event_type = AST_SECURITY_EVENT_FAILED_ACL,
2160 .common.version = AST_SECURITY_EVENT_FAILED_ACL_VERSION,
2161 .common.service = "AMI",
2162 .common.account_id = username,
2163 .common.session_tv = &s->session->sessionstart_tv,
2164 .common.local_addr = {
2165 .addr = &s->tcptls_session->parent->local_address,
2166 .transport = mansession_get_transport(s),
2167 },
2168 .common.remote_addr = {
2169 .addr = &s->session->addr,
2170 .transport = mansession_get_transport(s),
2171 },
2172 .common.session_id = session_id,
2173 };
2174
2175 snprintf(session_id, sizeof(session_id), "%p", s->session);
2176
2177 ast_security_event_report(AST_SEC_EVT(&failed_acl_event));
2178 }
2179
2180 static void report_inval_password(const struct mansession *s, const char *username)
2181 {
2182 char session_id[32];
2183 struct ast_security_event_inval_password inval_password = {
2184 .common.event_type = AST_SECURITY_EVENT_INVAL_PASSWORD,
2185 .common.version = AST_SECURITY_EVENT_INVAL_PASSWORD_VERSION,
2186 .common.service = "AMI",
2187 .common.account_id = username,
2188 .common.session_tv = &s->session->sessionstart_tv,
2189 .common.local_addr = {
2190 .addr = &s->tcptls_session->parent->local_address,
2191 .transport = mansession_get_transport(s),
2192 },
2193 .common.remote_addr = {
2194 .addr = &s->session->addr,
2195 .transport = mansession_get_transport(s),
2196 },
2197 .common.session_id = session_id,
2198 };
2199
2200 snprintf(session_id, sizeof(session_id), "%p", s->session);
2201
2202 ast_security_event_report(AST_SEC_EVT(&inval_password));
2203 }
2204
2205 static void report_auth_success(const struct mansession *s)
2206 {
2207 char session_id[32];
2208 struct ast_security_event_successful_auth successful_auth = {
2209 .common.event_type = AST_SECURITY_EVENT_SUCCESSFUL_AUTH,
2210 .common.version = AST_SECURITY_EVENT_SUCCESSFUL_AUTH_VERSION,
2211 .common.service = "AMI",
2212 .common.account_id = s->session->username,
2213 .common.session_tv = &s->session->sessionstart_tv,
2214 .common.local_addr = {
2215 .addr = &s->tcptls_session->parent->local_address,
2216 .transport = mansession_get_transport(s),
2217 },
2218 .common.remote_addr = {
2219 .addr = &s->session->addr,
2220 .transport = mansession_get_transport(s),
2221 },
2222 .common.session_id = session_id,
2223 };
2224
2225 snprintf(session_id, sizeof(session_id), "%p", s->session);
2226
2227 ast_security_event_report(AST_SEC_EVT(&successful_auth));
2228 }
2229
2230 static void report_req_not_allowed(const struct mansession *s, const char *action)
2231 {
2232 char session_id[32];
2233 char request_type[64];
2234 struct ast_security_event_req_not_allowed req_not_allowed = {
2235 .common.event_type = AST_SECURITY_EVENT_REQ_NOT_ALLOWED,
2236 .common.version = AST_SECURITY_EVENT_REQ_NOT_ALLOWED_VERSION,
2237 .common.service = "AMI",
2238 .common.account_id = s->session->username,
2239 .common.session_tv = &s->session->sessionstart_tv,
2240 .common.local_addr = {
2241 .addr = &s->tcptls_session->parent->local_address,
2242 .transport = mansession_get_transport(s),
2243 },
2244 .common.remote_addr = {
2245 .addr = &s->session->addr,
2246 .transport = mansession_get_transport(s),
2247 },
2248 .common.session_id = session_id,
2249
2250 .request_type = request_type,
2251 };
2252
2253 snprintf(session_id, sizeof(session_id), "%p", s->session);
2254 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2255
2256 ast_security_event_report(AST_SEC_EVT(&req_not_allowed));
2257 }
2258
2259 static void report_req_bad_format(const struct mansession *s, const char *action)
2260 {
2261 char session_id[32];
2262 char request_type[64];
2263 struct ast_security_event_req_bad_format req_bad_format = {
2264 .common.event_type = AST_SECURITY_EVENT_REQ_BAD_FORMAT,
2265 .common.version = AST_SECURITY_EVENT_REQ_BAD_FORMAT_VERSION,
2266 .common.service = "AMI",
2267 .common.account_id = s->session->username,
2268 .common.session_tv = &s->session->sessionstart_tv,
2269 .common.local_addr = {
2270 .addr = &s->tcptls_session->parent->local_address,
2271 .transport = mansession_get_transport(s),
2272 },
2273 .common.remote_addr = {
2274 .addr = &s->session->addr,
2275 .transport = mansession_get_transport(s),
2276 },
2277 .common.session_id = session_id,
2278
2279 .request_type = request_type,
2280 };
2281
2282 snprintf(session_id, sizeof(session_id), "%p", s->session);
2283 snprintf(request_type, sizeof(request_type), "Action: %s", action);
2284
2285 ast_security_event_report(AST_SEC_EVT(&req_bad_format));
2286 }
2287
2288 static void report_failed_challenge_response(const struct mansession *s,
2289 const char *response, const char *expected_response)
2290 {
2291 char session_id[32];
2292 struct ast_security_event_chal_resp_failed chal_resp_failed = {
2293 .common.event_type = AST_SECURITY_EVENT_CHAL_RESP_FAILED,
2294 .common.version = AST_SECURITY_EVENT_CHAL_RESP_FAILED_VERSION,
2295 .common.service = "AMI",
2296 .common.account_id = s->session->username,
2297 .common.session_tv = &s->session->sessionstart_tv,
2298 .common.local_addr = {
2299 .addr = &s->tcptls_session->parent->local_address,
2300 .transport = mansession_get_transport(s),
2301 },
2302 .common.remote_addr = {
2303 .addr = &s->session->addr,
2304 .transport = mansession_get_transport(s),
2305 },
2306 .common.session_id = session_id,
2307
2308 .challenge = s->session->challenge,
2309 .response = response,
2310 .expected_response = expected_response,
2311 };
2312
2313 snprintf(session_id, sizeof(session_id), "%p", s->session);
2314
2315 ast_security_event_report(AST_SEC_EVT(&chal_resp_failed));
2316 }
2317
2318 static void report_session_limit(const struct mansession *s)
2319 {
2320 char session_id[32];
2321 struct ast_security_event_session_limit session_limit = {
2322 .common.event_type = AST_SECURITY_EVENT_SESSION_LIMIT,
2323 .common.version = AST_SECURITY_EVENT_SESSION_LIMIT_VERSION,
2324 .common.service = "AMI",
2325 .common.account_id = s->session->username,
2326 .common.session_tv = &s->session->sessionstart_tv,
2327 .common.local_addr = {
2328 .addr = &s->tcptls_session->parent->local_address,
2329 .transport = mansession_get_transport(s),
2330 },
2331 .common.remote_addr = {
2332 .addr = &s->session->addr,
2333 .transport = mansession_get_transport(s),
2334 },
2335 .common.session_id = session_id,
2336 };
2337
2338 snprintf(session_id, sizeof(session_id), "%p", s->session);
2339
2340 ast_security_event_report(AST_SEC_EVT(&session_limit));
2341 }
2342
2343 /*
2344 * Here we start with action_ handlers for AMI actions,
2345 * and the internal functions used by them.
2346 * Generally, the handlers are called action_foo()
2347 */
2348
2349 /* helper function for action_login() */
2350 static int authenticate(struct mansession *s, const struct message *m)
2351 {
2352 const char *username = astman_get_header(m, "Username");
2353 const char *password = astman_get_header(m, "Secret");
2354 int error = -1;
2355 struct ast_manager_user *user = NULL;
2356 regex_t *regex_filter;
2357 struct ao2_iterator filter_iter;
2358
2359 if (ast_strlen_zero(username)) { /* missing username */
2360 return -1;
2361 }
2362
2363 /* locate user in locked state */
2364 AST_RWLIST_WRLOCK(&users);
2365
2366 if (!(user = get_manager_by_name_locked(username))) {
2367 report_invalid_user(s, username);
2368 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2369 } else if (user->acl && (ast_apply_acl(user->acl, &s->session->addr, "Manager User ACL: ") == AST_SENSE_DENY)) {
2370 report_failed_acl(s, username);
2371 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2372 } else if (!strcasecmp(astman_get_header(m, "AuthType"), "MD5")) {
2373 const char *key = astman_get_header(m, "Key");
2374 if (!ast_strlen_zero(key) && !ast_strlen_zero(s->session->challenge) && user->secret) {
2375 int x;
2376 int len = 0;
2377 char md5key[256] = "";
2378 struct MD5Context md5;
2379 unsigned char digest[16];
2380
2381 MD5Init(&md5);
2382 MD5Update(&md5, (unsigned char *) s->session->challenge, strlen(s->session->challenge));
2383 MD5Update(&md5, (unsigned char *) user->secret, strlen(user->secret));
2384 MD5Final(digest, &md5);
2385 for (x = 0; x < 16; x++)
2386 len += sprintf(md5key + len, "%02hhx", digest[x]);
2387 if (!strcmp(md5key, key)) {
2388 error = 0;
2389 } else {
2390 report_failed_challenge_response(s, key, md5key);
2391 }
2392 } else {
2393 ast_debug(1, "MD5 authentication is not possible. challenge: '%s'\n",
2394 S_OR(s->session->challenge, ""));
2395 }
2396 } else if (user->secret) {
2397 if (!strcmp(password, user->secret)) {
2398 error = 0;
2399 } else {
2400 report_inval_password(s, username);
2401 }
2402 }
2403
2404 if (error) {
2405 ast_log(LOG_NOTICE, "%s failed to authenticate as '%s'\n", ast_sockaddr_stringify_addr(&s->session->addr), username);
2406 AST_RWLIST_UNLOCK(&users);
2407 return -1;
2408 }
2409
2410 /* auth complete */
2411
2412 /* All of the user parameters are copied to the session so that in the event
2413 * of a reload and a configuration change, the session parameters are not
2414 * changed. */
2415 ast_copy_string(s->session->username, username, sizeof(s->session->username));
2416 s->session->readperm = user->readperm;
2417 s->session->writeperm = user->writeperm;
2418 s->session->writetimeout = user->writetimeout;
2419 if (user->chanvars) {
2420 s->session->chanvars = ast_variables_dup(user->chanvars);
2421 }
2422
2423 filter_iter = ao2_iterator_init(user->includefilters, 0);
2424 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2425 ao2_t_link(s->session->includefilters, regex_filter, "add include user filter to session");
2426 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2427 }
2428 ao2_iterator_destroy(&filter_iter);
2429
2430 filter_iter = ao2_iterator_init(user->excludefilters, 0);
2431 while ((regex_filter = ao2_iterator_next(&filter_iter))) {
2432 ao2_t_link(s->session->excludefilters, regex_filter, "add exclude user filter to session");
2433 ao2_t_ref(regex_filter, -1, "remove iterator ref");
2434 }
2435 ao2_iterator_destroy(&filter_iter);
2436
2437 s->session->sessionstart = time(NULL);
2438 s->session->sessionstart_tv = ast_tvnow();
2439 set_eventmask(s, astman_get_header(m, "Events"));
2440
2441 report_auth_success(s);
2442
2443 AST_RWLIST_UNLOCK(&users);
2444 return 0;
2445 }
2446
2447 static int action_ping(struct mansession *s, const struct message *m)
2448 {
2449 const char *actionid = astman_get_header(m, "ActionID");
2450 struct timeval now = ast_tvnow();
2451
2452 astman_append(s, "Response: Success\r\n");
2453 if (!ast_strlen_zero(actionid)){
2454 astman_append(s, "ActionID: %s\r\n", actionid);
2455 }
2456 astman_append(
2457 s,
2458 "Ping: Pong\r\n"
2459 "Timestamp: %ld.%06lu\r\n"
2460 "\r\n",
2461 (long) now.tv_sec, (unsigned long) now.tv_usec);
2462 return 0;
2463 }
2464
2465 void astman_live_dangerously(int new_live_dangerously)
2466 {
2467 if (new_live_dangerously && !live_dangerously)
2468 {
2469 ast_log(LOG_WARNING, "Manager Configuration load protection disabled.\n");
2470 }
2471
2472 if (!new_live_dangerously && live_dangerously)
2473 {
2474 ast_log(LOG_NOTICE, "Manager Configuration load protection enabled.\n");
2475 }
2476 live_dangerously = new_live_dangerously;
2477 }
2478
2479 /**
2480 * \brief Check if a file is restricted or not
2481 *
2482 * \return 0 on success
2483 * \return 1 on restricted file
2484 * \return -1 on failure
2485 */
2486 static int is_restricted_file(const char *filename)
2487 {
2488 char *stripped_filename;
2489 RAII_VAR(char *, path, NULL, ast_free);
2490 RAII_VAR(char *, real_path, NULL, ast_std_free);
2491
2492 if (live_dangerously) {
2493 return 0;
2494 }
2495
2496 stripped_filename = ast_strip(ast_strdupa(filename));
2497
2498 /* If the file path starts with '/', don't prepend ast_config_AST_CONFIG_DIR */
2499 if (stripped_filename[0] == '/') {
2500 real_path = realpath(stripped_filename, NULL);
2501 } else {
2502 if (ast_asprintf(&path, "%s/%s", ast_config_AST_CONFIG_DIR, stripped_filename) == -1) {
2503 return -1;
2504 }
2505 real_path = realpath(path, NULL);
2506 }
2507
2508 if (!real_path) {
2509 return -1;
2510 }
2511
2512 if (!ast_begins_with(real_path, ast_config_AST_CONFIG_DIR)) {
2513 return 1;
2514 }
2515
2516 return 0;
2517 }
2518
2519 static int action_getconfig(struct mansession *s, const struct message *m)
2520 {
2521 struct ast_config *cfg;
2522 const char *fn = astman_get_header(m, "Filename");
2523 const char *category = astman_get_header(m, "Category");
2524 const char *filter = astman_get_header(m, "Filter");
2525 const char *category_name;
2526 int catcount = 0;
2527 int lineno = 0;
2528 int ret = 0;
2529 struct ast_category *cur_category = NULL;
2530 struct ast_variable *v;
2531 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2532
2533 if (ast_strlen_zero(fn)) {
2534 astman_send_error(s, m, "Filename not specified");
2535 return 0;
2536 }
2537
2538 ret = is_restricted_file(fn);
2539 if (ret == 1) {
2540 astman_send_error(s, m, "File requires escalated privileges");
2541 return 0;
2542 } else if (ret == -1) {
2543 astman_send_error(s, m, "Config file not found");
2544 return 0;
2545 }
2546
2547 cfg = ast_config_load2(fn, "manager", config_flags);
2548 if (cfg == CONFIG_STATUS_FILEMISSING) {
2549 astman_send_error(s, m, "Config file not found");
2550 return 0;
2551 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2552 astman_send_error(s, m, "Config file has invalid format");
2553 return 0;
2554 }
2555
2556 astman_start_ack(s, m);
2557 while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
2558 struct ast_str *templates;
2559
2560 category_name = ast_category_get_name(cur_category);
2561 lineno = 0;
2562 astman_append(s, "Category-%06d: %s\r\n", catcount, category_name);
2563
2564 if (ast_category_is_template(cur_category)) {
2565 astman_append(s, "IsTemplate-%06d: %d\r\n", catcount, 1);
2566 }
2567
2568 if ((templates = ast_category_get_templates(cur_category))
2569 && ast_str_strlen(templates) > 0) {
2570 astman_append(s, "Templates-%06d: %s\r\n", catcount, ast_str_buffer(templates));
2571 ast_free(templates);
2572 }
2573
2574 for (v = ast_category_first(cur_category); v; v = v->next) {
2575 astman_append(s, "Line-%06d-%06d: %s=%s\r\n", catcount, lineno++, v->name, v->value);
2576 }
2577
2578 catcount++;
2579 }
2580
2581 if (!ast_strlen_zero(category) && catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2582 astman_append(s, "No categories found\r\n");
2583 }
2584
2585 ast_config_destroy(cfg);
2586 astman_append(s, "\r\n");
2587
2588 return 0;
2589 }
2590
2591 static int action_listcategories(struct mansession *s, const struct message *m)
2592 {
2593 struct ast_config *cfg;
2594 const char *fn = astman_get_header(m, "Filename");
2595 const char *match = astman_get_header(m, "Match");
2596 struct ast_category *category = NULL;
2597 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2598 int catcount = 0;
2599 int ret = 0;
2600
2601 if (ast_strlen_zero(fn)) {
2602 astman_send_error(s, m, "Filename not specified");
2603 return 0;
2604 }
2605
2606 ret = is_restricted_file(fn);
2607 if (ret == 1) {
2608 astman_send_error(s, m, "File requires escalated privileges");
2609 return 0;
2610 } else if (ret == -1) {
2611 astman_send_error(s, m, "Config file not found");
2612 return 0;
2613 }
2614
2615 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2616 astman_send_error(s, m, "Config file not found");
2617 return 0;
2618 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2619 astman_send_error(s, m, "Config file has invalid format");
2620 return 0;
2621 }
2622
2623 astman_start_ack(s, m);
2624 while ((category = ast_category_browse_filtered(cfg, NULL, category, match))) {
2625 astman_append(s, "Category-%06d: %s\r\n", catcount, ast_category_get_name(category));
2626 catcount++;
2627 }
2628
2629 if (catcount == 0) { /* TODO: actually, a config with no categories doesn't even get loaded */
2630 astman_append(s, "Error: no categories found\r\n");
2631 }
2632
2633 ast_config_destroy(cfg);
2634 astman_append(s, "\r\n");
2635
2636 return 0;
2637 }
2638
2639 /*! The amount of space in out must be at least ( 2 * strlen(in) + 1 ) */
2640 static void json_escape(char *out, const char *in)
2641 {
2642 for (; *in; in++) {
2643 if (*in == '\\' || *in == '\"') {
2644 *out++ = '\\';
2645 }
2646 *out++ = *in;
2647 }
2648 *out = '\0';
2649 }
2650
2651 /*!
2652 * \internal
2653 * \brief Append a JSON escaped string to the manager stream.
2654 *
2655 * \param s AMI stream to append a string.
2656 * \param str String to append to the stream after JSON escaping it.
2657 */
2658 static void astman_append_json(struct mansession *s, const char *str)
2659 {
2660 char *buf;
2661
2662 buf = ast_alloca(2 * strlen(str) + 1);
2663 json_escape(buf, str);
2664 astman_append(s, "%s", buf);
2665 }
2666
2667 static int action_getconfigjson(struct mansession *s, const struct message *m)
2668 {
2669 struct ast_config *cfg;
2670 const char *fn = astman_get_header(m, "Filename");
2671 const char *filter = astman_get_header(m, "Filter");
2672 const char *category = astman_get_header(m, "Category");
2673 struct ast_category *cur_category = NULL;
2674 const char *category_name;
2675 struct ast_variable *v;
2676 int comma1 = 0;
2677 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
2678
2679 if (ast_strlen_zero(fn)) {
2680 astman_send_error(s, m, "Filename not specified");
2681 return 0;
2682 }
2683
2684 if (is_restricted_file(fn)) {
2685 astman_send_error(s, m, "File requires escalated privileges");
2686 return 0;
2687 }
2688
2689 if (!(cfg = ast_config_load2(fn, "manager", config_flags))) {
2690 astman_send_error(s, m, "Config file not found");
2691 return 0;
2692 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
2693 astman_send_error(s, m, "Config file has invalid format");
2694 return 0;
2695 }
2696
2697 astman_start_ack(s, m);
2698 astman_append(s, "JSON: {");
2699 while ((cur_category = ast_category_browse_filtered(cfg, category, cur_category, filter))) {
2700 int comma2 = 0;
2701 struct ast_str *templates;
2702
2703 category_name = ast_category_get_name(cur_category);
2704 astman_append(s, "%s\"", comma1 ? "," : "");
2705 astman_append_json(s, category_name);
2706 astman_append(s, "\":{");
2707 comma1 = 1;
2708
2709 if (ast_category_is_template(cur_category)) {
2710 astman_append(s, "\"istemplate\":1");
2711 comma2 = 1;
2712 }
2713
2714 if ((templates = ast_category_get_templates(cur_category))
2715 && ast_str_strlen(templates) > 0) {
2716 astman_append(s, "%s", comma2 ? "," : "");
2717 astman_append(s, "\"templates\":\"%s\"", ast_str_buffer(templates));
2718 ast_free(templates);
2719 comma2 = 1;
2720 }
2721
2722 for (v = ast_category_first(cur_category); v; v = v->next) {
2723 astman_append(s, "%s\"", comma2 ? "," : "");
2724 astman_append_json(s, v->name);
2725 astman_append(s, "\":\"");
2726 astman_append_json(s, v->value);
2727 astman_append(s, "\"");
2728 comma2 = 1;
2729 }
2730
2731 astman_append(s, "}");
2732 }
2733 astman_append(s, "}\r\n\r\n");
2734
2735 ast_config_destroy(cfg);
2736
2737 return 0;
2738 }
2739
2740 /*! \brief helper function for action_updateconfig */
2741 static enum error_type handle_updates(struct mansession *s, const struct message *m, struct ast_config *cfg, const char *dfn)
2742 {
2743 int x;
2744 char hdr[40];
2745 const char *action, *cat, *var, *value, *match, *line, *options;
2746 struct ast_variable *v;
2747 struct ast_str *str1 = ast_str_create(16), *str2 = ast_str_create(16);
2748 enum error_type result = 0;
2749
2750 for (x = 0; x < 100000; x++) { /* 100000 = the max number of allowed updates + 1 */
2751 unsigned int object = 0;
2752 char *dupoptions;
2753 int allowdups = 0;
2754 int istemplate = 0;
2755 int ignoreerror = 0;
2756 RAII_VAR(char *, inherit, NULL, ast_free);
2757 RAII_VAR(char *, catfilter, NULL, ast_free);
2758 char *token;
2759 int foundvar = 0;
2760 int foundcat = 0;
2761 struct ast_category *category = NULL;
2762
2763 snprintf(hdr, sizeof(hdr), "Action-%06d", x);
2764 action = astman_get_header(m, hdr);
2765 if (ast_strlen_zero(action)) /* breaks the for loop if no action header */
2766 break; /* this could cause problems if actions come in misnumbered */
2767
2768 snprintf(hdr, sizeof(hdr), "Cat-%06d", x);
2769 cat = astman_get_header(m, hdr);
2770 if (ast_strlen_zero(cat)) { /* every action needs a category */
2771 result = UNSPECIFIED_CATEGORY;
2772 break;
2773 }
2774
2775 snprintf(hdr, sizeof(hdr), "Var-%06d", x);
2776 var = astman_get_header(m, hdr);
2777
2778 snprintf(hdr, sizeof(hdr), "Value-%06d", x);
2779 value = astman_get_header(m, hdr);
2780
2781 if (!ast_strlen_zero(value) && *value == '>') {
2782 object = 1;
2783 value++;
2784 }
2785
2786 snprintf(hdr, sizeof(hdr), "Match-%06d", x);
2787 match = astman_get_header(m, hdr);
2788
2789 snprintf(hdr, sizeof(hdr), "Line-%06d", x);
2790 line = astman_get_header(m, hdr);
2791
2792 snprintf(hdr, sizeof(hdr), "Options-%06d", x);
2793 options = astman_get_header(m, hdr);
2794 if (!ast_strlen_zero(options)) {
2795 char copy[strlen(options) + 1];
2796 strcpy(copy, options); /* safe */
2797 dupoptions = copy;
2798 while ((token = ast_strsep(&dupoptions, ',', AST_STRSEP_STRIP))) {
2799 if (!strcasecmp("allowdups", token)) {
2800 allowdups = 1;
2801 continue;
2802 }
2803 if (!strcasecmp("template", token)) {
2804 istemplate = 1;
2805 continue;
2806 }
2807 if (!strcasecmp("ignoreerror", token)) {
2808 ignoreerror = 1;
2809 continue;
2810 }
2811 if (ast_begins_with(token, "inherit")) {
2812 char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
2813 c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
2814 if (c) {
2815 inherit = ast_strdup(c);
2816 }
2817 continue;
2818 }
2819 if (ast_begins_with(token, "catfilter")) {
2820 char *c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
2821 c = ast_strsep(&token, '=', AST_STRSEP_STRIP);
2822 if (c) {
2823 catfilter = ast_strdup(c);
2824 }
2825 continue;
2826 }
2827 }
2828 }
2829
2830 if (!strcasecmp(action, "newcat")) {
2831 struct ast_category *template;
2832 char *tmpl_name = NULL;
2833
2834 if (!allowdups) {
2835 if (ast_category_get(cfg, cat, "TEMPLATES=include")) {
2836 if (ignoreerror) {
2837 continue;
2838 } else {
2839 result = FAILURE_NEWCAT; /* already exist */
2840 break;
2841 }
2842 }
2843 }
2844
2845 if (istemplate) {
2846 category = ast_category_new_template(cat, dfn, -1);
2847 } else {
2848 category = ast_category_new(cat, dfn, -1);
2849 }
2850
2851 if (!category) {
2852 result = FAILURE_ALLOCATION;
2853 break;
2854 }
2855
2856 if (inherit) {
2857 while ((tmpl_name = ast_strsep(&inherit, ',', AST_STRSEP_STRIP))) {
2858 if ((template = ast_category_get(cfg, tmpl_name, "TEMPLATES=restrict"))) {
2859 if (ast_category_inherit(category, template)) {
2860 result = FAILURE_ALLOCATION;
2861 break;
2862 }
2863 } else {
2864 ast_category_destroy(category);
2865 category = NULL;
2866 result = FAILURE_TEMPLATE; /* template not found */
2867 break;
2868 }
2869 }
2870 }
2871
2872 if (category != NULL) {
2873 if (ast_strlen_zero(match)) {
2874 ast_category_append(cfg, category);
2875 } else {
2876 if (ast_category_insert(cfg, category, match)) {
2877 ast_category_destroy(category);
2878 result = FAILURE_NEWCAT;
2879 break;
2880 }
2881 }
2882 }
2883 } else if (!strcasecmp(action, "renamecat")) {
2884 if (ast_strlen_zero(value)) {
2885 result = UNSPECIFIED_ARGUMENT;
2886 break;
2887 }
2888
2889 foundcat = 0;
2890 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
2891 ast_category_rename(category, value);
2892 foundcat = 1;
2893 }
2894
2895 if (!foundcat) {
2896 result = UNKNOWN_CATEGORY;
2897 break;
2898 }
2899 } else if (!strcasecmp(action, "delcat")) {
2900 foundcat = 0;
2901 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
2902 category = ast_category_delete(cfg, category);
2903 foundcat = 1;
2904 }
2905
2906 if (!foundcat && !ignoreerror) {
2907 result = UNKNOWN_CATEGORY;
2908 break;
2909 }
2910 } else if (!strcasecmp(action, "emptycat")) {
2911 foundcat = 0;
2912 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
2913 ast_category_empty(category);
2914 foundcat = 1;
2915 }
2916
2917 if (!foundcat) {
2918 result = UNKNOWN_CATEGORY;
2919 break;
2920 }
2921 } else if (!strcasecmp(action, "update")) {
2922 if (ast_strlen_zero(var)) {
2923 result = UNSPECIFIED_ARGUMENT;
2924 break;
2925 }
2926
2927 foundcat = 0;
2928 foundvar = 0;
2929 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
2930 if (!ast_variable_update(category, var, value, match, object)) {
2931 foundvar = 1;
2932 }
2933 foundcat = 1;
2934 }
2935
2936 if (!foundcat) {
2937 result = UNKNOWN_CATEGORY;
2938 break;
2939 }
2940
2941 if (!foundvar) {
2942 result = FAILURE_UPDATE;
2943 break;
2944 }
2945 } else if (!strcasecmp(action, "delete")) {
2946 if ((ast_strlen_zero(var) && ast_strlen_zero(line))) {
2947 result = UNSPECIFIED_ARGUMENT;
2948 break;
2949 }
2950
2951 foundcat = 0;
2952 foundvar = 0;
2953 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
2954 if (!ast_variable_delete(category, var, match, line)) {
2955 foundvar = 1;
2956 }
2957 foundcat = 1;
2958 }
2959
2960 if (!foundcat) {
2961 result = UNKNOWN_CATEGORY;
2962 break;
2963 }
2964
2965 if (!foundvar && !ignoreerror) {
2966 result = FAILURE_UPDATE;
2967 break;
2968 }
2969 } else if (!strcasecmp(action, "append")) {
2970 if (ast_strlen_zero(var)) {
2971 result = UNSPECIFIED_ARGUMENT;
2972 break;
2973 }
2974
2975 foundcat = 0;
2976 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
2977 if (!(v = ast_variable_new(var, value, dfn))) {
2978 result = FAILURE_ALLOCATION;
2979 break;
2980 }
2981 if (object || (match && !strcasecmp(match, "object"))) {
2982 v->object = 1;
2983 }
2984 ast_variable_append(category, v);
2985 foundcat = 1;
2986 }
2987
2988 if (!foundcat) {
2989 result = UNKNOWN_CATEGORY;
2990 break;
2991 }
2992 } else if (!strcasecmp(action, "insert")) {
2993 if (ast_strlen_zero(var) || ast_strlen_zero(line)) {
2994 result = UNSPECIFIED_ARGUMENT;
2995 break;
2996 }
2997
2998 foundcat = 0;
2999 while ((category = ast_category_browse_filtered(cfg, cat, category, catfilter))) {
3000 if (!(v = ast_variable_new(var, value, dfn))) {
3001 result = FAILURE_ALLOCATION;
3002 break;
3003 }
3004 ast_variable_insert(category, v, line);
3005 foundcat = 1;
3006 }
3007
3008 if (!foundcat) {
3009 result = UNKNOWN_CATEGORY;
3010 break;
3011 }
3012 }
3013 else {
3014 ast_log(LOG_WARNING, "Action-%06d: %s not handled\n", x, action);
3015 result = UNKNOWN_ACTION;
3016 break;
3017 }
3018 }
3019 ast_free(str1);
3020 ast_free(str2);
3021 return result;
3022 }
3023
3024 static int action_updateconfig(struct mansession *s, const struct message *m)
3025 {
3026 struct ast_config *cfg;
3027 const char *sfn = astman_get_header(m, "SrcFilename");
3028 const char *dfn = astman_get_header(m, "DstFilename");
3029 int res;
3030 const char *rld = astman_get_header(m, "Reload");
3031 int preserve_effective_context = CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT;
3032 const char *preserve_effective_context_string = astman_get_header(m, "PreserveEffectiveContext");
3033 struct ast_flags config_flags = { CONFIG_FLAG_WITHCOMMENTS | CONFIG_FLAG_NOCACHE };
3034 enum error_type result;
3035
3036 if (ast_strlen_zero(sfn) || ast_strlen_zero(dfn)) {
3037 astman_send_error(s, m, "Filename not specified");
3038 return 0;
3039 }
3040 if (is_restricted_file(sfn) || is_restricted_file(dfn)) {
3041 astman_send_error(s, m, "File requires escalated privileges");
3042 return 0;
3043 }
3044 if (!(cfg = ast_config_load2(sfn, "manager", config_flags))) {
3045 astman_send_error(s, m, "Config file not found");
3046 return 0;
3047 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
3048 astman_send_error(s, m, "Config file has invalid format");
3049 return 0;
3050 }
3051 result = handle_updates(s, m, cfg, dfn);
3052 if (!result) {
3053 ast_include_rename(cfg, sfn, dfn); /* change the include references from dfn to sfn, so things match up */
3054 if (!ast_strlen_zero(preserve_effective_context_string) && !ast_true(preserve_effective_context_string)) {
3055 preserve_effective_context = CONFIG_SAVE_FLAG_NONE;
3056 }
3057 res = ast_config_text_file_save2(dfn, cfg, "Manager", preserve_effective_context);
3058 ast_config_destroy(cfg);
3059 if (res) {
3060 astman_send_error(s, m, "Save of config failed");
3061 return 0;
3062 }
3063 astman_send_ack(s, m, NULL);
3064 if (!ast_strlen_zero(rld)) {
3065 if (ast_true(rld)) {
3066 ast_module_reload(NULL); /* Reload everything */
3067 } else if (!ast_false(rld)) {
3068 ast_module_reload(rld); /* Reload the specific module */
3069 }
3070 }
3071 } else {
3072 ast_config_destroy(cfg);
3073 switch(result) {
3074 case UNKNOWN_ACTION:
3075 astman_send_error(s, m, "Unknown action command");
3076 break;
3077 case UNKNOWN_CATEGORY:
3078 astman_send_error(s, m, "Given category does not exist");
3079 break;
3080 case UNSPECIFIED_CATEGORY:
3081 astman_send_error(s, m, "Category not specified");
3082 break;
3083 case UNSPECIFIED_ARGUMENT:
3084 astman_send_error(s, m, "Problem with category, value, or line (if required)");
3085 break;
3086 case FAILURE_ALLOCATION:
3087 astman_send_error(s, m, "Memory allocation failure, this should not happen");
3088 break;
3089 case FAILURE_NEWCAT:
3090 astman_send_error(s, m, "Create category did not complete successfully");
3091 break;
3092 case FAILURE_DELCAT:
3093 astman_send_error(s, m, "Delete category did not complete successfully");
3094 break;
3095 case FAILURE_EMPTYCAT:
3096 astman_send_error(s, m, "Empty category did not complete successfully");
3097 break;
3098 case FAILURE_UPDATE:
3099 astman_send_error(s, m, "Update did not complete successfully");
3100 break;
3101 case FAILURE_DELETE:
3102 astman_send_error(s, m, "Delete did not complete successfully");
3103 break;
3104 case FAILURE_APPEND:
3105 astman_send_error(s, m, "Append did not complete successfully");
3106 break;
3107 case FAILURE_TEMPLATE:
3108 astman_send_error(s, m, "Template category not found");
3109 break;
3110 }
3111 }
3112 return 0;
3113 }
3114
3115 static int action_createconfig(struct mansession *s, const struct message *m)
3116 {
3117 int fd;
3118 const char *fn = astman_get_header(m, "Filename");
3119 char *stripped_filename;
3120 RAII_VAR(char *, filepath, NULL, ast_free);
3121 RAII_VAR(char *, real_dir, NULL, ast_std_free);
3122 RAII_VAR(char *, real_path, NULL, ast_free);
3123 char *filename;
3124
3125 if (ast_strlen_zero(fn)) {
3126 astman_send_error(s, m, "Filename not specified");
3127 return 0;
3128 }
3129
3130 stripped_filename = ast_strip(ast_strdupa(fn));
3131
3132 /* If the file name is relative, prepend ast_config_AST_CONFIG_DIR */
3133 if (stripped_filename[0] != '/') {
3134 if (ast_asprintf(&filepath, "%s/%s", ast_config_AST_CONFIG_DIR, stripped_filename) == -1) {
3135 return -1;
3136 }
3137 } else {
3138 filepath = ast_strdup(stripped_filename);
3139 }
3140
3141 /*
3142 * We can't call is_restricted_file() here because it uses realpath() and...
3143 *
3144 * realpath() and other functions that canonicalize paths won't work with
3145 * a filename that doesn't exist, so we need to separate the directory
3146 * from the filename and canonicalize the directory first. We have to do
3147 * the separation manually because dirname() and basename() aren't all
3148 * that friendly to multi-threaded programs and there are different
3149 * versions of basename for glibc and POSIX.
3150 */
3151
3152 filename = strrchr(filepath, '/');
3153 if (!filename) {
3154 astman_send_error(s, m, "Filename is invalid");
3155 return 0;
3156 }
3157 *filename = '\0';
3158 filename++;
3159
3160 /* filepath just has the directory now so canonicalize it. */
3161 real_dir = realpath(filepath, NULL);
3162 if (ast_strlen_zero(real_dir)) {
3163 astman_send_error(s, m, strerror(errno));
3164 return 0;
3165 }
3166
3167 /* Check if the directory is restricted. */
3168 if (!live_dangerously && !ast_begins_with(real_dir, ast_config_AST_CONFIG_DIR)) {
3169 astman_send_error(s, m, "File requires escalated privileges");
3170 return 0;
3171 }
3172
3173 /* Create the final file path. */
3174 if (ast_asprintf(&real_path, "%s/%s", real_dir, filename) == -1) {
3175 astman_send_error(s, m, strerror(errno));
3176 return -1;
3177 }
3178
3179 if ((fd = open(real_path, O_CREAT | O_EXCL, AST_FILE_MODE)) != -1) {
3180 close(fd);
3181 astman_send_ack(s, m, "New configuration file created successfully");
3182 } else {
3183 astman_send_error(s, m, strerror(errno));
3184 }
3185
3186 return 0;
3187 }
3188
3189 static int action_waitevent(struct mansession *s, const struct message *m)
3190 {
3191 const char *timeouts = astman_get_header(m, "Timeout");
3192 int timeout = -1;
3193 int x;
3194 int needexit = 0;
3195 const char *id = astman_get_header(m, "ActionID");
3196 char idText[256];
3197
3198 if (!ast_strlen_zero(id)) {
3199 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3200 } else {
3201 idText[0] = '\0';
3202 }
3203
3204 if (!ast_strlen_zero(timeouts)) {
3205 sscanf(timeouts, "%30i", &timeout);
3206 if (timeout < -1) {
3207 timeout = -1;
3208 }
3209 /* XXX maybe put an upper bound, or prevent the use of 0 ? */
3210 }
3211
3212 ast_mutex_lock(&s->session->notify_lock);
3213 if (s->session->waiting_thread != AST_PTHREADT_NULL) {
3214 pthread_kill(s->session->waiting_thread, SIGURG);
3215 }
3216 ast_mutex_unlock(&s->session->notify_lock);
3217
3218 ao2_lock(s->session);
3219
3220 if (s->session->managerid) { /* AMI-over-HTTP session */
3221 /*
3222 * Make sure the timeout is within the expire time of the session,
3223 * as the client will likely abort the request if it does not see
3224 * data coming after some amount of time.
3225 */
3226 time_t now = time(NULL);
3227 int max = s->session->sessiontimeout - now - 10;
3228
3229 if (max < 0) { /* We are already late. Strange but possible. */
3230 max = 0;
3231 }
3232 if (timeout < 0 || timeout > max) {
3233 timeout = max;
3234 }
3235 if (!s->session->send_events) { /* make sure we record events */
3236 s->session->send_events = -1;
3237 }
3238 }
3239 ao2_unlock(s->session);
3240
3241 ast_mutex_lock(&s->session->notify_lock);
3242 s->session->waiting_thread = pthread_self(); /* let new events wake up this thread */
3243 ast_mutex_unlock(&s->session->notify_lock);
3244 ast_debug(1, "Starting waiting for an event!\n");
3245
3246 for (x = 0; x < timeout || timeout < 0; x++) {
3247 ao2_lock(s->session);
3248 if (AST_RWLIST_NEXT(s->session->last_ev, eq_next)) {
3249 needexit = 1;
3250 }
3251 if (s->session->needdestroy) {
3252 needexit = 1;
3253 }
3254 ao2_unlock(s->session);
3255 /* We can have multiple HTTP session point to the same mansession entry.
3256 * The way we deal with it is not very nice: newcomers kick out the previous
3257 * HTTP session. XXX this needs to be improved.
3258 */
3259 ast_mutex_lock(&s->session->notify_lock);
3260 if (s->session->waiting_thread != pthread_self()) {
3261 needexit = 1;
3262 }
3263 ast_mutex_unlock(&s->session->notify_lock);
3264 if (needexit) {
3265 break;
3266 }
3267 if (s->session->managerid == 0) { /* AMI session */
3268 if (ast_wait_for_input(ast_iostream_get_fd(s->session->stream), 1000)) {
3269 break;
3270 }
3271 } else { /* HTTP session */
3272 sleep(1);
3273 }
3274 }
3275 ast_debug(1, "Finished waiting for an event!\n");
3276
3277 ast_mutex_lock(&s->session->notify_lock);
3278 if (s->session->waiting_thread == pthread_self()) {
3279 struct eventqent *eqe = s->session->last_ev;
3280
3281 s->session->waiting_thread = AST_PTHREADT_NULL;
3282 ast_mutex_unlock(&s->session->notify_lock);
3283
3284 ao2_lock(s->session);
3285 astman_send_response(s, m, "Success", "Waiting for Event completed.");
3286 while ((eqe = advance_event(eqe))) {
3287 if (((s->session->readperm & eqe->category) == eqe->category)
3288 && ((s->session->send_events & eqe->category) == eqe->category)
3289 && should_send_event(s->session->includefilters, s->session->excludefilters, eqe)) {
3290 astman_append(s, "%s", eqe->eventdata);
3291 }
3292 s->session->last_ev = eqe;
3293 }
3294 astman_append(s,
3295 "Event: WaitEventComplete\r\n"
3296 "%s"
3297 "\r\n", idText);
3298 ao2_unlock(s->session);
3299 } else {
3300 ast_mutex_unlock(&s->session->notify_lock);
3301 ast_debug(1, "Abandoning event request!\n");
3302 }
3303
3304 return 0;
3305 }
3306
3307 static int action_listcommands(struct mansession *s, const struct message *m)
3308 {
3309 struct manager_action *cur;
3310 struct ast_str *temp = ast_str_alloca(MAX_AUTH_PERM_STRING);
3311
3312 astman_start_ack(s, m);
3313 AST_RWLIST_RDLOCK(&actions);
3314 AST_RWLIST_TRAVERSE(&actions, cur, list) {
3315 if ((s->session->writeperm & cur->authority) || cur->authority == 0) {
3316 astman_append(s, "%s: %s (Priv: %s)\r\n",
3317 cur->action, cur->synopsis, authority_to_str(cur->authority, &temp));
3318 }
3319 }
3320 AST_RWLIST_UNLOCK(&actions);
3321 astman_append(s, "\r\n");
3322
3323 return 0;
3324 }
3325
3326 static int action_events(struct mansession *s, const struct message *m)
3327 {
3328 const char *mask = astman_get_header(m, "EventMask");
3329 int res, x;
3330 const char *id = astman_get_header(m, "ActionID");
3331 char id_text[256];
3332
3333 if (!ast_strlen_zero(id)) {
3334 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3335 } else {
3336 id_text[0] = '\0';
3337 }
3338
3339 res = set_eventmask(s, mask);
3340 if (broken_events_action) {
3341 /* if this option is set we should not return a response on
3342 * error, or when all events are set */
3343
3344 if (res > 0) {
3345 for (x = 0; x < ARRAY_LEN(perms); x++) {
3346 if (!strcasecmp(perms[x].label, "all") && res == perms[x].num) {
3347 return 0;
3348 }
3349 }
3350 astman_append(s, "Response: Success\r\n%s"
3351 "Events: On\r\n\r\n", id_text);
3352 } else if (res == 0)
3353 astman_append(s, "Response: Success\r\n%s"
3354 "Events: Off\r\n\r\n", id_text);
3355 return 0;
3356 }
3357
3358 if (res > 0)
3359 astman_append(s, "Response: Success\r\n%s"
3360 "Events: On\r\n\r\n", id_text);
3361 else if (res == 0)
3362 astman_append(s, "Response: Success\r\n%s"
3363 "Events: Off\r\n\r\n", id_text);
3364 else
3365 astman_send_error(s, m, "Invalid event mask");
3366
3367 return 0;
3368 }
3369
3370 static int action_logoff(struct mansession *s, const struct message *m)
3371 {
3372 astman_send_response(s, m, "Goodbye", "Thanks for all the fish.");
3373 return -1;
3374 }
3375
3376 static int action_login(struct mansession *s, const struct message *m)
3377 {
3378
3379 /* still authenticated - don't process again */
3380 if (s->session->authenticated) {
3381 astman_send_ack(s, m, "Already authenticated");
3382 return 0;
3383 }
3384
3385 if (authenticate(s, m)) {
3386 sleep(1);
3387 astman_send_error(s, m, "Authentication failed");
3388 return -1;
3389 }
3390 s->session->authenticated = 1;
3391 ast_atomic_fetchadd_int(&unauth_sessions, -1);
3392 if (manager_displayconnects(s->session)) {
3393 ast_verb(2, "%sManager '%s' logged on from %s\n", (s->session->managerid ? "HTTP " : ""), s->session->username, ast_sockaddr_stringify_addr(&s->session->addr));
3394 }
3395 astman_send_ack(s, m, "Authentication accepted");
3396 if ((s->session->send_events & EVENT_FLAG_SYSTEM)
3397 && (s->session->readperm & EVENT_FLAG_SYSTEM)
3398 && ast_fully_booted) {
3399 struct ast_str *auth = ast_str_alloca(MAX_AUTH_PERM_STRING);
3400 const char *cat_str = authority_to_str(EVENT_FLAG_SYSTEM, &auth);
3401 long uptime = 0;
3402 long lastreloaded = 0;
3403 struct timeval tmp;
3404 struct timeval curtime = ast_tvnow();
3405
3406 if (ast_startuptime.tv_sec) {
3407 tmp = ast_tvsub(curtime, ast_startuptime);
3408 uptime = tmp.tv_sec;
3409 }
3410
3411 if (ast_lastreloadtime.tv_sec) {
3412 tmp = ast_tvsub(curtime, ast_lastreloadtime);
3413 lastreloaded = tmp.tv_sec;
3414 }
3415
3416 astman_append(s, "Event: FullyBooted\r\n"
3417 "Privilege: %s\r\n"
3418 "Uptime: %ld\r\n"
3419 "LastReload: %ld\r\n"
3420 "Status: Fully Booted\r\n\r\n", cat_str, uptime, lastreloaded);
3421 }
3422 return 0;
3423 }
3424
3425 static int action_challenge(struct mansession *s, const struct message *m)
3426 {
3427 const char *authtype = astman_get_header(m, "AuthType");
3428
3429 if (!strcasecmp(authtype, "MD5")) {
3430 if (ast_strlen_zero(s->session->challenge)) {
3431 snprintf(s->session->challenge, sizeof(s->session->challenge), "%ld", ast_random());
3432 }
3433 mansession_lock(s);
3434 astman_start_ack(s, m);
3435 astman_append(s, "Challenge: %s\r\n\r\n", s->session->challenge);
3436 mansession_unlock(s);
3437 } else {
3438 astman_send_error(s, m, "Must specify AuthType");
3439 }
3440 return 0;
3441 }
3442
3443 int ast_manager_hangup_helper(struct mansession *s,
3444 const struct message *m, manager_hangup_handler_t hangup_handler,
3445 manager_hangup_cause_validator_t cause_validator)
3446 {
3447 struct ast_channel *c = NULL;
3448 int causecode = 0; /* all values <= 0 mean 'do not set hangupcause in channel' */
3449 const char *id = astman_get_header(m, "ActionID");
3450 const char *name_or_regex = astman_get_header(m, "Channel");
3451 const char *cause = astman_get_header(m, "Cause");
3452 char idText[256];
3453 regex_t regexbuf;
3454 struct ast_channel_iterator *iter = NULL;
3455 struct ast_str *regex_string;
3456 int channels_matched = 0;
3457
3458 if (ast_strlen_zero(name_or_regex)) {
3459 astman_send_error(s, m, "No channel specified");
3460 return 0;
3461 }
3462
3463 if (!ast_strlen_zero(id)) {
3464 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
3465 } else {
3466 idText[0] = '\0';
3467 }
3468
3469 if (cause_validator) {
3470 causecode = cause_validator(name_or_regex, cause);
3471 } else if (!ast_strlen_zero(cause)) {
3472 char *endptr;
3473 causecode = strtol(cause, &endptr, 10);
3474 if (causecode < 0 || causecode > 127 || *endptr != '\0') {
3475 ast_log(LOG_NOTICE, "Invalid 'Cause: %s' in manager action Hangup\n", cause);
3476 /* keep going, better to hangup without cause than to not hang up at all */
3477 causecode = 0; /* do not set channel's hangupcause */
3478 }
3479 }
3480
3481 /************************************************/
3482 /* Regular explicit match channel byname hangup */
3483
3484 if (name_or_regex[0] != '/') {
3485 if (!(c = ast_channel_get_by_name(name_or_regex))) {
3486 ast_log(LOG_NOTICE, "Request to hangup non-existent channel: %s\n",
3487 name_or_regex);
3488 astman_send_error(s, m, "No such channel");
3489 return 0;
3490 }
3491
3492 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3493 (s->session->managerid ? "HTTP " : ""),
3494 s->session->username,
3495 ast_sockaddr_stringify_addr(&s->session->addr),
3496 ast_channel_name(c));
3497
3498 hangup_handler(c, causecode);
3499 c = ast_channel_unref(c);
3500
3501 astman_send_ack(s, m, "Channel Hungup");
3502
3503 return 0;
3504 }
3505
3506 /***********************************************/
3507 /* find and hangup any channels matching regex */
3508
3509 regex_string = ast_str_create(strlen(name_or_regex));
3510 if (!regex_string) {
3511 astman_send_error(s, m, "Memory Allocation Failure");
3512 return 0;
3513 }
3514
3515 /* Make "/regex/" into "regex" */
3516 if (ast_regex_string_to_regex_pattern(name_or_regex, &regex_string) != 0) {
3517 astman_send_error(s, m, "Regex format invalid, Channel param should be /regex/");
3518 ast_free(regex_string);
3519 return 0;
3520 }
3521
3522 /* if regex compilation fails, hangup fails */
3523 if (regcomp(&regexbuf, ast_str_buffer(regex_string), REG_EXTENDED | REG_NOSUB)) {
3524 astman_send_error_va(s, m, "Regex compile failed on: %s", name_or_regex);
3525 ast_free(regex_string);
3526 return 0;
3527 }
3528
3529 astman_send_listack(s, m, "Channels hung up will follow", "start");
3530
3531 iter = ast_channel_iterator_all_new();
3532 if (iter) {
3533 for (; (c = ast_channel_iterator_next(iter)); ast_channel_unref(c)) {
3534 if (regexec(&regexbuf, ast_channel_name(c), 0, NULL, 0)) {
3535 continue;
3536 }
3537
3538 ast_verb(3, "%sManager '%s' from %s, hanging up channel: %s\n",
3539 (s->session->managerid ? "HTTP " : ""),
3540 s->session->username,
3541 ast_sockaddr_stringify_addr(&s->session->addr),
3542 ast_channel_name(c));
3543
3544 hangup_handler(c, causecode);
3545 channels_matched++;
3546
3547 astman_append(s,
3548 "Event: ChannelHungup\r\n"
3549 "Channel: %s\r\n"
3550 "%s"
3551 "\r\n", ast_channel_name(c), idText);
3552 }
3553 ast_channel_iterator_destroy(iter);
3554 }
3555
3556 regfree(&regexbuf);
3557 ast_free(regex_string);
3558
3559 astman_send_list_complete(s, m, "ChannelsHungupListComplete", channels_matched);
3560
3561 return 0;
3562 }
3563
3564 static int action_hangup(struct mansession *s, const struct message *m)
3565 {
3566 return ast_manager_hangup_helper(s, m,
3567 ast_channel_softhangup_withcause_locked, NULL);
3568 }
3569
3570 static int action_setvar(struct mansession *s, const struct message *m)
3571 {
3572 struct ast_channel *c = NULL;
3573 const char *name = astman_get_header(m, "Channel");
3574 const char *varname = astman_get_header(m, "Variable");
3575 const char *varval = astman_get_header(m, "Value");
3576 int res = 0;
3577
3578 if (ast_strlen_zero(varname)) {
3579 astman_send_error(s, m, "No variable specified");
3580 return 0;
3581 }
3582
3583 if (!ast_strlen_zero(name)) {
3584 if (!(c = ast_channel_get_by_name(name))) {
3585 astman_send_error(s, m, "No such channel");
3586 return 0;
3587 }
3588 }
3589
3590 res = pbx_builtin_setvar_helper(c, varname, S_OR(varval, ""));
3591
3592 if (c) {
3593 c = ast_channel_unref(c);
3594 }
3595 if (res == 0) {
3596 astman_send_ack(s, m, "Variable Set");
3597 } else {
3598 astman_send_error(s, m, "Variable not set");
3599 }
3600 return 0;
3601 }
3602
3603 static int action_getvar(struct mansession *s, const struct message *m)
3604 {
3605 struct ast_channel *c = NULL;
3606 const char *name = astman_get_header(m, "Channel");
3607 const char *varname = astman_get_header(m, "Variable");
3608 char *varval;
3609 char workspace[1024];
3610
3611 if (ast_strlen_zero(varname)) {
3612 astman_send_error(s, m, "No variable specified");
3613 return 0;
3614 }
3615
3616 /* We don't want users with insufficient permissions using certain functions. */
3617 if (!(function_capable_string_allowed_with_auths(varname, s->session->writeperm))) {
3618 astman_send_error(s, m, "GetVar Access Forbidden: Variable");
3619 return 0;
3620 }
3621
3622 if (!ast_strlen_zero(name)) {
3623 if (!(c = ast_channel_get_by_name(name))) {
3624 astman_send_error(s, m, "No such channel");
3625 return 0;
3626 }
3627 }
3628
3629 workspace[0] = '\0';
3630 if (varname[strlen(varname) - 1] == ')') {
3631 if (!c) {
3632 c = ast_dummy_channel_alloc();
3633 if (c) {
3634 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3635 } else
3636 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
3637 } else {
3638 ast_func_read(c, (char *) varname, workspace, sizeof(workspace));
3639 }
3640 varval = workspace;
3641 } else {
3642 pbx_retrieve_variable(c, varname, &varval, workspace, sizeof(workspace), NULL);
3643 }
3644
3645 if (c) {
3646 c = ast_channel_unref(c);
3647 }
3648
3649 astman_start_ack(s, m);
3650 astman_append(s, "Variable: %s\r\nValue: %s\r\n\r\n", varname, S_OR(varval, ""));
3651
3652 return 0;
3653 }
3654
3655 static void generate_status(struct mansession *s, struct ast_channel *chan, char **vars, int varc, int all_variables, char *id_text, int *count)
3656 {
3657 struct timeval now;
3658 long elapsed_seconds;
3659 struct ast_bridge *bridge;
3660 RAII_VAR(struct ast_str *, variable_str, NULL, ast_free);
3661 struct ast_str *write_transpath = ast_str_alloca(256);
3662 struct ast_str *read_transpath = ast_str_alloca(256);
3663 struct ast_str *codec_buf = ast_str_alloca(AST_FORMAT_CAP_NAMES_LEN);
3664 struct ast_party_id effective_id;
3665 int i;
3666 RAII_VAR(struct ast_channel_snapshot *, snapshot,
3667 ast_channel_snapshot_get_latest(ast_channel_uniqueid(chan)),
3668 ao2_cleanup);
3669 RAII_VAR(struct ast_str *, snapshot_str, NULL, ast_free);
3670
3671 if (!snapshot) {
3672 return;
3673 }
3674
3675 snapshot_str = ast_manager_build_channel_state_string(snapshot);
3676 if (!snapshot_str) {
3677 return;
3678 }
3679
3680 if (all_variables) {
3681 variable_str = ast_str_create(2048);
3682 } else {
3683 variable_str = ast_str_create(1024);
3684 }
3685 if (!variable_str) {
3686 return;
3687 }
3688
3689 now = ast_tvnow();
3690 elapsed_seconds = ast_tvdiff_sec(now, ast_channel_creationtime(chan));
3691
3692 /* Even if all_variables has been specified, explicitly requested variables
3693 * may be global variables or dialplan functions */
3694 for (i = 0; i < varc; i++) {
3695 char valbuf[512], *ret = NULL;
3696
3697 if (vars[i][strlen(vars[i]) - 1] == ')') {
3698 if (ast_func_read(chan, vars[i], valbuf, sizeof(valbuf)) < 0) {
3699 valbuf[0] = '\0';
3700 }
3701 ret = valbuf;
3702 } else {
3703 pbx_retrieve_variable(chan, vars[i], &ret, valbuf, sizeof(valbuf), NULL);
3704 }
3705
3706 ast_str_append(&variable_str, 0, "Variable: %s=%s\r\n", vars[i], ret);
3707 }
3708
3709 /* Walk all channel variables and add them */
3710 if (all_variables) {
3711 struct ast_var_t *variables;
3712
3713 AST_LIST_TRAVERSE(ast_channel_varshead(chan), variables, entries) {
3714 ast_str_append(&variable_str, 0, "Variable: %s=%s\r\n",
3715 ast_var_name(variables), ast_var_value(variables));
3716 }
3717 }
3718
3719 bridge = ast_channel_get_bridge(chan);
3720 effective_id = ast_channel_connected_effective_id(chan);
3721
3722 astman_append(s,
3723 "Event: Status\r\n"
3724 "Privilege: Call\r\n"
3725 "%s"
3726 "Type: %s\r\n"
3727 "DNID: %s\r\n"
3728 "EffectiveConnectedLineNum: %s\r\n"
3729 "EffectiveConnectedLineName: %s\r\n"
3730 "TimeToHangup: %ld\r\n"
3731 "BridgeID: %s\r\n"
3732 "Application: %s\r\n"
3733 "Data: %s\r\n"
3734 "Nativeformats: %s\r\n"
3735 "Readformat: %s\r\n"
3736 "Readtrans: %s\r\n"
3737 "Writeformat: %s\r\n"
3738 "Writetrans: %s\r\n"
3739 "Callgroup: %llu\r\n"
3740 "Pickupgroup: %llu\r\n"
3741 "Seconds: %ld\r\n"
3742 "%s"
3743 "%s"
3744 "\r\n",
3745 ast_str_buffer(snapshot_str),
3746 ast_channel_tech(chan)->type,
3747 S_OR(ast_channel_dialed(chan)->number.str, ""),
3748 S_COR(effective_id.number.valid, effective_id.number.str, "<unknown>"),
3749 S_COR(effective_id.name.valid, effective_id.name.str, "<unknown>"),
3750 (long)ast_channel_whentohangup(chan)->tv_sec,
3751 bridge ? bridge->uniqueid : "",
3752 ast_channel_appl(chan),
3753 ast_channel_data(chan),
3754 ast_format_cap_get_names(ast_channel_nativeformats(chan), &codec_buf),
3755 ast_format_get_name(ast_channel_readformat(chan)),
3756 ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath),
3757 ast_format_get_name(ast_channel_writeformat(chan)),
3758 ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath),
3759 ast_channel_callgroup(chan),
3760 ast_channel_pickupgroup(chan),
3761 (long)elapsed_seconds,
3762 ast_str_buffer(variable_str),
3763 id_text);
3764 ++*count;
3765
3766 ao2_cleanup(bridge);
3767 }
3768
3769 /*! \brief Manager "status" command to show channels */
3770 static int action_status(struct mansession *s, const struct message *m)
3771 {
3772 const char *name = astman_get_header(m, "Channel");
3773 const char *chan_variables = astman_get_header(m, "Variables");
3774 const char *all_chan_variables = astman_get_header(m, "AllVariables");
3775 int all_variables = 0;
3776 const char *id = astman_get_header(m, "ActionID");
3777 char *variables = ast_strdupa(S_OR(chan_variables, ""));
3778 struct ast_channel *chan;
3779 int channels = 0;
3780 int all = ast_strlen_zero(name); /* set if we want all channels */
3781 char id_text[256];
3782 struct ast_channel_iterator *it_chans = NULL;
3783 AST_DECLARE_APP_ARGS(vars,
3784 AST_APP_ARG(name)[100];
3785 );
3786
3787 if (!ast_strlen_zero(all_chan_variables)) {
3788 all_variables = ast_true(all_chan_variables);
3789 }
3790
3791 if (!(function_capable_string_allowed_with_auths(variables, s->session->writeperm))) {
3792 astman_send_error(s, m, "Status Access Forbidden: Variables");
3793 return 0;
3794 }
3795
3796 if (all) {
3797 if (!(it_chans = ast_channel_iterator_all_new())) {
3798 astman_send_error(s, m, "Memory Allocation Failure");
3799 return 1;
3800 }
3801 chan = ast_channel_iterator_next(it_chans);
3802 } else {
3803 chan = ast_channel_get_by_name(name);
3804 if (!chan) {
3805 astman_send_error(s, m, "No such channel");
3806 return 0;
3807 }
3808 }
3809
3810 astman_send_listack(s, m, "Channel status will follow", "start");
3811
3812 if (!ast_strlen_zero(id)) {
3813 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", id);
3814 } else {
3815 id_text[0] = '\0';
3816 }
3817
3818 if (!ast_strlen_zero(chan_variables)) {
3819 AST_STANDARD_APP_ARGS(vars, variables);
3820 }
3821
3822 /* if we look by name, we break after the first iteration */
3823 for (; chan; all ? chan = ast_channel_iterator_next(it_chans) : 0) {
3824 ast_channel_lock(chan);
3825
3826 generate_status(s, chan, vars.name, vars.argc, all_variables, id_text, &channels);
3827
3828 ast_channel_unlock(chan);
3829 chan = ast_channel_unref(chan);
3830 }
3831
3832 if (it_chans) {
3833 ast_channel_iterator_destroy(it_chans);
3834 }
3835
3836 astman_send_list_complete_start(s, m, "StatusComplete", channels);
3837 astman_append(s, "Items: %d\r\n", channels);
3838 astman_send_list_complete_end(s);
3839
3840 return 0;
3841 }
3842
3843 /*!
3844 * \brief Queue a given read action containing a payload onto a channel
3845 *
3846 * This queues a READ_ACTION control frame that contains a given "payload", or
3847 * data to be triggered and handled on the channel's read side. This ensures
3848 * the "action" is handled by the channel's media reading thread.
3849 *
3850 * \param chan The channel to queue the action on
3851 * \param payload The read action's payload
3852 * \param payload_size The size of the given payload
3853 * \param action The type of read action to queue
3854 *
3855 * \retval -1 on error
3856 * \retval 0 on success
3857 */
3858 static int queue_read_action_payload(struct ast_channel *chan, const unsigned char *payload,
3859 size_t payload_size, enum ast_frame_read_action action)
3860 {
3861 struct ast_control_read_action_payload *obj;
3862 size_t obj_size;
3863 int res;
3864
3865 obj_size = payload_size + sizeof(*obj);
3866
3867 obj = ast_malloc(obj_size);
3868 if (!obj) {
3869 return -1;
3870 }
3871
3872 obj->action = action;
3873 obj->payload_size = payload_size;
3874 memcpy(obj->payload, payload, payload_size);
3875
3876 res = ast_queue_control_data(chan, AST_CONTROL_READ_ACTION, obj, obj_size);
3877
3878 ast_free(obj);
3879 return res;
3880 }
3881
3882 /*!
3883 * \brief Queue a read action to send a text message
3884 *
3885 * \param chan The channel to queue the action on
3886 * \param body The body of the message
3887 *
3888 * \retval -1 on error
3889 * \retval 0 on success
3890 */
3891 static int queue_sendtext(struct ast_channel *chan, const char *body)
3892 {
3893 return queue_read_action_payload(chan, (const unsigned char *)body,
3894 strlen(body) + 1, AST_FRAME_READ_ACTION_SEND_TEXT);
3895 }
3896
3897 /*!
3898 * \brief Queue a read action to send a text data message
3899 *
3900 * \param chan The channel to queue the action on
3901 * \param body The body of the message
3902 * \param content_type The message's content type
3903 *
3904 * \retval -1 on error
3905 * \retval 0 on success
3906 */
3907 static int queue_sendtext_data(struct ast_channel *chan, const char *body,
3908 const char *content_type)
3909 {
3910 int res;
3911 struct ast_msg_data *obj;
3912
3913 obj = ast_msg_data_alloc2(AST_MSG_DATA_SOURCE_TYPE_UNKNOWN,
3914 NULL, NULL, content_type, body);
3915 if (!obj) {
3916 return -1;
3917 }
3918
3919 res = queue_read_action_payload(chan, (const unsigned char *)obj,
3920 ast_msg_data_get_length(obj), AST_FRAME_READ_ACTION_SEND_TEXT_DATA);
3921
3922 ast_free(obj);
3923 return res;
3924 }
3925
3926 static int action_sendtext(struct mansession *s, const struct message *m)
3927 {
3928 struct ast_channel *c;
3929 const char *name = astman_get_header(m, "Channel");
3930 const char *textmsg = astman_get_header(m, "Message");
3931 const char *content_type = astman_get_header(m, "Content-Type");
3932 int res;
3933
3934 if (ast_strlen_zero(name)) {
3935 astman_send_error(s, m, "No channel specified");
3936 return 0;
3937 }
3938
3939 if (ast_strlen_zero(textmsg)) {
3940 astman_send_error(s, m, "No Message specified");
3941 return 0;
3942 }
3943
3944 c = ast_channel_get_by_name(name);
3945 if (!c) {
3946 astman_send_error(s, m, "No such channel");
3947 return 0;
3948 }
3949
3950 /*
3951 * If the "extra" data is not available, then send using "string" only.
3952 * Doing such maintains backward compatibilities.
3953 */
3954 res = ast_strlen_zero(content_type) ? queue_sendtext(c, textmsg) :
3955 queue_sendtext_data(c, textmsg, content_type);
3956
3957 ast_channel_unref(c);
3958
3959 if (res >= 0) {
3960 astman_send_ack(s, m, "Success");
3961 } else {
3962 astman_send_error(s, m, "Failure");
3963 }
3964
3965 return 0;
3966 }
3967
3968 static int async_goto_with_discard_bridge_after(struct ast_channel *chan, const char *context, const char *exten, int priority)
3969 {
3970 ast_bridge_discard_after_goto(chan);
3971 return ast_async_goto(chan, context, exten, priority);
3972 }
3973
3974 /*! \brief action_redirect: The redirect manager command */
3975 static int action_redirect(struct mansession *s, const struct message *m)
3976 {
3977 char buf[256];
3978 const char *name = astman_get_header(m, "Channel");
3979 const char *name2 = astman_get_header(m, "ExtraChannel");
3980 const char *exten = astman_get_header(m, "Exten");
3981 const char *exten2 = astman_get_header(m, "ExtraExten");
3982 const char *context = astman_get_header(m, "Context");
3983 const char *context2 = astman_get_header(m, "ExtraContext");
3984 const char *priority = astman_get_header(m, "Priority");
3985 const char *priority2 = astman_get_header(m, "ExtraPriority");
3986 struct ast_channel *chan;
3987 struct ast_channel *chan2;
3988 int pi = 0;
3989 int pi2 = 0;
3990 int res;
3991 int chan1_wait = 0;
3992 int chan2_wait = 0;
3993
3994 if (ast_strlen_zero(name)) {
3995 astman_send_error(s, m, "Channel not specified");
3996 return 0;
3997 }
3998
3999 if (ast_strlen_zero(context)) {
4000 astman_send_error(s, m, "Context not specified");
4001 return 0;
4002 }
4003 if (ast_strlen_zero(exten)) {
4004 astman_send_error(s, m, "Exten not specified");
4005 return 0;
4006 }
4007 if (ast_strlen_zero(priority)) {
4008 astman_send_error(s, m, "Priority not specified");
4009 return 0;
4010 }
4011 if (sscanf(priority, "%30d", &pi) != 1) {
4012 pi = ast_findlabel_extension(NULL, context, exten, priority, NULL);
4013 }
4014 if (pi < 1) {
4015 astman_send_error(s, m, "Priority is invalid");
4016 return 0;
4017 }
4018
4019 if (!ast_strlen_zero(name2) && !ast_strlen_zero(context2)) {
4020 /* We have an ExtraChannel and an ExtraContext */
4021 if (ast_strlen_zero(exten2)) {
4022 astman_send_error(s, m, "ExtraExten not specified");
4023 return 0;
4024 }
4025 if (ast_strlen_zero(priority2)) {
4026 astman_send_error(s, m, "ExtraPriority not specified");
4027 return 0;
4028 }
4029 if (sscanf(priority2, "%30d", &pi2) != 1) {
4030 pi2 = ast_findlabel_extension(NULL, context2, exten2, priority2, NULL);
4031 }
4032 if (pi2 < 1) {
4033 astman_send_error(s, m, "ExtraPriority is invalid");
4034 return 0;
4035 }
4036 }
4037
4038 chan = ast_channel_get_by_name(name);
4039 if (!chan) {
4040 snprintf(buf, sizeof(buf), "Channel does not exist: %s", name);
4041 astman_send_error(s, m, buf);
4042 return 0;
4043 }
4044 if (ast_check_hangup_locked(chan)) {
4045 astman_send_error(s, m, "Redirect failed, channel not up.");
4046 chan = ast_channel_unref(chan);
4047 return 0;
4048 }
4049
4050 if (ast_strlen_zero(name2)) {
4051 /* Single channel redirect in progress. */
4052 res = async_goto_with_discard_bridge_after(chan, context, exten, pi);
4053 if (!res) {
4054 astman_send_ack(s, m, "Redirect successful");
4055 } else {
4056 astman_send_error(s, m, "Redirect failed");
4057 }
4058 chan = ast_channel_unref(chan);
4059 return 0;
4060 }
4061
4062 chan2 = ast_channel_get_by_name(name2);
4063 if (!chan2) {
4064 snprintf(buf, sizeof(buf), "ExtraChannel does not exist: %s", name2);
4065 astman_send_error(s, m, buf);
4066 chan = ast_channel_unref(chan);
4067 return 0;
4068 }
4069 if (ast_check_hangup_locked(chan2)) {
4070 astman_send_error(s, m, "Redirect failed, extra channel not up.");
4071 chan2 = ast_channel_unref(chan2);
4072 chan = ast_channel_unref(chan);
4073 return 0;
4074 }
4075
4076 /* Dual channel redirect in progress. */
4077 ast_channel_lock(chan);
4078 if (ast_channel_is_bridged(chan)) {
4079 ast_set_flag(ast_channel_flags(chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
4080 chan1_wait = 1;
4081 }
4082 ast_channel_unlock(chan);
4083
4084 ast_channel_lock(chan2);
4085 if (ast_channel_is_bridged(chan2)) {
4086 ast_set_flag(ast_channel_flags(chan2), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
4087 chan2_wait = 1;
4088 }
4089 ast_channel_unlock(chan2);
4090
4091 res = async_goto_with_discard_bridge_after(chan, context, exten, pi);
4092 if (!res) {
4093 if (!ast_strlen_zero(context2)) {
4094 res = async_goto_with_discard_bridge_after(chan2, context2, exten2, pi2);
4095 } else {
4096 res = async_goto_with_discard_bridge_after(chan2, context, exten, pi);
4097 }
4098 if (!res) {
4099 astman_send_ack(s, m, "Dual Redirect successful");
4100 } else {
4101 astman_send_error(s, m, "Secondary redirect failed");
4102 }
4103 } else {
4104 astman_send_error(s, m, "Redirect failed");
4105 }
4106
4107 /* Release the bridge wait. */
4108 if (chan1_wait) {
4109 ast_channel_clear_flag(chan, AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
4110 }
4111 if (chan2_wait) {
4112 ast_channel_clear_flag(chan2, AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT);
4113 }
4114
4115 chan2 = ast_channel_unref(chan2);
4116 chan = ast_channel_unref(chan);
4117 return 0;
4118 }
4119
4120 static int action_blind_transfer(struct mansession *s, const struct message *m)
4121 {
4122 const char *name = astman_get_header(m, "Channel");
4123 const char *exten = astman_get_header(m, "Exten");
4124 const char *context = astman_get_header(m, "Context");
4125 struct ast_channel *chan;
4126
4127 if (ast_strlen_zero(name)) {
4128 astman_send_error(s, m, "No channel specified");
4129 return 0;
4130 }
4131
4132 if (ast_strlen_zero(exten)) {
4133 astman_send_error(s, m, "No extension specified");
4134 return 0;
4135 }
4136
4137 chan = ast_channel_get_by_name(name);
4138 if (!chan) {
4139 astman_send_error(s, m, "Channel specified does not exist");
4140 return 0;
4141 }
4142
4143 if (ast_strlen_zero(context)) {
4144 context = ast_channel_context(chan);
4145 }
4146
4147 switch (ast_bridge_transfer_blind(1, chan, exten, context, NULL, NULL)) {
4148 case AST_BRIDGE_TRANSFER_NOT_PERMITTED:
4149 astman_send_error(s, m, "Transfer not permitted");
4150 break;
4151 case AST_BRIDGE_TRANSFER_INVALID:
4152 astman_send_error(s, m, "Transfer invalid");
4153 break;
4154 case AST_BRIDGE_TRANSFER_FAIL:
4155 astman_send_error(s, m, "Transfer failed");
4156 break;
4157 case AST_BRIDGE_TRANSFER_SUCCESS:
4158 astman_send_ack(s, m, "Transfer succeeded");
4159 break;
4160 }
4161
4162 ast_channel_unref(chan);
4163 return 0;
4164 }
4165
4166 static int action_atxfer(struct mansession *s, const struct message *m)
4167 {
4168 const char *name = astman_get_header(m, "Channel");
4169 const char *exten = astman_get_header(m, "Exten");
4170 const char *context = astman_get_header(m, "Context");
4171 struct ast_channel *chan = NULL;
4172 char feature_code[AST_FEATURE_MAX_LEN];
4173 const char *digit;
4174
4175 if (ast_strlen_zero(name)) {
4176 astman_send_error(s, m, "No channel specified");
4177 return 0;
4178 }
4179 if (ast_strlen_zero(exten)) {
4180 astman_send_error(s, m, "No extension specified");
4181 return 0;
4182 }
4183
4184 if (!(chan = ast_channel_get_by_name(name))) {
4185 astman_send_error(s, m, "Channel specified does not exist");
4186 return 0;
4187 }
4188
4189 ast_channel_lock(chan);
4190 if (ast_get_builtin_feature(chan, "atxfer", feature_code, sizeof(feature_code)) ||
4191 ast_strlen_zero(feature_code)) {
4192 ast_channel_unlock(chan);
4193 astman_send_error(s, m, "No attended transfer feature code found");
4194 ast_channel_unref(chan);
4195 return 0;
4196 }
4197 ast_channel_unlock(chan);
4198
4199 if (!ast_strlen_zero(context)) {
4200 pbx_builtin_setvar_helper(chan, "TRANSFER_CONTEXT", context);
4201 }
4202
4203 for (digit = feature_code; *digit; ++digit) {
4204 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
4205 ast_queue_frame(chan, &f);
4206 }
4207
4208 for (digit = exten; *digit; ++digit) {
4209 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
4210 ast_queue_frame(chan, &f);
4211 }
4212
4213 chan = ast_channel_unref(chan);
4214
4215 astman_send_ack(s, m, "Atxfer successfully queued");
4216
4217 return 0;
4218 }
4219
4220 static int action_cancel_atxfer(struct mansession *s, const struct message *m)
4221 {
4222 const char *name = astman_get_header(m, "Channel");
4223 struct ast_channel *chan = NULL;
4224 char *feature_code;
4225 const char *digit;
4226
4227 if (ast_strlen_zero(name)) {
4228 astman_send_error(s, m, "No channel specified");
4229 return 0;
4230 }
4231
4232 if (!(chan = ast_channel_get_by_name(name))) {
4233 astman_send_error(s, m, "Channel specified does not exist");
4234 return 0;
4235 }
4236
4237 ast_channel_lock(chan);
4238 feature_code = ast_get_chan_features_atxferabort(chan);
4239 ast_channel_unlock(chan);
4240
4241 if (!feature_code) {
4242 astman_send_error(s, m, "No disconnect feature code found");
4243 ast_channel_unref(chan);
4244 return 0;
4245 }
4246
4247 for (digit = feature_code; *digit; ++digit) {
4248 struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = *digit };
4249 ast_queue_frame(chan, &f);
4250 }
4251 ast_free(feature_code);
4252
4253 chan = ast_channel_unref(chan);
4254
4255 astman_send_ack(s, m, "CancelAtxfer successfully queued");
4256
4257 return 0;
4258 }
4259
4260
4261 static int check_blacklist(const char *cmd)
4262 {
4263 char *cmd_copy, *cur_cmd;
4264 char *cmd_words[AST_MAX_CMD_LEN] = { NULL, };
4265 int i;
4266
4267 cmd_copy = ast_strdupa(cmd);
4268 for (i = 0; i < MAX_BLACKLIST_CMD_LEN && (cur_cmd = strsep(&cmd_copy, " ")); i++) {
4269 cur_cmd = ast_strip(cur_cmd);
4270 if (ast_strlen_zero(cur_cmd)) {
4271 i--;
4272 continue;
4273 }
4274
4275 cmd_words[i] = cur_cmd;
4276 }
4277
4278 for (i = 0; i < ARRAY_LEN(command_blacklist); i++) {
4279 int j, match = 1;
4280
4281 for (j = 0; command_blacklist[i].words[j]; j++) {
4282 if (ast_strlen_zero(cmd_words[j]) || strcasecmp(cmd_words[j], command_blacklist[i].words[j])) {
4283 match = 0;
4284 break;
4285 }
4286 }
4287
4288 if (match) {
4289 return 1;
4290 }
4291 }
4292
4293 return 0;
4294 }
4295
4296 /*! \brief Manager command "command" - execute CLI command */
4297 static int action_command(struct mansession *s, const struct message *m)
4298 {
4299 const char *cmd = astman_get_header(m, "Command");
4300 char *buf = NULL, *final_buf = NULL, *delim, *output;
4301 char template[] = "/tmp/ast-ami-XXXXXX"; /* template for temporary file */
4302 int fd, ret;
4303 off_t len;
4304
4305 if (ast_strlen_zero(cmd)) {
4306 astman_send_error(s, m, "No command provided");
4307 return 0;
4308 }
4309
4310 if (check_blacklist(cmd)) {
4311 astman_send_error(s, m, "Command blacklisted");
4312 return 0;
4313 }
4314
4315 if ((fd = mkstemp(template)) < 0) {
4316 astman_send_error_va(s, m, "Failed to create temporary file: %s", strerror(errno));
4317 return 0;
4318 }
4319
4320 ret = ast_cli_command(fd, cmd);
4321 astman_send_response_full(s, m, ret == RESULT_SUCCESS ? "Success" : "Error", MSG_MOREDATA, NULL);
4322
4323 /* Determine number of characters available */
4324 if ((len = lseek(fd, 0, SEEK_END)) < 0) {
4325 astman_append(s, "Message: Failed to determine number of characters: %s\r\n", strerror(errno));
4326 goto action_command_cleanup;
4327 }
4328
4329 /* This has a potential to overflow the stack. Hence, use the heap. */
4330 buf = ast_malloc(len + 1);
4331 final_buf = ast_malloc(len + 1);
4332
4333 if (!buf || !final_buf) {
4334 astman_append(s, "Message: Memory allocation failure\r\n");
4335 goto action_command_cleanup;
4336 }
4337
4338 if (lseek(fd, 0, SEEK_SET) < 0) {
4339 astman_append(s, "Message: Failed to set position on temporary file: %s\r\n", strerror(errno));
4340 goto action_command_cleanup;
4341 }
4342
4343 if (read(fd, buf, len) < 0) {
4344 astman_append(s, "Message: Failed to read from temporary file: %s\r\n", strerror(errno));
4345 goto action_command_cleanup;
4346 }
4347
4348 buf[len] = '\0';
4349 term_strip(final_buf, buf, len);
4350 final_buf[len] = '\0';
4351
4352 /* Trim trailing newline */
4353 if (len && final_buf[len - 1] == '\n') {
4354 final_buf[len - 1] = '\0';
4355 }
4356
4357 astman_append(s, "Message: Command output follows\r\n");
4358
4359 delim = final_buf;
4360 while ((output = strsep(&delim, "\n"))) {
4361 astman_append(s, "Output: %s\r\n", output);
4362 }
4363
4364 action_command_cleanup:
4365 astman_append(s, "\r\n");
4366
4367 close(fd);
4368 unlink(template);
4369
4370 ast_free(buf);
4371 ast_free(final_buf);
4372
4373 return 0;
4374 }
4375
4376 /*! \brief helper function for originate */
4377 struct fast_originate_helper {
4378 int timeout;
4379 struct ast_format_cap *cap; /*!< Codecs used for a call */
4380 int early_media;
4381 AST_DECLARE_STRING_FIELDS (
4382 AST_STRING_FIELD(tech);
4383 /*! data can contain a channel name, extension number, username, password, etc. */
4384 AST_STRING_FIELD(data);
4385 AST_STRING_FIELD(app);
4386 AST_STRING_FIELD(appdata);
4387 AST_STRING_FIELD(cid_name);
4388 AST_STRING_FIELD(cid_num);
4389 AST_STRING_FIELD(context);
4390 AST_STRING_FIELD(exten);
4391 AST_STRING_FIELD(idtext);
4392 AST_STRING_FIELD(account);
4393 AST_STRING_FIELD(channelid);
4394 AST_STRING_FIELD(otherchannelid);
4395 );
4396 int priority;
4397 struct ast_variable *vars;
4398 };
4399
4400 /*!
4401 * \internal
4402 *
4403 * \param doomed Struct to destroy.
4404 */
4405 static void destroy_fast_originate_helper(struct fast_originate_helper *doomed)
4406 {
4407 ao2_cleanup(doomed->cap);
4408 ast_variables_destroy(doomed->vars);
4409 ast_string_field_free_memory(doomed);
4410 ast_free(doomed);
4411 }
4412
4413 static void *fast_originate(void *data)
4414 {
4415 struct fast_originate_helper *in = data;
4416 int res;
4417 int reason = 0;
4418 struct ast_channel *chan = NULL, *chans[1];
4419 char requested_channel[AST_CHANNEL_NAME];
4420 struct ast_assigned_ids assignedids = {
4421 .uniqueid = in->channelid,
4422 .uniqueid2 = in->otherchannelid
4423 };
4424
4425 if (!ast_strlen_zero(in->app)) {
4426 res = ast_pbx_outgoing_app(in->tech, in->cap, in->data,
4427 in->timeout, in->app, in->appdata, &reason,
4428 AST_OUTGOING_WAIT,
4429 S_OR(in->cid_num, NULL),
4430 S_OR(in->cid_name, NULL),
4431 in->vars, in->account, &chan, &assignedids);
4432 } else {
4433 res = ast_pbx_outgoing_exten(in->tech, in->cap, in->data,
4434 in->timeout, in->context, in->exten, in->priority, &reason,
4435 AST_OUTGOING_WAIT,
4436 S_OR(in->cid_num, NULL),
4437 S_OR(in->cid_name, NULL),
4438 in->vars, in->account, &chan, in->early_media, &assignedids);
4439 }
4440
4441 if (!chan) {
4442 snprintf(requested_channel, AST_CHANNEL_NAME, "%s/%s", in->tech, in->data);
4443 }
4444 /* Tell the manager what happened with the channel */
4445 chans[0] = chan;
4446 if (!ast_strlen_zero(in->app)) {
4447 ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
4448 "%s"
4449 "Response: %s\r\n"
4450 "Channel: %s\r\n"
4451 "Application: %s\r\n"
4452 "Data: %s\r\n"
4453 "Reason: %d\r\n"
4454 "Uniqueid: %s\r\n"
4455 "CallerIDNum: %s\r\n"
4456 "CallerIDName: %s\r\n",
4457 in->idtext, res ? "Failure" : "Success",
4458 chan ? ast_channel_name(chan) : requested_channel,
4459 in->app, in->appdata, reason,
4460 chan ? ast_channel_uniqueid(chan) : S_OR(in->channelid, "<unknown>"),
4461 S_OR(in->cid_num, "<unknown>"),
4462 S_OR(in->cid_name, "<unknown>")
4463 );
4464 } else {
4465 ast_manager_event_multichan(EVENT_FLAG_CALL, "OriginateResponse", chan ? 1 : 0, chans,
4466 "%s"
4467 "Response: %s\r\n"
4468 "Channel: %s\r\n"
4469 "Context: %s\r\n"
4470 "Exten: %s\r\n"
4471 "Reason: %d\r\n"
4472 "Uniqueid: %s\r\n"
4473 "CallerIDNum: %s\r\n"
4474 "CallerIDName: %s\r\n",
4475 in->idtext, res ? "Failure" : "Success",
4476 chan ? ast_channel_name(chan) : requested_channel,
4477 in->context, in->exten, reason,
4478 chan ? ast_channel_uniqueid(chan) : S_OR(in->channelid, "<unknown>"),
4479 S_OR(in->cid_num, "<unknown>"),
4480 S_OR(in->cid_name, "<unknown>")
4481 );
4482 }
4483
4484 /* Locked and ref'd by ast_pbx_outgoing_exten or ast_pbx_outgoing_app */
4485 if (chan) {
4486 ast_channel_unlock(chan);
4487 ast_channel_unref(chan);
4488 }
4489 destroy_fast_originate_helper(in);
4490 return NULL;
4491 }
4492
4493 static int aocmessage_get_unit_entry(const struct message *m, struct ast_aoc_unit_entry *entry, unsigned int entry_num)
4494 {
4495 const char *unitamount;
4496 const char *unittype;
4497 struct ast_str *str = ast_str_alloca(32);
4498
4499 memset(entry, 0, sizeof(*entry));
4500
4501 ast_str_set(&str, 0, "UnitAmount(%u)", entry_num);
4502 unitamount = astman_get_header(m, ast_str_buffer(str));
4503
4504 ast_str_set(&str, 0, "UnitType(%u)", entry_num);
4505 unittype = astman_get_header(m, ast_str_buffer(str));
4506
4507 if (!ast_strlen_zero(unitamount) && (sscanf(unitamount, "%30u", &entry->amount) == 1)) {
4508 entry->valid_amount = 1;
4509 }
4510
4511 if (!ast_strlen_zero(unittype) && sscanf(unittype, "%30u", &entry->type) == 1) {
4512 entry->valid_type = 1;
4513 }
4514
4515 return 0;
4516 }
4517
4518 static struct ast_aoc_decoded *action_aoc_de_message(struct mansession *s, const struct message *m)
4519 {
4520 const char *msgtype = astman_get_header(m, "MsgType");
4521 const char *chargetype = astman_get_header(m, "ChargeType");
4522 const char *currencyname = astman_get_header(m, "CurrencyName");
4523 const char *currencyamount = astman_get_header(m, "CurrencyAmount");
4524 const char *mult = astman_get_header(m, "CurrencyMultiplier");
4525 const char *totaltype = astman_get_header(m, "TotalType");
4526 const char *aocbillingid = astman_get_header(m, "AOCBillingId");
4527 const char *association_id= astman_get_header(m, "ChargingAssociationId");
4528 const char *association_num = astman_get_header(m, "ChargingAssociationNumber");
4529 const char *association_plan = astman_get_header(m, "ChargingAssociationPlan");
4530
4531 enum ast_aoc_type _msgtype;
4532 enum ast_aoc_charge_type _chargetype;
4533 enum ast_aoc_currency_multiplier _mult = AST_AOC_MULT_ONE;
4534 enum ast_aoc_total_type _totaltype = AST_AOC_TOTAL;
4535 enum ast_aoc_billing_id _billingid = AST_AOC_BILLING_NA;
4536 unsigned int _currencyamount = 0;
4537 int _association_id = 0;
4538 unsigned int _association_plan = 0;
4539
4540 struct ast_aoc_decoded *decoded = NULL;
4541
4542 if (ast_strlen_zero(chargetype)) {
4543 astman_send_error(s, m, "ChargeType not specified");
4544 goto aocmessage_cleanup;
4545 }
4546
4547 _msgtype = strcasecmp(msgtype, "d") ? AST_AOC_E : AST_AOC_D;
4548
4549 if (!strcasecmp(chargetype, "NA")) {
4550 _chargetype = AST_AOC_CHARGE_NA;
4551 } else if (!strcasecmp(chargetype, "Free")) {
4552 _chargetype = AST_AOC_CHARGE_FREE;
4553 } else if (!strcasecmp(chargetype, "Currency")) {
4554 _chargetype = AST_AOC_CHARGE_CURRENCY;
4555 } else if (!strcasecmp(chargetype, "Unit")) {
4556 _chargetype = AST_AOC_CHARGE_UNIT;
4557 } else {
4558 astman_send_error(s, m, "Invalid ChargeType");
4559 goto aocmessage_cleanup;
4560 }
4561
4562 if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
4563
4564 if (ast_strlen_zero(currencyamount) || (sscanf(currencyamount, "%30u", &_currencyamount) != 1)) {
4565 astman_send_error(s, m, "Invalid CurrencyAmount, CurrencyAmount is a required when ChargeType is Currency");
4566 goto aocmessage_cleanup;
4567 }
4568
4569 if (ast_strlen_zero(mult)) {
4570 astman_send_error(s, m, "ChargeMultiplier unspecified, ChargeMultiplier is required when ChargeType is Currency.");
4571 goto aocmessage_cleanup;
4572 } else if (!strcasecmp(mult, "onethousandth")) {
4573 _mult = AST_AOC_MULT_ONETHOUSANDTH;
4574 } else if (!strcasecmp(mult, "onehundredth")) {
4575 _mult = AST_AOC_MULT_ONEHUNDREDTH;
4576 } else if (!strcasecmp(mult, "onetenth")) {
4577 _mult = AST_AOC_MULT_ONETENTH;
4578 } else if (!strcasecmp(mult, "one")) {
4579 _mult = AST_AOC_MULT_ONE;
4580 } else if (!strcasecmp(mult, "ten")) {
4581 _mult = AST_AOC_MULT_TEN;
4582 } else if (!strcasecmp(mult, "hundred")) {
4583 _mult = AST_AOC_MULT_HUNDRED;
4584 } else if (!strcasecmp(mult, "thousand")) {
4585 _mult = AST_AOC_MULT_THOUSAND;
4586 } else {
4587 astman_send_error(s, m, "Invalid ChargeMultiplier");
4588 goto aocmessage_cleanup;
4589 }
4590 }
4591
4592 /* create decoded object and start setting values */
4593 if (!(decoded = ast_aoc_create(_msgtype, _chargetype, 0))) {
4594 astman_send_error(s, m, "Message Creation Failed");
4595 goto aocmessage_cleanup;
4596 }
4597
4598 if (_msgtype == AST_AOC_D) {
4599 if (!ast_strlen_zero(totaltype) && !strcasecmp(totaltype, "subtotal")) {
4600 _totaltype = AST_AOC_SUBTOTAL;
4601 }
4602
4603 if (ast_strlen_zero(aocbillingid)) {
4604 /* ignore this is optional */
4605 } else if (!strcasecmp(aocbillingid, "Normal")) {
4606 _billingid = AST_AOC_BILLING_NORMAL;
4607 } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
4608 _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
4609 } else if (!strcasecmp(aocbillingid, "CreditCard")) {
4610 _billingid = AST_AOC_BILLING_CREDIT_CARD;
4611 } else {
4612 astman_send_error(s, m, "Invalid AOC-D AOCBillingId");
4613 goto aocmessage_cleanup;
4614 }
4615 } else {
4616 if (ast_strlen_zero(aocbillingid)) {
4617 /* ignore this is optional */
4618 } else if (!strcasecmp(aocbillingid, "Normal")) {
4619 _billingid = AST_AOC_BILLING_NORMAL;
4620 } else if (!strcasecmp(aocbillingid, "ReverseCharge")) {
4621 _billingid = AST_AOC_BILLING_REVERSE_CHARGE;
4622 } else if (!strcasecmp(aocbillingid, "CreditCard")) {
4623 _billingid = AST_AOC_BILLING_CREDIT_CARD;
4624 } else if (!strcasecmp(aocbillingid, "CallFwdUnconditional")) {
4625 _billingid = AST_AOC_BILLING_CALL_FWD_UNCONDITIONAL;
4626 } else if (!strcasecmp(aocbillingid, "CallFwdBusy")) {
4627 _billingid = AST_AOC_BILLING_CALL_FWD_BUSY;
4628 } else if (!strcasecmp(aocbillingid, "CallFwdNoReply")) {
4629 _billingid = AST_AOC_BILLING_CALL_FWD_NO_REPLY;
4630 } else if (!strcasecmp(aocbillingid, "CallDeflection")) {
4631 _billingid = AST_AOC_BILLING_CALL_DEFLECTION;
4632 } else if (!strcasecmp(aocbillingid, "CallTransfer")) {
4633 _billingid = AST_AOC_BILLING_CALL_TRANSFER;
4634 } else {
4635 astman_send_error(s, m, "Invalid AOC-E AOCBillingId");
4636 goto aocmessage_cleanup;
4637 }
4638
4639 if (!ast_strlen_zero(association_id) && (sscanf(association_id, "%30d", &_association_id) != 1)) {
4640 astman_send_error(s, m, "Invalid ChargingAssociationId");
4641 goto aocmessage_cleanup;
4642 }
4643 if (!ast_strlen_zero(association_plan) && (sscanf(association_plan, "%30u", &_association_plan) != 1)) {
4644 astman_send_error(s, m, "Invalid ChargingAssociationPlan");
4645 goto aocmessage_cleanup;
4646 }
4647
4648 if (_association_id) {
4649 ast_aoc_set_association_id(decoded, _association_id);
4650 } else if (!ast_strlen_zero(association_num)) {
4651 ast_aoc_set_association_number(decoded, association_num, _association_plan);
4652 }
4653 }
4654
4655 if (_chargetype == AST_AOC_CHARGE_CURRENCY) {
4656 ast_aoc_set_currency_info(decoded, _currencyamount, _mult, ast_strlen_zero(currencyname) ? NULL : currencyname);
4657 } else if (_chargetype == AST_AOC_CHARGE_UNIT) {
4658 struct ast_aoc_unit_entry entry;
4659 int i;
4660
4661 /* multiple unit entries are possible, lets get them all */
4662 for (i = 0; i < 32; i++) {
4663 if (aocmessage_get_unit_entry(m, &entry, i)) {
4664 break; /* that's the end then */
4665 }
4666
4667 ast_aoc_add_unit_entry(decoded, entry.valid_amount, entry.amount, entry.valid_type, entry.type);
4668 }
4669
4670 /* at least one unit entry is required */
4671 if (!i) {
4672 astman_send_error(s, m, "Invalid UnitAmount(0), At least one valid unit entry is required when ChargeType is set to Unit");
4673 goto aocmessage_cleanup;
4674 }
4675
4676 }
4677
4678 ast_aoc_set_billing_id(decoded, _billingid);
4679 ast_aoc_set_total_type(decoded, _totaltype);
4680
4681 return decoded;
4682
4683 aocmessage_cleanup:
4684
4685 ast_aoc_destroy_decoded(decoded);
4686 return NULL;
4687 }
4688
4689 static int action_aoc_s_submessage(struct mansession *s, const struct message *m,
4690 struct ast_aoc_decoded *decoded)
4691 {
4692 const char *chargeditem = __astman_get_header(m, "ChargedItem", GET_HEADER_LAST_MATCH);
4693 const char *ratetype = __astman_get_header(m, "RateType", GET_HEADER_LAST_MATCH);
4694 const char *currencyname = __astman_get_header(m, "CurrencyName", GET_HEADER_LAST_MATCH);
4695 const char *currencyamount = __astman_get_header(m, "CurrencyAmount", GET_HEADER_LAST_MATCH);
4696 const char *mult = __astman_get_header(m, "CurrencyMultiplier", GET_HEADER_LAST_MATCH);
4697 const char *time = __astman_get_header(m, "Time", GET_HEADER_LAST_MATCH);
4698 const char *timescale = __astman_get_header(m, "TimeScale", GET_HEADER_LAST_MATCH);
4699 const char *granularity = __astman_get_header(m, "Granularity", GET_HEADER_LAST_MATCH);
4700 const char *granularitytimescale = __astman_get_header(m, "GranularityTimeScale", GET_HEADER_LAST_MATCH);
4701 const char *chargingtype = __astman_get_header(m, "ChargingType", GET_HEADER_LAST_MATCH);
4702 const char *volumeunit = __astman_get_header(m, "VolumeUnit", GET_HEADER_LAST_MATCH);
4703 const char *code = __astman_get_header(m, "Code", GET_HEADER_LAST_MATCH);
4704
4705 enum ast_aoc_s_charged_item _chargeditem;
4706 enum ast_aoc_s_rate_type _ratetype;
4707 enum ast_aoc_currency_multiplier _mult = AST_AOC_MULT_ONE;
4708 unsigned int _currencyamount = 0;
4709 unsigned int _code;
4710 unsigned int _time = 0;
4711 enum ast_aoc_time_scale _scale = 0;
4712 unsigned int _granularity = 0;
4713 enum ast_aoc_time_scale _granularity_time_scale = AST_AOC_TIME_SCALE_MINUTE;
4714 int _step = 0;
4715 enum ast_aoc_volume_unit _volumeunit = 0;
4716
4717 if (ast_strlen_zero(chargeditem)) {
4718 astman_send_error(s, m, "ChargedItem not specified");
4719 goto aocmessage_cleanup;
4720 }
4721
4722 if (ast_strlen_zero(ratetype)) {
4723 astman_send_error(s, m, "RateType not specified");
4724 goto aocmessage_cleanup;
4725 }
4726
4727 if (!strcasecmp(chargeditem, "NA")) {
4728 _chargeditem = AST_AOC_CHARGED_ITEM_NA;
4729 } else if (!strcasecmp(chargeditem, "SpecialArrangement")) {
4730 _chargeditem = AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT;
4731 } else if (!strcasecmp(chargeditem, "BasicCommunication")) {
4732 _chargeditem = AST_AOC_CHARGED_ITEM_BASIC_COMMUNICATION;
4733 } else if (!strcasecmp(chargeditem, "CallAttempt")) {
4734 _chargeditem = AST_AOC_CHARGED_ITEM_CALL_ATTEMPT;
4735 } else if (!strcasecmp(chargeditem, "CallSetup")) {
4736 _chargeditem = AST_AOC_CHARGED_ITEM_CALL_SETUP;
4737 } else if (!strcasecmp(chargeditem, "UserUserInfo")) {
4738 _chargeditem = AST_AOC_CHARGED_ITEM_USER_USER_INFO;
4739 } else if (!strcasecmp(chargeditem, "SupplementaryService")) {
4740 _chargeditem = AST_AOC_CHARGED_ITEM_SUPPLEMENTARY_SERVICE;
4741 } else {
4742 astman_send_error(s, m, "Invalid ChargedItem");
4743 goto aocmessage_cleanup;
4744 }
4745
4746 if (!strcasecmp(ratetype, "NA")) {
4747 _ratetype = AST_AOC_RATE_TYPE_NA;
4748 } else if (!strcasecmp(ratetype, "Free")) {
4749 _ratetype = AST_AOC_RATE_TYPE_FREE;
4750 } else if (!strcasecmp(ratetype, "FreeFromBeginning")) {
4751 _ratetype = AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING;
4752 } else if (!strcasecmp(ratetype, "Duration")) {
4753 _ratetype = AST_AOC_RATE_TYPE_DURATION;
4754 } else if (!strcasecmp(ratetype, "Flat")) {
4755 _ratetype = AST_AOC_RATE_TYPE_FLAT;
4756 } else if (!strcasecmp(ratetype, "Volume")) {
4757 _ratetype = AST_AOC_RATE_TYPE_VOLUME;
4758 } else if (!strcasecmp(ratetype, "SpecialCode")) {
4759 _ratetype = AST_AOC_RATE_TYPE_SPECIAL_CODE;
4760 } else {
4761 astman_send_error(s, m, "Invalid RateType");
4762 goto aocmessage_cleanup;
4763 }
4764
4765 if (_ratetype > AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING) {
4766 if (ast_strlen_zero(currencyamount) || (sscanf(currencyamount, "%30u",
4767 &_currencyamount) != 1)) {
4768 astman_send_error(s, m, "Invalid CurrencyAmount, CurrencyAmount is a required when RateType is non-free");
4769 goto aocmessage_cleanup;
4770 }
4771
4772 if (ast_strlen_zero(mult)) {
4773 astman_send_error(s, m, "ChargeMultiplier unspecified, ChargeMultiplier is required when ChargeType is Currency.");
4774 goto aocmessage_cleanup;
4775 } else if (!strcasecmp(mult, "onethousandth")) {
4776 _mult = AST_AOC_MULT_ONETHOUSANDTH;
4777 } else if (!strcasecmp(mult, "onehundredth")) {
4778 _mult = AST_AOC_MULT_ONEHUNDREDTH;
4779 } else if (!strcasecmp(mult, "onetenth")) {
4780 _mult = AST_AOC_MULT_ONETENTH;
4781 } else if (!strcasecmp(mult, "one")) {
4782 _mult = AST_AOC_MULT_ONE;
4783 } else if (!strcasecmp(mult, "ten")) {
4784 _mult = AST_AOC_MULT_TEN;
4785 } else if (!strcasecmp(mult, "hundred")) {
4786 _mult = AST_AOC_MULT_HUNDRED;
4787 } else if (!strcasecmp(mult, "thousand")) {
4788 _mult = AST_AOC_MULT_THOUSAND;
4789 } else {
4790 astman_send_error(s, m, "Invalid ChargeMultiplier");
4791 goto aocmessage_cleanup;
4792 }
4793 }
4794
4795 if (_ratetype == AST_AOC_RATE_TYPE_DURATION) {
4796 if (ast_strlen_zero(timescale)) {
4797 astman_send_error(s, m, "TimeScale unspecified, TimeScale is required when RateType is Duration.");
4798 goto aocmessage_cleanup;
4799 } else if (!strcasecmp(timescale, "onehundredthsecond")) {
4800 _scale = AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
4801 } else if (!strcasecmp(timescale, "onetenthsecond")) {
4802 _scale = AST_AOC_TIME_SCALE_TENTH_SECOND;
4803 } else if (!strcasecmp(timescale, "second")) {
4804 _scale = AST_AOC_TIME_SCALE_SECOND;
4805 } else if (!strcasecmp(timescale, "tenseconds")) {
4806 _scale = AST_AOC_TIME_SCALE_TEN_SECOND;
4807 } else if (!strcasecmp(timescale, "minute")) {
4808 _scale = AST_AOC_TIME_SCALE_MINUTE;
4809 } else if (!strcasecmp(timescale, "hour")) {
4810 _scale = AST_AOC_TIME_SCALE_HOUR;
4811 } else if (!strcasecmp(timescale, "day")) {
4812 _scale = AST_AOC_TIME_SCALE_DAY;
4813 } else {
4814 astman_send_error(s, m, "Invalid TimeScale");
4815 goto aocmessage_cleanup;
4816 }
4817
4818 if (ast_strlen_zero(time) || (sscanf(time, "%30u", &_time) != 1)) {
4819 astman_send_error(s, m, "Invalid Time, Time is a required when RateType is Duration");
4820 goto aocmessage_cleanup;
4821 }
4822
4823 if (!ast_strlen_zero(granularity)) {
4824 if ((sscanf(time, "%30u", &_granularity) != 1)) {
4825 astman_send_error(s, m, "Invalid Granularity");
4826 goto aocmessage_cleanup;
4827 }
4828
4829 if (ast_strlen_zero(granularitytimescale)) {
4830 astman_send_error(s, m, "Invalid GranularityTimeScale, GranularityTimeScale is a required when Granularity is specified");
4831 } else if (!strcasecmp(granularitytimescale, "onehundredthsecond")) {
4832 _granularity_time_scale = AST_AOC_TIME_SCALE_HUNDREDTH_SECOND;
4833 } else if (!strcasecmp(granularitytimescale, "onetenthsecond")) {
4834 _granularity_time_scale = AST_AOC_TIME_SCALE_TENTH_SECOND;
4835 } else if (!strcasecmp(granularitytimescale, "second")) {
4836 _granularity_time_scale = AST_AOC_TIME_SCALE_SECOND;
4837 } else if (!strcasecmp(granularitytimescale, "tenseconds")) {
4838 _granularity_time_scale = AST_AOC_TIME_SCALE_TEN_SECOND;
4839 } else if (!strcasecmp(granularitytimescale, "minute")) {
4840 _granularity_time_scale = AST_AOC_TIME_SCALE_MINUTE;
4841 } else if (!strcasecmp(granularitytimescale, "hour")) {
4842 _granularity_time_scale = AST_AOC_TIME_SCALE_HOUR;
4843 } else if (!strcasecmp(granularitytimescale, "day")) {
4844 _granularity_time_scale = AST_AOC_TIME_SCALE_DAY;
4845 } else {
4846 astman_send_error(s, m, "Invalid GranularityTimeScale");
4847 goto aocmessage_cleanup;
4848 }
4849 }
4850
4851 if (ast_strlen_zero(chargingtype) || strcasecmp(chargingtype, "continuouscharging") == 0) {
4852 _step = 0;
4853 } else if (strcasecmp(chargingtype, "stepfunction") == 0 ) {
4854 _step = 1;
4855 } else {
4856 astman_send_error(s, m, "Invalid ChargingType");
4857 goto aocmessage_cleanup;
4858 }
4859 }
4860
4861 if (_ratetype == AST_AOC_RATE_TYPE_VOLUME) {
4862 if (ast_strlen_zero(volumeunit)) {
4863 astman_send_error(s, m, "VolumeUnit unspecified, VolumeUnit is required when RateType is Volume.");
4864 goto aocmessage_cleanup;
4865 } else if (!strcasecmp(timescale, "octet")) {
4866 _volumeunit = AST_AOC_VOLUME_UNIT_OCTET;
4867 } else if (!strcasecmp(timescale, "segment")) {
4868 _volumeunit = AST_AOC_VOLUME_UNIT_SEGMENT;
4869 } else if (!strcasecmp(timescale, "message")) {
4870 _volumeunit = AST_AOC_VOLUME_UNIT_MESSAGE;
4871 }else {
4872 astman_send_error(s, m, "Invalid VolumeUnit");
4873 goto aocmessage_cleanup;
4874 }
4875 }
4876
4877 if (_chargeditem == AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT
4878 || _ratetype == AST_AOC_RATE_TYPE_SPECIAL_CODE) {
4879 if (ast_strlen_zero(code) || (sscanf(code, "%30u", &_code) != 1)) {
4880 astman_send_error(s, m, "Invalid Code, Code is a required when ChargedItem is SpecialArrangement and when RateType is SpecialCode");
4881 goto aocmessage_cleanup;
4882 }
4883 }
4884
4885 if (_chargeditem == AST_AOC_CHARGED_ITEM_SPECIAL_ARRANGEMENT) {
4886 ast_aoc_s_add_special_arrangement(decoded, _code);
4887 } else if (_ratetype == AST_AOC_RATE_TYPE_DURATION) {
4888 ast_aoc_s_add_rate_duration(decoded, _chargeditem, _currencyamount, _mult,
4889 currencyname, _time, _scale, _granularity, _granularity_time_scale, _step);
4890 } else if (_ratetype == AST_AOC_RATE_TYPE_FLAT) {
4891 ast_aoc_s_add_rate_flat(decoded, _chargeditem, _currencyamount, _mult,
4892 currencyname);
4893 } else if (_ratetype == AST_AOC_RATE_TYPE_VOLUME) {
4894 ast_aoc_s_add_rate_volume(decoded, _chargeditem, _volumeunit, _currencyamount,
4895 _mult, currencyname);
4896 } else if (_ratetype == AST_AOC_RATE_TYPE_SPECIAL_CODE) {
4897 ast_aoc_s_add_rate_special_charge_code(decoded, _chargeditem, _code);
4898 } else if (_ratetype == AST_AOC_RATE_TYPE_FREE) {
4899 ast_aoc_s_add_rate_free(decoded, _chargeditem, 0);
4900 } else if (_ratetype == AST_AOC_RATE_TYPE_FREE_FROM_BEGINNING) {
4901 ast_aoc_s_add_rate_free(decoded, _chargeditem, 1);
4902 } else if (_ratetype == AST_AOC_RATE_TYPE_NA) {
4903 ast_aoc_s_add_rate_na(decoded, _chargeditem);
4904 }
4905
4906 return 0;
4907
4908 aocmessage_cleanup:
4909
4910 return -1;
4911 }
4912
4913 static struct ast_aoc_decoded *action_aoc_s_message(struct mansession *s,
4914 const struct message *m)
4915 {
4916 struct ast_aoc_decoded *decoded = NULL;
4917 int hdrlen;
4918 int x;
4919 static const char hdr[] = "ChargedItem:";
4920 struct message sm = { 0 };
4921 int rates = 0;
4922
4923 if (!(decoded = ast_aoc_create(AST_AOC_S, 0, 0))) {
4924 astman_send_error(s, m, "Message Creation Failed");
4925 goto aocmessage_cleanup;
4926 }
4927
4928 hdrlen = strlen(hdr);
4929 for (x = 0; x < m->hdrcount; x++) {
4930 if (strncasecmp(hdr, m->headers[x], hdrlen) == 0) {
4931 if (rates > ast_aoc_s_get_count(decoded)) {
4932 if (action_aoc_s_submessage(s, &sm, decoded) == -1) {
4933 goto aocmessage_cleanup;
4934 }
4935 }
4936 ++rates;
4937 }
4938
4939 sm.headers[sm.hdrcount] = m->headers[x];
4940 ++sm.hdrcount;
4941 }
4942 if (rates > ast_aoc_s_get_count(decoded)) {
4943 if (action_aoc_s_submessage(s, &sm, decoded) == -1) {
4944 goto aocmessage_cleanup;
4945 }
4946 }
4947
4948 return decoded;
4949
4950 aocmessage_cleanup:
4951
4952 ast_aoc_destroy_decoded(decoded);
4953 return NULL;
4954 }
4955
4956 static int action_aocmessage(struct mansession *s, const struct message *m)
4957 {
4958 const char *msgtype = astman_get_header(m, "MsgType");
4959 const char *channel = astman_get_header(m, "Channel");
4960 const char *pchannel = astman_get_header(m, "ChannelPrefix");
4961
4962 struct ast_channel *chan = NULL;
4963
4964 struct ast_aoc_decoded *decoded = NULL;
4965 struct ast_aoc_encoded *encoded = NULL;
4966 size_t encoded_size = 0;
4967
4968 if (ast_strlen_zero(channel) && ast_strlen_zero(pchannel)) {
4969 astman_send_error(s, m, "Channel and PartialChannel are not specified. Specify at least one of these.");
4970 goto aocmessage_cleanup;
4971 }
4972
4973 if (!(chan = ast_channel_get_by_name(channel)) && !ast_strlen_zero(pchannel)) {
4974 chan = ast_channel_get_by_name_prefix(pchannel, strlen(pchannel));
4975 }
4976
4977 if (!chan) {
4978 astman_send_error(s, m, "No such channel");
4979 goto aocmessage_cleanup;
4980 }
4981
4982 if (strcasecmp(msgtype, "d") == 0 || strcasecmp(msgtype, "e") == 0) {
4983 decoded = action_aoc_de_message(s, m);
4984 }
4985 else if (strcasecmp(msgtype, "s") == 0) {
4986 decoded = action_aoc_s_message(s, m);
4987 }
4988 else {
4989 astman_send_error(s, m, "Invalid MsgType");
4990 goto aocmessage_cleanup;
4991 }
4992
4993 if (!decoded) {
4994 goto aocmessage_cleanup;
4995 }
4996
4997 if ((encoded = ast_aoc_encode(decoded, &encoded_size, chan))
4998 && !ast_indicate_data(chan, AST_CONTROL_AOC, encoded, encoded_size)) {
4999 astman_send_ack(s, m, "AOC Message successfully queued on channel");
5000 } else {
5001 astman_send_error(s, m, "Error encoding AOC message, could not queue onto channel");
5002 }
5003
5004 aocmessage_cleanup:
5005
5006 ast_aoc_destroy_decoded(decoded);
5007 ast_aoc_destroy_encoded(encoded);
5008
5009 if (chan) {
5010 chan = ast_channel_unref(chan);
5011 }
5012 return 0;
5013 }
5014
5015 struct originate_permissions_entry {
5016 const char *search;
5017 int permission;
5018 int (*searchfn)(const char *app, const char *data, const char *search);
5019 };
5020
5021 /*!
5022 * \internal
5023 * \brief Check if the application is allowed for Originate
5024 *
5025 * \param app The "app" parameter
5026 * \param data The "appdata" parameter (ignored)
5027 * \param search The search string
5028 * \retval 1 Match
5029 * \retval 0 No match
5030 */
5031 static int app_match(const char *app, const char *data, const char *search)
5032 {
5033 /*
5034 * We use strcasestr so we don't have to trim any blanks
5035 * from the front or back of the string.
5036 */
5037 return !!(strcasestr(app, search));
5038 }
5039
5040 /*!
5041 * \internal
5042 * \brief Check if the appdata is allowed for Originate
5043 *
5044 * \param app The "app" parameter (ignored)
5045 * \param data The "appdata" parameter
5046 * \param search The search string
5047 * \retval 1 Match
5048 * \retval 0 No match
5049 */
5050 static int appdata_match(const char *app, const char *data, const char *search)
5051 {
5052 if (ast_strlen_zero(data)) {
5053 return 0;
5054 }
5055 return !!(strstr(data, search));
5056 }
5057
5058 /*!
5059 * \internal
5060 * \brief Check if the Queue application is allowed for Originate
5061 *
5062 * It's only allowed if there's no AGI parameter set
5063 *
5064 * \param app The "app" parameter
5065 * \param data The "appdata" parameter
5066 * \param search The search string
5067 * \retval 1 Match
5068 * \retval 0 No match
5069 */
5070 static int queue_match(const char *app, const char *data, const char *search)
5071 {
5072 char *parse;
5073 AST_DECLARE_APP_ARGS(args,
5074 AST_APP_ARG(queuename);
5075 AST_APP_ARG(options);
5076 AST_APP_ARG(url);
5077 AST_APP_ARG(announceoverride);
5078 AST_APP_ARG(queuetimeoutstr);
5079 AST_APP_ARG(agi);
5080 AST_APP_ARG(gosub);
5081 AST_APP_ARG(rule);
5082 AST_APP_ARG(position);
5083 );
5084
5085 if (!strcasestr(app, "queue") || ast_strlen_zero(data)) {
5086 return 0;
5087 }
5088
5089 parse = ast_strdupa(data);
5090 AST_STANDARD_APP_ARGS(args, parse);
5091
5092 /*
5093 * The Queue application is fine unless the AGI parameter is set.
5094 * If it is, we need to check the user's permissions.
5095 */
5096 return !ast_strlen_zero(args.agi);
5097 }
5098
5099 /*
5100 * The Originate application and application data are passed
5101 * to each searchfn in the list. If a searchfn returns true
5102 * and the user's permissions don't include the permissions specified
5103 * in the list entry, the Originate action will be denied.
5104 *
5105 * If no searchfn returns true, the Originate action is allowed.
5106 */
5107 static struct originate_permissions_entry originate_app_permissions[] = {
5108 /*
5109 * The app_match function checks if the search string is
5110 * anywhere in the app parameter. The check is case-insensitive.
5111 */
5112 { "agi", EVENT_FLAG_SYSTEM, app_match },
5113 { "dbdeltree", EVENT_FLAG_SYSTEM, app_match },
5114 { "exec", EVENT_FLAG_SYSTEM, app_match },
5115 { "externalivr", EVENT_FLAG_SYSTEM, app_match },
5116 { "mixmonitor", EVENT_FLAG_SYSTEM, app_match },
5117 { "originate", EVENT_FLAG_SYSTEM, app_match },
5118 { "reload", EVENT_FLAG_SYSTEM, app_match },
5119 { "system", EVENT_FLAG_SYSTEM, app_match },
5120 /*
5121 * Since the queue_match function specifically checks
5122 * for the presence of the AGI parameter, we'll allow
5123 * the call if the user has either the AGI or SYSTEM
5124 * permission.
5125 */
5126 { "queue", EVENT_FLAG_AGI | EVENT_FLAG_SYSTEM, queue_match },
5127 /*
5128 * The appdata_match function checks if the search string is
5129 * anywhere in the appdata parameter. Unlike app_match,
5130 * the check is case-sensitive. These are generally
5131 * dialplan functions.
5132 */
5133 { "CURL", EVENT_FLAG_SYSTEM, appdata_match },
5134 { "DB", EVENT_FLAG_SYSTEM, appdata_match },
5135 { "EVAL", EVENT_FLAG_SYSTEM, appdata_match },
5136 { "FILE", EVENT_FLAG_SYSTEM, appdata_match },
5137 { "ODBC", EVENT_FLAG_SYSTEM, appdata_match },
5138 { "REALTIME", EVENT_FLAG_SYSTEM, appdata_match },
5139 { "SHELL", EVENT_FLAG_SYSTEM, appdata_match },
5140 { NULL, 0 },
5141 };
5142
5143 static int is_originate_app_permitted(const char *app, const char *data,
5144 int permission)
5145 {
5146 int i;
5147
5148 for (i = 0; originate_app_permissions[i].search; i++) {
5149 if (originate_app_permissions[i].searchfn(app, data, originate_app_permissions[i].search)) {
5150 return !!(permission & originate_app_permissions[i].permission);
5151 }
5152 }
5153
5154 return 1;
5155 }
5156
5157 #ifdef TEST_FRAMEWORK
5158 #define ALL_PERMISSIONS (INT_MAX)
5159 #define NO_PERMISSIONS (0)
5160 AST_TEST_DEFINE(originate_permissions_test)
5161 {
5162 enum ast_test_result_state res = AST_TEST_PASS;
5163
5164 switch (cmd) {
5165 case TEST_INIT:
5166 info->name = "originate_permissions_test";
5167 info->category = "/main/manager/";
5168 info->summary = "Test permissions for originate action";
5169 info->description =
5170 "Make sure that dialplan apps/functions that need special "
5171 "permissions are prohibited if the user doesn't have the permission.";
5172 return AST_TEST_NOT_RUN;
5173 case TEST_EXECUTE:
5174 break;
5175 }
5176
5177 /*
5178 * Check application matching. We don't need to check every one.
5179 * The code is the same.
5180 */
5181
5182 ast_test_validate(test, is_originate_app_permitted("exec",
5183 NULL, EVENT_FLAG_SYSTEM), "exec permission check failed");
5184 ast_test_validate(test, is_originate_app_permitted("exec",
5185 NULL, EVENT_FLAG_SYSTEM | EVENT_FLAG_AGI), "exec check permission failed");
5186 ast_test_validate(test, is_originate_app_permitted("exec",
5187 NULL, ALL_PERMISSIONS), "exec check permission failed");
5188 ast_test_validate(test, !is_originate_app_permitted("exec",
5189 NULL, EVENT_FLAG_AGI), "exec permission check failed");
5190 ast_test_validate(test, !is_originate_app_permitted("exec",
5191 NULL, EVENT_FLAG_VERBOSE), "exec permission check failed");
5192 ast_test_validate(test, !is_originate_app_permitted("exec",
5193 NULL, NO_PERMISSIONS), "exec permission check failed");
5194
5195 /*
5196 * If queue is used with the AGI parameter but without the SYSTEM or AGI
5197 * permission, it should be denied. Queue param order:
5198 * queuename,options,url,announceoverride,queuetimeoutstr,AGI,gosub,rule,position
5199 * The values of the options aren't checked. They just have to be present.
5200 */
5201
5202 /* AGI not specified should always be allowed */
5203 ast_test_validate(test, is_originate_app_permitted("queue",
5204 NULL, NO_PERMISSIONS), "Queue permission check failed");
5205 ast_test_validate(test, is_originate_app_permitted("queue",
5206 "somequeue,CcdHh,someURL,tt-monkeys,100,,gosub,rule,666",
5207 EVENT_FLAG_ORIGINATE | EVENT_FLAG_HOOKRESPONSE ), "Queue permission check failed");
5208
5209 /* AGI specified with SYSTEM or AGI permission should be allowed */
5210 ast_test_validate(test, is_originate_app_permitted("queue",
5211 "somequeue,CcdHh,someURL,tt-monkeys,100,SomeAGIScript,gosub,rule,666",
5212 EVENT_FLAG_SYSTEM | EVENT_FLAG_HOOKRESPONSE ), "Queue permission check failed");
5213 ast_test_validate(test, is_originate_app_permitted("queue",
5214 "somequeue,CcdHh,someURL,tt-monkeys,100,SomeAGIScript,gosub,rule,666",
5215 EVENT_FLAG_AGI | EVENT_FLAG_HOOKRESPONSE ), "Queue permission check failed");
5216 ast_test_validate(test, is_originate_app_permitted("queue",
5217 "somequeue,CcdHh,someURL,tt-monkeys,100,SomeAGIScript,gosub,rule,666",
5218 ALL_PERMISSIONS), "Queue permission check failed");
5219
5220 /* AGI specified without SYSTEM or AGI permission should be denied */
5221 ast_test_validate(test, !is_originate_app_permitted("queue",
5222 "somequeue,CcdHh,someURL,tt-monkeys,100,SomeAGIScript,gosub,rule,666",
5223 NO_PERMISSIONS), "Queue permission check failed");
5224 ast_test_validate(test, !is_originate_app_permitted("queue",
5225 "somequeue,CcdHh,someURL,tt-monkeys,100,SomeAGIScript,gosub,rule,666",
5226 EVENT_FLAG_ORIGINATE | EVENT_FLAG_HOOKRESPONSE ), "Queue permission check failed");
5227
5228 /*
5229 * Check appdata. The function name can appear anywhere in appdata.
5230 */
5231 ast_test_validate(test, is_originate_app_permitted("someapp",
5232 "aaaDBbbb", EVENT_FLAG_SYSTEM), "exec permission check failed");
5233 ast_test_validate(test, is_originate_app_permitted("someapp",
5234 "aaa DB bbb", ALL_PERMISSIONS), "exec permission check failed");
5235 ast_test_validate(test, !is_originate_app_permitted("someapp",
5236 "aaaDBbbb", NO_PERMISSIONS), "exec permission check failed");
5237 ast_test_validate(test, !is_originate_app_permitted("someapp",
5238 "aaa DB bbb", NO_PERMISSIONS), "exec permission check failed");
5239 /* The check is case-sensitive so although DB is a match, db isn't. */
5240 ast_test_validate(test, is_originate_app_permitted("someapp",
5241 "aaa db bbb", NO_PERMISSIONS), "exec permission check failed");
5242
5243 return res;
5244 }
5245 #undef ALL_PERMISSIONS
5246 #undef NO_PERMISSIONS
5247 #endif
5248
5249 static int action_originate(struct mansession *s, const struct message *m)
5250 {
5251 const char *name = astman_get_header(m, "Channel");
5252 const char *exten = astman_get_header(m, "Exten");
5253 const char *context = astman_get_header(m, "Context");
5254 const char *priority = astman_get_header(m, "Priority");
5255 const char *timeout = astman_get_header(m, "Timeout");
5256 const char *callerid = astman_get_header(m, "CallerID");
5257 const char *account = astman_get_header(m, "Account");
5258 const char *app = astman_get_header(m, "Application");
5259 const char *appdata = astman_get_header(m, "Data");
5260 const char *async = astman_get_header(m, "Async");
5261 const char *id = astman_get_header(m, "ActionID");
5262 const char *codecs = astman_get_header(m, "Codecs");
5263 const char *early_media = astman_get_header(m, "Earlymedia");
5264 struct ast_assigned_ids assignedids = {
5265 .uniqueid = astman_get_header(m, "ChannelId"),
5266 .uniqueid2 = astman_get_header(m, "OtherChannelId"),
5267 };
5268 const char *gosub = astman_get_header(m, "PreDialGoSub");
5269
5270 struct ast_variable *vars = NULL;
5271 char *tech, *data;
5272 char *l = NULL, *n = NULL;
5273 int pi = 0;
5274 int res;
5275 int to = 30000;
5276 int reason = 0;
5277 char tmp[256];
5278 char tmp2[256];
5279 struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
5280 pthread_t th;
5281 int bridge_early = 0;
5282
5283 if (!cap) {
5284 astman_send_error(s, m, "Internal Error. Memory allocation failure.");
5285 return 0;
5286 }
5287 ast_format_cap_append(cap, ast_format_slin, 0);
5288
5289 if ((assignedids.uniqueid && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid))
5290 || (assignedids.uniqueid2 && AST_MAX_PUBLIC_UNIQUEID < strlen(assignedids.uniqueid2))) {
5291 astman_send_error_va(s, m, "Uniqueid length exceeds maximum of %d\n",
5292 AST_MAX_PUBLIC_UNIQUEID);
5293 res = 0;
5294 goto fast_orig_cleanup;
5295 }
5296
5297 if (ast_strlen_zero(name)) {
5298 astman_send_error(s, m, "Channel not specified");
5299 res = 0;
5300 goto fast_orig_cleanup;
5301 }
5302 if (!ast_strlen_zero(priority) && (sscanf(priority, "%30d", &pi) != 1)) {
5303 if ((pi = ast_findlabel_extension(NULL, context, exten, priority, NULL)) < 1) {
5304 astman_send_error(s, m, "Invalid priority");
5305 res = 0;
5306 goto fast_orig_cleanup;
5307 }
5308 }
5309 if (!ast_strlen_zero(timeout) && (sscanf(timeout, "%30d", &to) != 1)) {
5310 astman_send_error(s, m, "Invalid timeout");
5311 res = 0;
5312 goto fast_orig_cleanup;
5313 }
5314 ast_copy_string(tmp, name, sizeof(tmp));
5315 tech = tmp;
5316 data = strchr(tmp, '/');
5317 if (!data) {
5318 astman_send_error(s, m, "Invalid channel");
5319 res = 0;
5320 goto fast_orig_cleanup;
5321 }
5322 *data++ = '\0';
5323 ast_copy_string(tmp2, callerid, sizeof(tmp2));
5324 ast_callerid_parse(tmp2, &n, &l);
5325 if (n) {
5326 if (ast_strlen_zero(n)) {
5327 n = NULL;
5328 }
5329 }
5330 if (l) {
5331 ast_shrink_phone_number(l);
5332 if (ast_strlen_zero(l)) {
5333 l = NULL;
5334 }
5335 }
5336 if (!ast_strlen_zero(codecs)) {
5337 ast_format_cap_remove_by_type(cap, AST_MEDIA_TYPE_UNKNOWN);
5338 ast_format_cap_update_by_allow_disallow(cap, codecs, 1);
5339 }
5340
5341 if (!ast_strlen_zero(app) && s->session) {
5342 if (!is_originate_app_permitted(app, appdata, s->session->writeperm)) {
5343 astman_send_error(s, m, "Originate Access Forbidden: app or data blacklisted");
5344 res = 0;
5345 goto fast_orig_cleanup;
5346 }
5347 }
5348
5349 /* Check early if the extension exists. If not, we need to bail out here. */
5350 if (exten && context && pi) {
5351 if (! ast_exists_extension(NULL, context, exten, pi, l)) {
5352 /* The extension does not exist. */
5353 astman_send_error(s, m, "Extension does not exist.");
5354 res = 0;
5355 goto fast_orig_cleanup;
5356 }
5357 }
5358
5359 /* Allocate requested channel variables */
5360 vars = astman_get_variables(m);
5361 if (s->session && s->session->chanvars) {
5362 struct ast_variable *v, *old;
5363 old = vars;
5364 vars = NULL;
5365
5366 /* The variables in the AMI originate action are appended at the end of the list, to override any user variables that apply */
5367
5368 vars = ast_variables_dup(s->session->chanvars);
5369 if (old) {
5370 for (v = vars; v->next; v = v->next );
5371 v->next = old; /* Append originate variables at end of list */
5372 }
5373 }
5374
5375 /* For originate async - we can bridge in early media stage */
5376 bridge_early = ast_true(early_media);
5377
5378 if (ast_true(async)) {
5379 struct fast_originate_helper *fast;
5380
5381 fast = ast_calloc(1, sizeof(*fast));
5382 if (!fast || ast_string_field_init(fast, 252)) {
5383 ast_free(fast);
5384 ast_variables_destroy(vars);
5385 res = -1;
5386 } else {
5387 if (!ast_strlen_zero(id)) {
5388 ast_string_field_build(fast, idtext, "ActionID: %s\r\n", id);
5389 }
5390 ast_string_field_set(fast, tech, tech);
5391 ast_string_field_set(fast, data, data);
5392 ast_string_field_set(fast, app, app);
5393 ast_string_field_set(fast, appdata, appdata);
5394 ast_string_field_set(fast, cid_num, l);
5395 ast_string_field_set(fast, cid_name, n);
5396 ast_string_field_set(fast, context, context);
5397 ast_string_field_set(fast, exten, exten);
5398 ast_string_field_set(fast, account, account);
5399 ast_string_field_set(fast, channelid, assignedids.uniqueid);
5400 ast_string_field_set(fast, otherchannelid, assignedids.uniqueid2);
5401 fast->vars = vars;
5402 fast->cap = cap;
5403 cap = NULL; /* transferred originate helper the capabilities structure. It is now responsible for freeing it. */
5404 fast->timeout = to;
5405 fast->early_media = bridge_early;
5406 fast->priority = pi;
5407 if (ast_pthread_create_detached(&th, NULL, fast_originate, fast)) {
5408 destroy_fast_originate_helper(fast);
5409 res = -1;
5410 } else {
5411 res = 0;
5412 }
5413 }
5414 } else if (!ast_strlen_zero(app)) {
5415 res = ast_pbx_outgoing_app(tech, cap, data, to, app, appdata, &reason,
5416 AST_OUTGOING_WAIT, l, n, vars, account, NULL,
5417 assignedids.uniqueid ? &assignedids : NULL);
5418 ast_variables_destroy(vars);
5419 } else {
5420 if (exten && context && pi) {
5421 res = ast_pbx_outgoing_exten_predial(tech, cap, data, to,
5422 context, exten, pi, &reason, AST_OUTGOING_WAIT,
5423 l, n, vars, account, NULL, bridge_early,
5424 assignedids.uniqueid ? &assignedids : NULL , gosub);
5425 ast_variables_destroy(vars);
5426 } else {
5427 astman_send_error(s, m, "Originate with 'Exten' requires 'Context' and 'Priority'");
5428 ast_variables_destroy(vars);
5429 res = 0;
5430 goto fast_orig_cleanup;
5431 }
5432 }
5433 if (!res) {
5434 astman_send_ack(s, m, "Originate successfully queued");
5435 } else {
5436 astman_send_error(s, m, "Originate failed");
5437 }
5438
5439 fast_orig_cleanup:
5440 ao2_cleanup(cap);
5441 return 0;
5442 }
5443
5444 static int action_mailboxstatus(struct mansession *s, const struct message *m)
5445 {
5446 const char *mailbox = astman_get_header(m, "Mailbox");
5447 int ret;
5448
5449 if (ast_strlen_zero(mailbox)) {
5450 astman_send_error(s, m, "Mailbox not specified");
5451 return 0;
5452 }
5453 ret = ast_app_has_voicemail(mailbox, NULL);
5454 astman_start_ack(s, m);
5455 astman_append(s, "Message: Mailbox Status\r\n"
5456 "Mailbox: %s\r\n"
5457 "Waiting: %d\r\n\r\n", mailbox, ret);
5458 return 0;
5459 }
5460
5461 static int action_mailboxcount(struct mansession *s, const struct message *m)
5462 {
5463 const char *mailbox = astman_get_header(m, "Mailbox");
5464 int newmsgs = 0, oldmsgs = 0, urgentmsgs = 0;;
5465
5466 if (ast_strlen_zero(mailbox)) {
5467 astman_send_error(s, m, "Mailbox not specified");
5468 return 0;
5469 }
5470 ast_app_inboxcount2(mailbox, &urgentmsgs, &newmsgs, &oldmsgs);
5471 astman_start_ack(s, m);
5472 astman_append(s, "Message: Mailbox Message Count\r\n"
5473 "Mailbox: %s\r\n"
5474 "UrgMessages: %d\r\n"
5475 "NewMessages: %d\r\n"
5476 "OldMessages: %d\r\n"
5477 "\r\n",
5478 mailbox, urgentmsgs, newmsgs, oldmsgs);
5479 return 0;
5480 }
5481
5482 static int action_extensionstate(struct mansession *s, const struct message *m)
5483 {
5484 const char *exten = astman_get_header(m, "Exten");
5485 const char *context = astman_get_header(m, "Context");
5486 char hint[256];
5487 int status;
5488
5489 if (ast_strlen_zero(exten)) {
5490 astman_send_error(s, m, "Extension not specified");
5491 return 0;
5492 }
5493 if (ast_strlen_zero(context)) {
5494 context = "default";
5495 }
5496 status = ast_extension_state(NULL, context, exten);
5497 hint[0] = '\0';
5498 ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
5499 astman_start_ack(s, m);
5500 astman_append(s, "Message: Extension Status\r\n"
5501 "Exten: %s\r\n"
5502 "Context: %s\r\n"
5503 "Hint: %s\r\n"
5504 "Status: %d\r\n"
5505 "StatusText: %s\r\n"
5506 "\r\n",
5507 exten, context, hint, status,
5508 ast_extension_state2str(status));
5509 return 0;
5510 }
5511
5512 static int action_presencestate(struct mansession *s, const struct message *m)
5513 {
5514 const char *provider = astman_get_header(m, "Provider");
5515 enum ast_presence_state state;
5516 char *subtype;
5517 char *message;
5518
5519 if (ast_strlen_zero(provider)) {
5520 astman_send_error(s, m, "No provider specified");
5521 return 0;
5522 }
5523
5524 state = ast_presence_state(provider, &subtype, &message);
5525 if (state == AST_PRESENCE_INVALID) {
5526 astman_send_error_va(s, m, "Invalid provider %s or provider in invalid state", provider);
5527 return 0;
5528 }
5529
5530 astman_start_ack(s, m);
5531 astman_append(s, "Message: Presence State\r\n"
5532 "State: %s\r\n", ast_presence_state2str(state));
5533
5534 if (!ast_strlen_zero(subtype)) {
5535 astman_append(s, "Subtype: %s\r\n", subtype);
5536 }
5537
5538 if (!ast_strlen_zero(message)) {
5539 /* XXX The Message header here is deprecated as it
5540 * duplicates the action response header 'Message'.
5541 * Remove it in the next major revision of AMI.
5542 */
5543 astman_append(s, "Message: %s\r\n"
5544 "PresenceMessage: %s\r\n",
5545 message, message);
5546 }
5547 astman_append(s, "\r\n");
5548
5549 ast_free(subtype);
5550 ast_free(message);
5551
5552 return 0;
5553 }
5554
5555 static int action_timeout(struct mansession *s, const struct message *m)
5556 {
5557 struct ast_channel *c;
5558 const char *name = astman_get_header(m, "Channel");
5559 double timeout = atof(astman_get_header(m, "Timeout"));
5560 struct timeval when = { timeout, 0 };
5561
5562 if (ast_strlen_zero(name)) {
5563 astman_send_error(s, m, "No channel specified");
5564 return 0;
5565 }
5566
5567 if (!timeout || timeout < 0) {
5568 astman_send_error(s, m, "No timeout specified");
5569 return 0;
5570 }
5571
5572 if (!(c = ast_channel_get_by_name(name))) {
5573 astman_send_error(s, m, "No such channel");
5574 return 0;
5575 }
5576
5577 when.tv_usec = (timeout - when.tv_sec) * 1000000.0;
5578
5579 ast_channel_lock(c);
5580 ast_channel_setwhentohangup_tv(c, when);
5581 ast_channel_unlock(c);
5582 c = ast_channel_unref(c);
5583
5584 astman_send_ack(s, m, "Timeout Set");
5585
5586 return 0;
5587 }
5588
5589 /*!
5590 * \brief Test eventdata against a filter entry
5591 *
5592 * \param entry The event_filter entry to match with
5593 * \param eventdata The data to match against
5594 * \retval 0 if no match
5595 * \retval 1 if match
5596 */
5597 static int match_eventdata(struct event_filter_entry *entry, const char *eventdata)
5598 {
5599 switch(entry->match_type) {
5600 case FILTER_MATCH_REGEX:
5601 return regexec(entry->regex_filter, eventdata, 0, NULL, 0) == 0;
5602 case FILTER_MATCH_STARTS_WITH:
5603 return ast_begins_with(eventdata, entry->string_filter);
5604 case FILTER_MATCH_ENDS_WITH:
5605 return ast_ends_with(eventdata, entry->string_filter);
5606 case FILTER_MATCH_CONTAINS:
5607 return strstr(eventdata, entry->string_filter) != NULL;
5608 case FILTER_MATCH_EXACT:
5609 return strcmp(eventdata, entry->string_filter) == 0;
5610 case FILTER_MATCH_NONE:
5611 return 1;
5612 }
5613
5614 return 0;
5615 }
5616
5617 static int filter_cmp_fn(void *obj, void *arg, void *data, int flags)
5618 {
5619 struct eventqent *eqe = arg;
5620 struct event_filter_entry *filter_entry = obj;
5621 char *line_buffer_start = NULL;
5622 char *line_buffer = NULL;
5623 char *line = NULL;
5624 int match = 0;
5625 int *result = data;
5626
5627 if (filter_entry->event_name_hash) {
5628 if (eqe->event_name_hash != filter_entry->event_name_hash) {
5629 goto done;
5630 }
5631 }
5632
5633 /* We're looking at the entire event data */
5634 if (!filter_entry->header_name) {
5635 match = match_eventdata(filter_entry, eqe->eventdata);
5636 goto done;
5637 }
5638
5639 /* We're looking at a specific header */
5640 line_buffer_start = ast_strdup(eqe->eventdata);
5641 line_buffer = line_buffer_start;
5642 if (!line_buffer_start) {
5643 goto done;
5644 }
5645
5646 while ((line = ast_read_line_from_buffer(&line_buffer))) {
5647 if (ast_begins_with(line, filter_entry->header_name)) {
5648 line += strlen(filter_entry->header_name);
5649 line = ast_skip_blanks(line);
5650 if (ast_strlen_zero(line)) {
5651 continue;
5652 }
5653 match = match_eventdata(filter_entry, line);
5654 if (match) {
5655 ast_free(line_buffer_start);
5656 line_buffer_start = NULL;
5657 break;
5658 }
5659 }
5660 }
5661
5662 ast_free(line_buffer_start);
5663
5664 done:
5665
5666 *result = match;
5667 return match ? CMP_MATCH | CMP_STOP : 0;
5668 }
5669
5670 static int should_send_event(struct ao2_container *includefilters,
5671 struct ao2_container *excludefilters, struct eventqent *eqe)
5672 {
5673 int result = 0;
5674
5675 if (manager_debug) {
5676 ast_verbose("<-- Examining AMI event (%u): -->\n%s\n", eqe->event_name_hash, eqe->eventdata);
5677 } else {
5678 ast_debug(4, "Examining AMI event (%u):\n%s\n", eqe->event_name_hash, eqe->eventdata);
5679 }
5680 if (!ao2_container_count(includefilters) && !ao2_container_count(excludefilters)) {
5681 return 1; /* no filtering means match all */
5682 } else if (ao2_container_count(includefilters) && !ao2_container_count(excludefilters)) {
5683 /* include filters only: implied exclude all filter processed first, then include filters */
5684 ao2_t_callback_data(includefilters, OBJ_NODATA, filter_cmp_fn, eqe, &result, "find filter in includefilters container");
5685 return result;
5686 } else if (!ao2_container_count(includefilters) && ao2_container_count(excludefilters)) {
5687 /* exclude filters only: implied include all filter processed first, then exclude filters */
5688 ao2_t_callback_data(excludefilters, OBJ_NODATA, filter_cmp_fn, eqe, &result, "find filter in excludefilters container");
5689 return !result;
5690 } else {
5691 /* include and exclude filters: implied exclude all filter processed first, then include filters, and lastly exclude filters */
5692 ao2_t_callback_data(includefilters, OBJ_NODATA, filter_cmp_fn, eqe, &result, "find filter in session filter container");
5693 if (result) {
5694 result = 0;
5695 ao2_t_callback_data(excludefilters, OBJ_NODATA, filter_cmp_fn, eqe, &result, "find filter in session filter container");
5696 return !result;
5697 }
5698 }
5699
5700 return result;
5701 }
5702
5703 /*!
5704 * \brief Manager command to add an event filter to a manager session
5705 * \see For more details look at manager_add_filter
5706 */
5707 static int action_filter(struct mansession *s, const struct message *m)
5708 {
5709 const char *match_criteria = astman_get_header(m, "MatchCriteria");
5710 const char *filter = astman_get_header(m, "Filter");
5711 const char *operation = astman_get_header(m, "Operation");
5712 int res;
5713
5714 if (!strcasecmp(operation, "Add")) {
5715 char *criteria;
5716 int have_match = !ast_strlen_zero(match_criteria);
5717
5718 /* Create an eventfilter expression.
5719 * eventfilter[(match_criteria)]
5720 */
5721 res = ast_asprintf(&criteria, "eventfilter%s%s%s",
5722 S_COR(have_match, "(", ""), S_OR(match_criteria, ""),
5723 S_COR(have_match, ")", ""));
5724 if (res <= 0) {
5725 astman_send_error(s, m, "Internal Error. Failed to allocate storage for filter type");
5726 return 0;
5727 }
5728
5729 res = manager_add_filter(criteria, filter, s->session->includefilters, s->session->excludefilters);
5730 ast_free(criteria);
5731 if (res != FILTER_SUCCESS) {
5732 if (res == FILTER_ALLOC_FAILED) {
5733 astman_send_error(s, m, "Internal Error. Failed to allocate regex for filter");
5734 return 0;
5735 } else if (res == FILTER_COMPILE_FAIL) {
5736 astman_send_error(s, m,
5737 "Filter did not compile. Check the syntax of the filter given.");
5738 return 0;
5739 } else if (res == FILTER_FORMAT_ERROR) {
5740 astman_send_error(s, m,
5741 "Filter was formatted incorrectly. Check the syntax of the filter given.");
5742 return 0;
5743 } else {
5744 astman_send_error(s, m, "Internal Error. Failed adding filter.");
5745 return 0;
5746 }
5747 }
5748
5749 astman_send_ack(s, m, "Success");
5750 return 0;
5751 }
5752
5753 astman_send_error(s, m, "Unknown operation");
5754 return 0;
5755 }
5756
5757 /*!
5758 * \brief Add an event filter to a manager session
5759 *
5760 * \param criteria See examples in manager.conf.sample
5761 * \param filter_pattern Filter pattern
5762 * \param includefilters, excludefilters
5763 *
5764 * \return FILTER_ALLOC_FAILED Memory allocation failure
5765 * \return FILTER_COMPILE_FAIL If the filter did not compile
5766 * \return FILTER_FORMAT_ERROR If the criteria weren't formatted correctly
5767 * \return FILTER_SUCCESS Success
5768 *
5769 *
5770 * Examples:
5771 * See examples in manager.conf.sample
5772 *
5773 */
5774 static enum add_filter_result manager_add_filter(
5775 const char *criteria, const char *filter_pattern,
5776 struct ao2_container *includefilters, struct ao2_container *excludefilters)
5777 {
5778 RAII_VAR(struct event_filter_entry *, filter_entry,
5779 ao2_t_alloc(sizeof(*filter_entry), event_filter_destructor, "event_filter allocation"),
5780 ao2_cleanup);
5781 const char *options_start = NULL;
5782 SCOPE_ENTER(3, "manager_add_filter(%s, %s, %p, %p)", criteria, filter_pattern, includefilters, excludefilters);
5783
5784 if (!filter_entry) {
5785 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_ALLOC_FAILED, LOG_WARNING, "Unable to allocate filter_entry");
5786 }
5787
5788 /*
5789 * At a minimum, criteria must be "eventfilter" but may contain additional
5790 * constraints.
5791 */
5792 if (ast_strlen_zero(criteria)) {
5793 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "Missing criteria");
5794 }
5795
5796 /*
5797 * filter_pattern could be empty but it should never be NULL.
5798 */
5799 if (!filter_pattern) {
5800 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "Filter pattern was NULL");
5801 }
5802
5803 /*
5804 * For a legacy filter, if the first character of filter_pattern is
5805 * '!' then it's an exclude filter. It's also accepted as an alternative
5806 * to specifying "action(exclude)" for an advanced filter. If
5807 * "action" is specified however, it will take precedence.
5808 */
5809 if (filter_pattern[0] == '!') {
5810 filter_entry->is_excludefilter = 1;
5811 filter_pattern++;
5812 }
5813
5814 /*
5815 * This is the default
5816 */
5817 filter_entry->match_type = FILTER_MATCH_REGEX;
5818
5819 /*
5820 * If the criteria has a '(' in it, then it's an advanced filter.
5821 */
5822 options_start = strstr(criteria, "(");
5823
5824 /*
5825 * If it's a legacy filter, there MUST be a filter pattern.
5826 */
5827 if (!options_start && ast_strlen_zero(filter_pattern)) {
5828 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING,
5829 "'%s = %s': Legacy filter with no filter pattern specified\n",
5830 criteria, filter_pattern);
5831 }
5832
5833 if (options_start) {
5834 /*
5835 * This is an advanced filter
5836 */
5837 char *temp = ast_strdupa(options_start + 1); /* skip over the leading '(' */
5838 char *saveptr = NULL;
5839 char *option = NULL;
5840 enum found_options {
5841 action_found = (1 << 0),
5842 name_found = (1 << 1),
5843 header_found = (1 << 2),
5844 method_found = (1 << 3),
5845 };
5846 enum found_options options_found = 0;
5847
5848 filter_entry->match_type = FILTER_MATCH_NONE;
5849
5850 ast_strip(temp);
5851 if (ast_strlen_zero(temp) || !ast_ends_with(temp, ")")) {
5852 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING,
5853 "'%s = %s': Filter options not formatted correctly\n",
5854 criteria, filter_pattern);
5855 }
5856
5857 /*
5858 * These can actually be in any order...
5859 * action(include|exclude),name(<event_name>),header(<header_name>),method(<match_method>)
5860 * At least one of action, name, or header is required.
5861 */
5862 while ((option = strtok_r(temp, " ,)", &saveptr))) {
5863 if (!strncmp(option, "action", 6)) {
5864 char *method = strstr(option, "(");
5865 if (ast_strlen_zero(method)) {
5866 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': 'action' parameter not formatted correctly\n",
5867 criteria, filter_pattern);
5868 }
5869 method++;
5870 ast_strip(method);
5871 if (!strcmp(method, "include")) {
5872 filter_entry->is_excludefilter = 0;
5873 } else if (!strcmp(method, "exclude")) {
5874 filter_entry->is_excludefilter = 1;
5875 } else {
5876 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': 'action' option '%s' is unknown\n",
5877 criteria, filter_pattern, method);
5878 }
5879 options_found |= action_found;
5880 } else if (!strncmp(option, "name", 4)) {
5881 char *event_name = strstr(option, "(");
5882 event_name++;
5883 ast_strip(event_name);
5884 if (ast_strlen_zero(event_name)) {
5885 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': 'name' parameter not formatted correctly\n",
5886 criteria, filter_pattern);
5887 }
5888 filter_entry->event_name = ast_strdup(event_name);
5889 filter_entry->event_name_hash = ast_str_hash(event_name);
5890 options_found |= name_found;
5891 } else if (!strncmp(option, "header", 6)) {
5892 char *header_name = strstr(option, "(");
5893 header_name++;
5894 ast_strip(header_name);
5895 if (ast_strlen_zero(header_name)) {
5896 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': 'header' parameter not formatted correctly\n",
5897 criteria, filter_pattern);
5898 }
5899 if (!ast_ends_with(header_name, ":")) {
5900 filter_entry->header_name = ast_malloc(strlen(header_name) + 2);
5901 if (!filter_entry->header_name) {
5902 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_ALLOC_FAILED, LOG_ERROR, "Unable to allocate memory for header_name");
5903 }
5904 sprintf(filter_entry->header_name, "%s:", header_name); /* Safe */
5905 } else {
5906 filter_entry->header_name = ast_strdup(header_name);
5907 }
5908 options_found |= header_found;
5909 } else if (!strncmp(option, "method", 6)) {
5910 char *method = strstr(option, "(");
5911 method++;
5912 ast_strip(method);
5913 if (ast_strlen_zero(method)) {
5914 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': 'method' parameter not formatted correctly\n",
5915 criteria, filter_pattern);
5916 }
5917 if (!strcmp(method, "regex")) {
5918 filter_entry->match_type = FILTER_MATCH_REGEX;
5919 } else if (!strcmp(method, "exact")) {
5920 filter_entry->match_type = FILTER_MATCH_EXACT;
5921 } else if (!strcmp(method, "starts_with")) {
5922 filter_entry->match_type = FILTER_MATCH_STARTS_WITH;
5923 } else if (!strcmp(method, "ends_with")) {
5924 filter_entry->match_type = FILTER_MATCH_ENDS_WITH;
5925 } else if (!strcmp(method, "contains")) {
5926 filter_entry->match_type = FILTER_MATCH_CONTAINS;
5927 } else if (!strcmp(method, "none")) {
5928 filter_entry->match_type = FILTER_MATCH_NONE;
5929 } else {
5930 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': 'method' option '%s' is unknown\n",
5931 criteria, filter_pattern, method);
5932 }
5933 options_found |= method_found;
5934 } else {
5935 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING, "'%s = %s': Filter option '%s' is unknown\n",
5936 criteria, filter_pattern, option);
5937 }
5938 temp = NULL;
5939 }
5940 if (!options_found) {
5941 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING,
5942 "'%s = %s': No action, name, header, or method option found\n",
5943 criteria, filter_pattern);
5944 }
5945 if (ast_strlen_zero(filter_pattern) && filter_entry->match_type != FILTER_MATCH_NONE) {
5946 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING,
5947 "'%s = %s': method can't be '%s' with no filter pattern\n",
5948 criteria, filter_pattern, match_type_names[filter_entry->match_type]);
5949 }
5950 if (!ast_strlen_zero(filter_pattern) && filter_entry->match_type == FILTER_MATCH_NONE) {
5951 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING,
5952 "'%s = %s': method can't be 'none' with a filter pattern\n",
5953 criteria, filter_pattern);
5954 }
5955 if (!(options_found & name_found) && !(options_found & header_found) &&
5956 filter_entry->match_type == FILTER_MATCH_NONE) {
5957 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_FORMAT_ERROR, LOG_WARNING,
5958 "'%s = %s': No name or header option found and no filter pattern\n",
5959 criteria, filter_pattern);
5960 }
5961 }
5962
5963 if (!ast_strlen_zero(filter_pattern)) {
5964 if (filter_entry->match_type == FILTER_MATCH_REGEX) {
5965 filter_entry->regex_filter = ast_calloc(1, sizeof(regex_t));
5966 if (!filter_entry->regex_filter) {
5967 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_ALLOC_FAILED, LOG_ERROR, "Unable to allocate memory for regex_filter");
5968 }
5969 if (regcomp(filter_entry->regex_filter, filter_pattern, REG_EXTENDED | REG_NOSUB)) {
5970 SCOPE_EXIT_LOG_RTN_VALUE(FILTER_COMPILE_FAIL, LOG_WARNING, "Unable to compile regex filter for '%s'", filter_pattern);
5971 }
5972 } else {
5973 filter_entry->string_filter = ast_strdup(filter_pattern);
5974 }
5975 }
5976
5977 ast_debug(2, "Event filter:\n"
5978 "conf entry: %s = %s\n"
5979 "event_name: %s (hash: %d)\n"
5980 "test_header: %s\n"
5981 "match_type: %s\n"
5982 "regex_filter: %p\n"
5983 "string filter: %s\n"
5984 "is excludefilter: %d\n",
5985 criteria, filter_pattern,
5986 S_OR(filter_entry->event_name, "<not used>"),
5987 filter_entry->event_name_hash,
5988 S_OR(filter_entry->header_name, "<not used>"),
5989 match_type_names[filter_entry->match_type],
5990 filter_entry->regex_filter,
5991 filter_entry->string_filter,
5992 filter_entry->is_excludefilter);
5993
5994 if (filter_entry->is_excludefilter) {
5995 ao2_t_link(excludefilters, filter_entry, "link new filter into exclude user container");
5996 } else {
5997 ao2_t_link(includefilters, filter_entry, "link new filter into include user container");
5998 }
5999
6000 SCOPE_EXIT_RTN_VALUE(FILTER_SUCCESS, "Filter added successfully");
6001 }
6002
6003 #ifdef TEST_FRAMEWORK
6004
6005 struct test_filter_data {
6006 const char *criteria;
6007 const char *filter;
6008 enum add_filter_result expected_add_filter_result;
6009 struct event_filter_entry expected_filter_entry;
6010 const char *test_event_name;
6011 const char *test_event_payload;
6012 int expected_should_send_event;
6013 };
6014
6015 static char *add_filter_result_enums[] = {
6016 [FILTER_SUCCESS] = "FILTER_SUCCESS",
6017 [FILTER_ALLOC_FAILED] = "FILTER_ALLOC_FAILED",
6018 [FILTER_COMPILE_FAIL] = "FILTER_COMPILE_FAIL",
6019 [FILTER_FORMAT_ERROR] = "FILTER_FORMAT_ERROR",
6020 };
6021
6022 #define TEST_EVENT_NEWCHANNEL "Newchannel", "Event: Newchannel\r\nChannel: XXX\r\nSomeheader: YYY\r\n"
6023 #define TEST_EVENT_VARSET "VarSet", "Event: VarSet\r\nChannel: ABC\r\nSomeheader: XXX\r\n"
6024 #define TEST_EVENT_NONE "", ""
6025
6026 static struct test_filter_data parsing_filter_tests[] = {
6027 /* Valid filters */
6028 { "eventfilter", "XXX", FILTER_SUCCESS,
6029 { FILTER_MATCH_REGEX, NULL, NULL, NULL, 0, NULL, 0}, TEST_EVENT_NEWCHANNEL, 1},
6030 { "eventfilter", "!XXX", FILTER_SUCCESS,
6031 { FILTER_MATCH_REGEX, NULL, NULL, NULL, 0, NULL, 1}, TEST_EVENT_VARSET, 0},
6032 { "eventfilter(name(VarSet),method(none))", "", FILTER_SUCCESS,
6033 { FILTER_MATCH_NONE, NULL, NULL, "VarSet", 0, NULL, 0}, TEST_EVENT_VARSET, 1},
6034 { "eventfilter(name(Newchannel),method(regex))", "X[XYZ]X", FILTER_SUCCESS,
6035 { FILTER_MATCH_REGEX, NULL, NULL, "Newchannel", 0, NULL, 0}, TEST_EVENT_NEWCHANNEL, 1},
6036 { "eventfilter(name(Newchannel),method(regex))", "X[abc]X", FILTER_SUCCESS,
6037 { FILTER_MATCH_REGEX, NULL, NULL, "Newchannel", 0, NULL, 0}, TEST_EVENT_NEWCHANNEL, 0},
6038 { "eventfilter(action(exclude),name(Newchannel),method(regex))", "X[XYZ]X", FILTER_SUCCESS,
6039 { FILTER_MATCH_REGEX, NULL, NULL, "Newchannel", 0, NULL, 1}, TEST_EVENT_NEWCHANNEL, 0},
6040 { "eventfilter(action(exclude),name(Newchannel),method(regex))", "X[abc]X", FILTER_SUCCESS,
6041 { FILTER_MATCH_REGEX, NULL, NULL, "Newchannel", 0, NULL, 1}, TEST_EVENT_NEWCHANNEL, 1},
6042 { "eventfilter(action(include),name(VarSet),header(Channel),method(starts_with))", "AB", FILTER_SUCCESS,
6043 { FILTER_MATCH_STARTS_WITH, NULL, NULL, "VarSet", 0, "Channel:", 0}, TEST_EVENT_VARSET, 1},
6044 { "eventfilter(action(include),name(VarSet),header(Channel),method(ends_with))", "BC", FILTER_SUCCESS,
6045 { FILTER_MATCH_ENDS_WITH, NULL, NULL, "VarSet", 0, "Channel:", 0}, TEST_EVENT_VARSET, 1},
6046 { "eventfilter(action(include),name(VarSet),header(Channel),method(exact))", "ABC", FILTER_SUCCESS,
6047 { FILTER_MATCH_EXACT, NULL, NULL, "VarSet", 0, "Channel:", 0}, TEST_EVENT_VARSET, 1},
6048 { "eventfilter(action(include),name(VarSet),header(Channel),method(exact))", "XXX", FILTER_SUCCESS,
6049 { FILTER_MATCH_EXACT, NULL, NULL, "VarSet", 0, "Channel:", 0}, TEST_EVENT_VARSET, 0},
6050 { "eventfilter(name(VarSet),header(Channel),method(exact))", "!ZZZ", FILTER_SUCCESS,
6051 { FILTER_MATCH_EXACT, NULL, NULL, "VarSet", 0, "Channel:", 1}, TEST_EVENT_VARSET, 1},
6052 { "eventfilter(action(exclude),name(VarSet),header(Channel),method(exact))", "ZZZ", FILTER_SUCCESS,
6053 { FILTER_MATCH_EXACT, NULL, NULL, "VarSet", 0, "Channel:", 1}, TEST_EVENT_VARSET, 1},
6054 { "eventfilter(action(include),name(VarSet),header(Someheader),method(exact))", "!XXX", FILTER_SUCCESS,
6055 { FILTER_MATCH_EXACT, NULL, NULL, "VarSet", 0, "Someheader:", 0}, TEST_EVENT_VARSET, 1},
6056
6057 /* Invalid filters */
6058 { "eventfilter(action(include)", "", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6059 { "eventfilter(action(inlude)", "", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6060 { "eventfilter(nnnn(yyy)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6061 { "eventfilter(eader(VarSet)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6062 { "eventfilter(ethod(contains)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6063 { "eventfilter(nnnn(yyy),header(VarSet),method(contains)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6064 { "eventfilter(name(yyy),heder(VarSet),method(contains)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6065 { "eventfilter(name(yyy),header(VarSet),mehod(contains)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6066 { "eventfilter(name(yyy),header(VarSet),method(coains)", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6067 { "eventfilter(method(yyy))", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6068 { "eventfilter", "", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6069 { "eventfilter", "!", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6070 { "eventfilter()", "XXX", FILTER_FORMAT_ERROR, { 0, }, TEST_EVENT_NONE, 0},
6071 { "eventfilter", "XX[X", FILTER_COMPILE_FAIL, { 0, }, TEST_EVENT_NONE, 0},
6072 { "eventfilter(method(regex))", "XX[X", FILTER_COMPILE_FAIL, { 0, }, TEST_EVENT_NONE, 0},
6073 };
6074
6075 /*
6076 * This is a bit different than ast_strings_equal in that
6077 * it will return 1 if both strings are NULL.
6078 */
6079 static int strings_equal(const char *str1, const char *str2)
6080 {
6081 if ((!str1 && str2) || (str1 && !str2)) {
6082 return 0;
6083 }
6084
6085 return str1 == str2 || !strcmp(str1, str2);
6086 }
6087
6088 AST_TEST_DEFINE(eventfilter_test_creation)
6089 {
6090 enum ast_test_result_state res = AST_TEST_PASS;
6091 RAII_VAR(struct ao2_container *, includefilters, NULL, ao2_cleanup);
6092 RAII_VAR(struct ao2_container *, excludefilters, NULL, ao2_cleanup);
6093 int i = 0;
6094
6095 switch (cmd) {
6096 case TEST_INIT:
6097 info->name = "eventfilter_test_creation";
6098 info->category = "/main/manager/";
6099 info->summary = "Test eventfilter creation";
6100 info->description =
6101 "This creates various eventfilters and tests to make sure they were created successfully.";
6102 return AST_TEST_NOT_RUN;
6103 case TEST_EXECUTE:
6104 break;
6105 }
6106
6107 includefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
6108 excludefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
6109 if (!includefilters || !excludefilters) {
6110 ast_test_status_update(test, "Failed to allocate filter containers.\n");
6111 return AST_TEST_FAIL;
6112 }
6113
6114 for (i = 0; i < ARRAY_LEN(parsing_filter_tests); i++) {
6115 struct event_filter_entry *filter_entry;
6116 enum add_filter_result add_filter_res;
6117 int send_event = 0;
6118 struct eventqent *eqe = NULL;
6119 int include_container_count = 0;
6120 int exclude_container_count = 0;
6121
6122 /* We need to clear the containers before each test */
6123 ao2_callback(includefilters, OBJ_UNLINK | OBJ_NODATA, NULL, NULL);
6124 ao2_callback(excludefilters, OBJ_UNLINK | OBJ_NODATA, NULL, NULL);
6125
6126 add_filter_res = manager_add_filter(parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6127 includefilters, excludefilters);
6128
6129 /* If you're adding a new test, enable this to see the full results */
6130 #if 0
6131 ast_test_debug(test, "Add filter result '%s = %s': Expected: %s Actual: %s %s\n",
6132 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6133 add_filter_result_enums[parsing_filter_tests[i].expected_add_filter_result],
6134 add_filter_result_enums[add_filter_res],
6135 add_filter_res != parsing_filter_tests[i].expected_add_filter_result ? "FAIL" : "PASS");
6136 #endif
6137
6138 if (add_filter_res != parsing_filter_tests[i].expected_add_filter_result) {
6139 ast_test_status_update(test,
6140 "Unexpected add filter result '%s = %s'. Expected result: %s Actual result: %s\n",
6141 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6142 add_filter_result_enums[parsing_filter_tests[i].expected_add_filter_result],
6143 add_filter_result_enums[add_filter_res]);
6144 res = AST_TEST_FAIL;
6145 continue;
6146 }
6147
6148 if (parsing_filter_tests[i].expected_add_filter_result != FILTER_SUCCESS) {
6149 /*
6150 * We don't need to test filters that we know aren't going
6151 * to be parsed successfully.
6152 */
6153 continue;
6154 }
6155
6156 /* We need to set the event name hash on the test data */
6157 if (parsing_filter_tests[i].expected_filter_entry.event_name) {
6158 parsing_filter_tests[i].expected_filter_entry.event_name_hash =
6159 ast_str_hash(parsing_filter_tests[i].expected_filter_entry.event_name);
6160 }
6161
6162 include_container_count = ao2_container_count(includefilters);
6163 exclude_container_count = ao2_container_count(excludefilters);
6164
6165 if (parsing_filter_tests[i].expected_filter_entry.is_excludefilter) {
6166 if (exclude_container_count != 1 || include_container_count != 0) {
6167 ast_test_status_update(test,
6168 "Invalid container counts for exclude filter '%s = %s'. Exclude: %d Include: %d. Should be 1 and 0\n",
6169 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6170 exclude_container_count, include_container_count);
6171 res = AST_TEST_FAIL;
6172 continue;
6173 }
6174 /* There can only be one entry in the container so ao2_find is fine */
6175 filter_entry = ao2_find(excludefilters, NULL, OBJ_SEARCH_OBJECT);
6176 } else {
6177 if (include_container_count != 1 || exclude_container_count != 0) {
6178 ast_test_status_update(test,
6179 "Invalid container counts for include filter '%s = %s'. Include: %d Exclude: %d. Should be 1 and 0\n",
6180 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6181 include_container_count, exclude_container_count);
6182 res = AST_TEST_FAIL;
6183 continue;
6184 }
6185 /* There can only be one entry in the container so ao2_find is fine */
6186 filter_entry = ao2_find(includefilters, NULL, OBJ_SEARCH_OBJECT);
6187 }
6188
6189 if (!filter_entry) {
6190 ast_test_status_update(test,
6191 "Failed to find filter entry for '%s = %s' in %s filter container\n",
6192 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6193 parsing_filter_tests[i].expected_filter_entry.is_excludefilter ? "exclude" : "include");
6194 res = AST_TEST_FAIL;
6195 goto loop_cleanup;
6196 }
6197
6198 if (filter_entry->match_type != parsing_filter_tests[i].expected_filter_entry.match_type) {
6199 ast_test_status_update(test,
6200 "Failed to match filter type for '%s = %s'. Expected: %s Actual: %s\n",
6201 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6202 match_type_names[parsing_filter_tests[i].expected_filter_entry.match_type],
6203 match_type_names[filter_entry->match_type]);
6204 res = AST_TEST_FAIL;
6205 goto loop_cleanup;
6206 }
6207
6208 if (!strings_equal(filter_entry->event_name, parsing_filter_tests[i].expected_filter_entry.event_name)) {
6209 ast_test_status_update(test,
6210 "Failed to match event name for '%s = %s'. Expected: '%s' Actual: '%s'\n",
6211 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6212 parsing_filter_tests[i].expected_filter_entry.event_name, filter_entry->event_name);
6213 res = AST_TEST_FAIL;
6214 goto loop_cleanup;
6215 }
6216
6217 if (filter_entry->event_name_hash != parsing_filter_tests[i].expected_filter_entry.event_name_hash) {
6218 ast_test_status_update(test,
6219 "Event name hashes failed to match for '%s = %s'. Expected: %u Actual: %u\n",
6220 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6221 parsing_filter_tests[i].expected_filter_entry.event_name_hash, filter_entry->event_name_hash);
6222 res = AST_TEST_FAIL;
6223 goto loop_cleanup;
6224 }
6225
6226 if (!strings_equal(filter_entry->header_name, parsing_filter_tests[i].expected_filter_entry.header_name)) {
6227 ast_test_status_update(test,
6228 "Failed to match header name for '%s = %s'. Expected: '%s' Actual: '%s'\n",
6229 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6230 parsing_filter_tests[i].expected_filter_entry.header_name, filter_entry->header_name);
6231 res = AST_TEST_FAIL;
6232 goto loop_cleanup;
6233 }
6234
6235 switch (parsing_filter_tests[i].expected_filter_entry.match_type) {
6236 case FILTER_MATCH_REGEX:
6237 if (!filter_entry->regex_filter) {
6238 ast_test_status_update(test,
6239 "Failed to compile regex filter for '%s = %s'\n",
6240 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter);
6241 res = AST_TEST_FAIL;
6242 goto loop_cleanup;
6243 }
6244 break;
6245 case FILTER_MATCH_NONE:
6246 if (filter_entry->regex_filter || !ast_strlen_zero(filter_entry->string_filter)) {
6247 ast_test_status_update(test,
6248 "Unexpected regex filter or string for '%s = %s' with match_type 'none'\n",
6249 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter);
6250 res = AST_TEST_FAIL;
6251 goto loop_cleanup;
6252 }
6253 break;
6254 case FILTER_MATCH_STARTS_WITH:
6255 case FILTER_MATCH_ENDS_WITH:
6256 case FILTER_MATCH_CONTAINS:
6257 case FILTER_MATCH_EXACT:
6258 if (filter_entry->regex_filter || ast_strlen_zero(filter_entry->string_filter)) {
6259 ast_test_status_update(test,
6260 "Unexpected regex filter or empty string for '%s = %s' with match_type '%s'\n",
6261 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6262 match_type_names[parsing_filter_tests[i].expected_filter_entry.match_type]);
6263 res = AST_TEST_FAIL;
6264 goto loop_cleanup;
6265 }
6266 break;
6267 default:
6268 res = AST_TEST_FAIL;
6269 goto loop_cleanup;
6270 }
6271
6272 /*
6273 * This is a basic test of whether a single event matches a single filter.
6274 */
6275 eqe = ast_calloc(1, sizeof(*eqe) + strlen(parsing_filter_tests[i].test_event_payload) + 1);
6276 if (!eqe) {
6277 ast_test_status_update(test, "Failed to allocate eventqent\n");
6278 res = AST_TEST_FAIL;
6279 ao2_ref(filter_entry, -1);
6280 break;
6281 }
6282 strcpy(eqe->eventdata, parsing_filter_tests[i].test_event_payload); /* Safe */
6283 eqe->event_name_hash = ast_str_hash(parsing_filter_tests[i].test_event_name);
6284 send_event = should_send_event(includefilters, excludefilters, eqe);
6285 if (send_event != parsing_filter_tests[i].expected_should_send_event) {
6286 char *escaped = ast_escape_c_alloc(parsing_filter_tests[i].test_event_payload);
6287 ast_test_status_update(test,
6288 "Should send event failed to match for '%s = %s' payload '%s'. Expected: %s Actual: %s\n",
6289 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter, escaped,
6290 AST_YESNO(parsing_filter_tests[i].expected_should_send_event), AST_YESNO(send_event));
6291 ast_free(escaped);
6292 res = AST_TEST_FAIL;
6293 }
6294 loop_cleanup:
6295 ast_free(eqe);
6296 ao2_cleanup(filter_entry);
6297
6298 }
6299 ast_test_status_update(test, "Tested %d filters\n", i);
6300
6301 return res;
6302 }
6303
6304 struct test_filter_matching {
6305 const char *criteria;
6306 const char *pattern;
6307 };
6308
6309 /*
6310 * These filters are used to test the precedence of include and exclude
6311 * filters. When there are both include and exclude filters, the include
6312 * filters are matched first. If the event doesn't match an include filter,
6313 * it's discarded. If it does match, the exclude filter list is searched and
6314 * if a match is found, the event is discarded.
6315 */
6316
6317 /*
6318 * The order of the filters in the array doesn't really matter. The
6319 * include and exclude filters are in separate containers and in each
6320 * container, traversal stops when a match is found.
6321 */
6322 static struct test_filter_matching filters_for_matching[] = {
6323 { "eventfilter(name(VarSet),method(none))", ""},
6324 { "eventfilter(name(Newchannel),method(regex))", "X[XYZ]X"},
6325 { "eventfilter(name(Newchannel),method(regex))", "X[abc]X"},
6326 { "eventfilter(name(Newchannel),header(Someheader),method(regex))", "ZZZ"},
6327 { "eventfilter(action(exclude),name(Newchannel),method(regex))", "X[a]X"},
6328 { "eventfilter(action(exclude),name(Newchannel),method(regex))", "X[Z]X"},
6329 { "eventfilter(action(exclude),name(VarSet),header(Channel),method(regex))", "YYY"},
6330 };
6331
6332 struct test_event_matching{
6333 const char *event_name;
6334 const char *payload;
6335 int expected_should_send_event;
6336 };
6337
6338 static struct test_event_matching events_for_matching[] = {
6339 { "Newchannel", "Event: Newchannel\r\nChannel: XXX\r\nSomeheader: YYY\r\n", 1 },
6340 { "Newchannel", "Event: Newchannel\r\nChannel: XZX\r\nSomeheader: YYY\r\n", 0 },
6341 { "Newchannel", "Event: Newchannel\r\nChannel: XaX\r\nSomeheader: YYY\r\n", 0 },
6342 { "Newchannel", "Event: Newchannel\r\nChannel: XbX\r\nSomeheader: YYY\r\n", 1 },
6343 { "Newchannel", "Event: Newchannel\r\nChannel: XcX\r\nSomeheader: YYY\r\n", 1 },
6344 { "Newchannel", "Event: Newchannel\r\nChannel: YYY\r\nSomeheader: YYY\r\n", 0 },
6345 { "Newchannel", "Event: Newchannel\r\nChannel: YYY\r\nSomeheader: ZZZ\r\n", 1 },
6346 { "VarSet", "Event: VarSet\r\nChannel: XXX\r\nSomeheader: YYY\r\n", 1 },
6347 { "VarSet", "Event: VarSet\r\nChannel: YYY\r\nSomeheader: YYY\r\n", 0 },
6348 };
6349
6350 AST_TEST_DEFINE(eventfilter_test_matching)
6351 {
6352 enum ast_test_result_state res = AST_TEST_PASS;
6353 RAII_VAR(struct ao2_container *, includefilters, NULL, ao2_cleanup);
6354 RAII_VAR(struct ao2_container *, excludefilters, NULL, ao2_cleanup);
6355 int i = 0;
6356
6357 switch (cmd) {
6358 case TEST_INIT:
6359 info->name = "eventfilter_test_matching";
6360 info->category = "/main/manager/";
6361 info->summary = "Test eventfilter matching";
6362 info->description =
6363 "This creates various eventfilters and tests to make sure they were matched successfully.";
6364 return AST_TEST_NOT_RUN;
6365 case TEST_EXECUTE:
6366 break;
6367 }
6368
6369 includefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
6370 excludefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
6371 if (!includefilters || !excludefilters) {
6372 ast_test_status_update(test, "Failed to allocate filter containers.\n");
6373 return AST_TEST_FAIL;
6374 }
6375
6376 /* Load all the expected SUCCESS filters */
6377 for (i = 0; i < ARRAY_LEN(filters_for_matching); i++) {
6378 enum add_filter_result add_filter_res;
6379
6380 add_filter_res = manager_add_filter(filters_for_matching[i].criteria,
6381 filters_for_matching[i].pattern, includefilters, excludefilters);
6382
6383 if (add_filter_res != FILTER_SUCCESS) {
6384 ast_test_status_update(test,
6385 "Unexpected add filter result '%s = %s'. Expected result: %s Actual result: %s\n",
6386 parsing_filter_tests[i].criteria, parsing_filter_tests[i].filter,
6387 add_filter_result_enums[FILTER_SUCCESS],
6388 add_filter_result_enums[add_filter_res]);
6389 res = AST_TEST_FAIL;
6390 break;
6391 }
6392 }
6393 ast_test_debug(test, "Loaded %d filters\n", i);
6394
6395 if (res != AST_TEST_PASS) {
6396 return res;
6397 }
6398
6399 /* Now test them */
6400 for (i = 0; i < ARRAY_LEN(events_for_matching); i++) {
6401 int send_event = 0;
6402 struct eventqent *eqe = NULL;
6403
6404 eqe = ast_calloc(1, sizeof(*eqe) + strlen(events_for_matching[i].payload) + 1);
6405 if (!eqe) {
6406 ast_test_status_update(test, "Failed to allocate eventqent\n");
6407 res = AST_TEST_FAIL;
6408 break;
6409 }
6410 strcpy(eqe->eventdata, events_for_matching[i].payload); /* Safe */
6411 eqe->event_name_hash = ast_str_hash(events_for_matching[i].event_name);
6412 send_event = should_send_event(includefilters, excludefilters, eqe);
6413 if (send_event != events_for_matching[i].expected_should_send_event) {
6414 char *escaped = ast_escape_c_alloc(events_for_matching[i].payload);
6415 ast_test_status_update(test,
6416 "Should send event failed to match for '%s'. Expected: %s Actual: %s\n",
6417 escaped,
6418 AST_YESNO(events_for_matching[i].expected_should_send_event), AST_YESNO(send_event));
6419 ast_free(escaped);
6420 res = AST_TEST_FAIL;
6421 }
6422 ast_free(eqe);
6423 }
6424 ast_test_debug(test, "Tested %d events\n", i);
6425
6426 return res;
6427 }
6428 #endif
6429
6430 /*!
6431 * Send any applicable events to the client listening on this socket.
6432 * Wait only for a finite time on each event, and drop all events whether
6433 * they are successfully sent or not.
6434 */
6435 static int process_events(struct mansession *s)
6436 {
6437 int ret = 0;
6438
6439 ao2_lock(s->session);
6440 if (s->session->stream != NULL) {
6441 struct eventqent *eqe = s->session->last_ev;
6442
6443 while ((eqe = advance_event(eqe))) {
6444 if (eqe->category == EVENT_FLAG_SHUTDOWN) {
6445 ast_debug(3, "Received CloseSession event\n");
6446 ret = -1;
6447 }
6448 if (!ret && s->session->authenticated &&
6449 (s->session->readperm & eqe->category) == eqe->category &&
6450 (s->session->send_events & eqe->category) == eqe->category) {
6451 if (should_send_event(s->session->includefilters, s->session->excludefilters, eqe)) {
6452 if (send_string(s, eqe->eventdata) < 0 || s->write_error)
6453 ret = -1; /* don't send more */
6454 }
6455 }
6456 s->session->last_ev = eqe;
6457 }
6458 }
6459 ao2_unlock(s->session);
6460 return ret;
6461 }
6462
6463 static int action_userevent(struct mansession *s, const struct message *m)
6464 {
6465 const char *event = astman_get_header(m, "UserEvent");
6466 struct ast_str *body = ast_str_thread_get(&userevent_buf, 16);
6467 int x;
6468
6469 ast_str_reset(body);
6470
6471 for (x = 0; x < m->hdrcount; x++) {
6472 if (strncasecmp("UserEvent:", m->headers[x], strlen("UserEvent:")) &&
6473 strncasecmp("Action:", m->headers[x], strlen("Action:"))) {
6474 ast_str_append(&body, 0, "%s\r\n", m->headers[x]);
6475 }
6476 }
6477
6478 astman_send_ack(s, m, "Event Sent");
6479 manager_event(EVENT_FLAG_USER, "UserEvent", "UserEvent: %s\r\n%s", event, ast_str_buffer(body));
6480 return 0;
6481 }
6482
6483 /*! \brief Show PBX core settings information */
6484 static int action_coresettings(struct mansession *s, const struct message *m)
6485 {
6486 const char *actionid = astman_get_header(m, "ActionID");
6487 char idText[150];
6488
6489 if (!ast_strlen_zero(actionid)) {
6490 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
6491 } else {
6492 idText[0] = '\0';
6493 }
6494
6495 astman_append(s, "Response: Success\r\n"
6496 "%s"
6497 "AMIversion: %s\r\n"
6498 "AsteriskVersion: %s\r\n"
6499 "SystemName: %s\r\n"
6500 "CoreMaxCalls: %d\r\n"
6501 "CoreMaxLoadAvg: %f\r\n"
6502 "CoreRunUser: %s\r\n"
6503 "CoreRunGroup: %s\r\n"
6504 "CoreMaxFilehandles: %d\r\n"
6505 "CoreRealTimeEnabled: %s\r\n"
6506 "CoreCDRenabled: %s\r\n"
6507 "CoreHTTPenabled: %s\r\n"
6508 "SoundsSearchCustomDir: %s\r\n"
6509 "\r\n",
6510 idText,
6511 AMI_VERSION,
6512 ast_get_version(),
6513 ast_config_AST_SYSTEM_NAME,
6514 ast_option_maxcalls,
6515 ast_option_maxload,
6516 ast_config_AST_RUN_USER,
6517 ast_config_AST_RUN_GROUP,
6518 ast_option_maxfiles,
6519 AST_CLI_YESNO(ast_realtime_enabled()),
6520 AST_CLI_YESNO(ast_cdr_is_enabled()),
6521 AST_CLI_YESNO(ast_webmanager_check_enabled()),
6522 AST_CLI_YESNO(ast_opt_sounds_search_custom)
6523 );
6524 return 0;
6525 }
6526
6527 /*! \brief Show PBX core status information */
6528 static int action_corestatus(struct mansession *s, const struct message *m)
6529 {
6530 const char *actionid = astman_get_header(m, "ActionID");
6531 char idText[150];
6532 char startuptime[150], startupdate[150];
6533 char reloadtime[150], reloaddate[150];
6534 struct ast_tm tm;
6535
6536 if (!ast_strlen_zero(actionid)) {
6537 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
6538 } else {
6539 idText[0] = '\0';
6540 }
6541
6542 ast_localtime(&ast_startuptime, &tm, NULL);
6543 ast_strftime(startuptime, sizeof(startuptime), "%H:%M:%S", &tm);
6544 ast_strftime(startupdate, sizeof(startupdate), "%Y-%m-%d", &tm);
6545 ast_localtime(&ast_lastreloadtime, &tm, NULL);
6546 ast_strftime(reloadtime, sizeof(reloadtime), "%H:%M:%S", &tm);
6547 ast_strftime(reloaddate, sizeof(reloaddate), "%Y-%m-%d", &tm);
6548
6549 astman_append(s, "Response: Success\r\n"
6550 "%s"
6551 "CoreStartupDate: %s\r\n"
6552 "CoreStartupTime: %s\r\n"
6553 "CoreReloadDate: %s\r\n"
6554 "CoreReloadTime: %s\r\n"
6555 "CoreCurrentCalls: %d\r\n"
6556 "CoreProcessedCalls: %d\r\n"
6557 "\r\n",
6558 idText,
6559 startupdate,
6560 startuptime,
6561 reloaddate,
6562 reloadtime,
6563 ast_active_channels(),
6564 ast_processed_calls()
6565 );
6566 return 0;
6567 }
6568
6569 /*! \brief Send a reload event */
6570 static int action_reload(struct mansession *s, const struct message *m)
6571 {
6572 const char *module = astman_get_header(m, "Module");
6573 enum ast_module_reload_result res = ast_module_reload(S_OR(module, NULL));
6574
6575 switch (res) {
6576 case AST_MODULE_RELOAD_NOT_FOUND:
6577 astman_send_error(s, m, "No such module");
6578 break;
6579 case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
6580 astman_send_error(s, m, "Module does not support reload");
6581 break;
6582 case AST_MODULE_RELOAD_ERROR:
6583 astman_send_error(s, m, "An unknown error occurred");
6584 break;
6585 case AST_MODULE_RELOAD_IN_PROGRESS:
6586 astman_send_error(s, m, "A reload is in progress");
6587 break;
6588 case AST_MODULE_RELOAD_UNINITIALIZED:
6589 astman_send_error(s, m, "Module not initialized");
6590 break;
6591 case AST_MODULE_RELOAD_QUEUED:
6592 case AST_MODULE_RELOAD_SUCCESS:
6593 /* Treat a queued request as success */
6594 astman_send_ack(s, m, "Module Reloaded");
6595 break;
6596 }
6597 return 0;
6598 }
6599
6600 /*! \brief Manager command "CoreShowChannels" - List currently defined channels
6601 * and some information about them. */
6602 static int action_coreshowchannels(struct mansession *s, const struct message *m)
6603 {
6604 const char *actionid = astman_get_header(m, "ActionID");
6605 char idText[256];
6606 int numchans = 0;
6607 struct ao2_container *channels;
6608 struct ao2_iterator it_chans;
6609 struct ast_channel_snapshot *cs;
6610
6611 if (!ast_strlen_zero(actionid)) {
6612 snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
6613 } else {
6614 idText[0] = '\0';
6615 }
6616
6617 channels = ast_channel_cache_by_name();
6618
6619 astman_send_listack(s, m, "Channels will follow", "start");
6620
6621 it_chans = ao2_iterator_init(channels, 0);
6622 for (; (cs = ao2_iterator_next(&it_chans)); ao2_ref(cs, -1)) {
6623 struct ast_str *built = ast_manager_build_channel_state_string_prefix(cs, "");
6624 char durbuf[16] = "";
6625
6626 if (!built) {
6627 continue;
6628 }
6629
6630 if (!ast_tvzero(cs->base->creationtime)) {
6631 int duration, durh, durm, durs;
6632
6633 duration = (int)(ast_tvdiff_ms(ast_tvnow(), cs->base->creationtime) / 1000);
6634 durh = duration / 3600;
6635 durm = (duration % 3600) / 60;
6636 durs = duration % 60;
6637 snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
6638 }
6639
6640 astman_append(s,
6641 "Event: CoreShowChannel\r\n"
6642 "%s"
6643 "%s"
6644 "Application: %s\r\n"
6645 "ApplicationData: %s\r\n"
6646 "Duration: %s\r\n"
6647 "BridgeId: %s\r\n"
6648 "\r\n",
6649 idText,
6650 ast_str_buffer(built),
6651 cs->dialplan->appl,
6652 cs->dialplan->data,
6653 durbuf,
6654 cs->bridge->id);
6655
6656 numchans++;
6657
6658 ast_free(built);
6659 }
6660 ao2_iterator_destroy(&it_chans);
6661
6662 astman_send_list_complete(s, m, "CoreShowChannelsComplete", numchans);
6663
6664 ao2_ref(channels, -1);
6665 return 0;
6666 }
6667
6668 /*! \brief Helper function to add a channel name to the vector */
6669 static int coreshowchannelmap_add_to_map(struct ao2_container *c, const char *s)
6670 {
6671 char *str;
6672
6673 str = ast_strdup(s);
6674 if (!str) {
6675 ast_log(LOG_ERROR, "Unable to append channel to channel map\n");
6676 return 1;
6677 }
6678
6679 /* If this is a duplicate, it will be ignored */
6680 ast_str_container_add(c, str);
6681
6682 return 0;
6683 }
6684
6685 /*! \brief Recursive function to get all channels in a bridge. Follow local channels as well */
6686 static int coreshowchannelmap_add_connected_channels(struct ao2_container *channel_map,
6687 struct ast_channel_snapshot *channel_snapshot, struct ast_bridge_snapshot *bridge_snapshot)
6688 {
6689 int res = 0;
6690 struct ao2_iterator iter;
6691 char *current_channel_uid;
6692
6693 iter = ao2_iterator_init(bridge_snapshot->channels, 0);
6694 while ((current_channel_uid = ao2_iterator_next(&iter))) {
6695 struct ast_channel_snapshot *current_channel_snapshot;
6696 int add_channel_res;
6697
6698 /* Don't add the original channel to the list - it's either already in there,
6699 * or it's the channel we want the map for */
6700 if (!strcmp(current_channel_uid, channel_snapshot->base->uniqueid)) {
6701 ao2_ref(current_channel_uid, -1);
6702 continue;
6703 }
6704
6705 current_channel_snapshot = ast_channel_snapshot_get_latest(current_channel_uid);
6706 if (!current_channel_snapshot) {
6707 ast_debug(5, "Unable to get channel snapshot\n");
6708 ao2_ref(current_channel_uid, -1);
6709 continue;
6710 }
6711
6712 add_channel_res = coreshowchannelmap_add_to_map(channel_map, current_channel_snapshot->base->name);
6713 if (add_channel_res) {
6714 res = 1;
6715 ao2_ref(current_channel_snapshot, -1);
6716 ao2_ref(current_channel_uid, -1);
6717 break;
6718 }
6719
6720 /* If this is a local channel that we haven't seen yet, let's go ahead and find out what else is connected to it */
6721 if (ast_begins_with(current_channel_snapshot->base->name, "Local")) {
6722 struct ast_channel_snapshot *other_local_snapshot;
6723 struct ast_bridge_snapshot *other_bridge_snapshot;
6724 int size = strlen(current_channel_snapshot->base->name);
6725 char other_local[size + 1];
6726
6727 /* Don't copy the trailing number - set it to 1 or 2, whichever one it currently is not */
6728 ast_copy_string(other_local, current_channel_snapshot->base->name, size);
6729 other_local[size - 1] = ast_ends_with(current_channel_snapshot->base->name, "1") ? '2' : '1';
6730 other_local[size] = '\0';
6731
6732 other_local_snapshot = ast_channel_snapshot_get_latest_by_name(other_local);
6733 if (!other_local_snapshot) {
6734 ast_debug(5, "Unable to get other local channel snapshot\n");
6735 ao2_ref(current_channel_snapshot, -1);
6736 ao2_ref(current_channel_uid, -1);
6737 continue;
6738 }
6739
6740 if (coreshowchannelmap_add_to_map(channel_map, other_local_snapshot->base->name)) {
6741 res = 1;
6742 ao2_ref(current_channel_snapshot, -1);
6743 ao2_ref(current_channel_uid, -1);
6744 ao2_ref(other_local_snapshot, -1);
6745 break;
6746 }
6747
6748 other_bridge_snapshot = ast_bridge_get_snapshot_by_uniqueid(other_local_snapshot->bridge->id);
6749 if (other_bridge_snapshot) {
6750 res = coreshowchannelmap_add_connected_channels(channel_map, other_local_snapshot, other_bridge_snapshot);
6751 }
6752
6753 ao2_ref(current_channel_snapshot, -1);
6754 ao2_ref(current_channel_uid, -1);
6755 ao2_ref(other_local_snapshot, -1);
6756 ao2_ref(other_bridge_snapshot, -1);
6757
6758 if (res) {
6759 break;
6760 }
6761 }
6762 }
6763 ao2_iterator_destroy(&iter);
6764
6765 return res;
6766 }
6767
6768 /*! \brief Manager command "CoreShowChannelMap" - Lists all channels connected to
6769 * the specified channel. */
6770 static int action_coreshowchannelmap(struct mansession *s, const struct message *m)
6771 {
6772 const char *actionid = astman_get_header(m, "ActionID");
6773 const char *channel_name = astman_get_header(m, "Channel");
6774 char *current_channel_name;
6775 char id_text[256];
6776 int total = 0;
6777 struct ao2_container *channel_map;
6778 struct ao2_iterator i;
6779 RAII_VAR(struct ast_bridge_snapshot *, bridge_snapshot, NULL, ao2_cleanup);
6780 RAII_VAR(struct ast_channel_snapshot *, channel_snapshot, NULL, ao2_cleanup);
6781
6782 if (!ast_strlen_zero(actionid)) {
6783 snprintf(id_text, sizeof(id_text), "ActionID: %s\r\n", actionid);
6784 } else {
6785 id_text[0] = '\0';
6786 }
6787
6788 if (ast_strlen_zero(channel_name)) {
6789 astman_send_error(s, m, "CoreShowChannelMap requires a channel.\n");
6790 return 0;
6791 }
6792
6793 channel_snapshot = ast_channel_snapshot_get_latest_by_name(channel_name);
6794 if (!channel_snapshot) {
6795 astman_send_error(s, m, "Could not get channel snapshot\n");
6796 return 0;
6797 }
6798
6799 if (ast_strlen_zero(channel_snapshot->bridge->id)) {
6800 astman_send_listack(s, m, "Channel map will follow", "start");
6801 astman_send_list_complete_start(s, m, "CoreShowChannelMapComplete", 0);
6802 astman_send_list_complete_end(s);
6803 return 0;
6804 }
6805
6806 bridge_snapshot = ast_bridge_get_snapshot_by_uniqueid(channel_snapshot->bridge->id);
6807 if (!bridge_snapshot) {
6808 astman_send_listack(s, m, "Channel map will follow", "start");
6809 astman_send_list_complete_start(s, m, "CoreShowChannelMapComplete", 0);
6810 astman_send_list_complete_end(s);
6811 return 0;
6812 }
6813
6814 channel_map = ast_str_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK | AO2_CONTAINER_ALLOC_OPT_DUPS_OBJ_REJECT, 1);
6815 if (!channel_map) {
6816 astman_send_error(s, m, "Could not create channel map\n");
6817 return 0;
6818 }
6819
6820 astman_send_listack(s, m, "Channel map will follow", "start");
6821
6822 if (coreshowchannelmap_add_connected_channels(channel_map, channel_snapshot, bridge_snapshot)) {
6823 astman_send_error(s, m, "Could not complete channel map\n");
6824 ao2_ref(channel_map, -1);
6825 return 0;
6826 }
6827
6828 i = ao2_iterator_init(channel_map, 0);
6829 while ((current_channel_name = ao2_iterator_next(&i))) {
6830 astman_append(s,
6831 "Event: CoreShowChannelMap\r\n"
6832 "%s"
6833 "Channel: %s\r\n"
6834 "ConnectedChannel: %s\r\n\r\n",
6835 id_text,
6836 channel_name,
6837 current_channel_name);
6838 total++;
6839 }
6840 ao2_iterator_destroy(&i);
6841
6842 ao2_ref(channel_map, -1);
6843 astman_send_list_complete_start(s, m, "CoreShowChannelMapComplete", total);
6844 astman_send_list_complete_end(s);
6845
6846 return 0;
6847 }
6848
6849 /*! \brief Manager command "LoggerRotate" - reloads and rotates the logger in
6850 * the same manner as the CLI command 'logger rotate'. */
6851 static int action_loggerrotate(struct mansession *s, const struct message *m)
6852 {
6853 if (ast_logger_rotate()) {
6854 astman_send_error(s, m, "Failed to reload the logger and rotate log files");
6855 return 0;
6856 }
6857
6858 astman_send_ack(s, m, "Reloaded the logger and rotated log files");
6859 return 0;
6860 }
6861
6862 /*! \brief Manager function to check if module is loaded */
6863 static int manager_modulecheck(struct mansession *s, const struct message *m)
6864 {
6865 const char *module = astman_get_header(m, "Module");
6866 const char *id = astman_get_header(m, "ActionID");
6867
6868 ast_debug(1, "**** ModuleCheck .so file %s\n", module);
6869 if (!ast_module_check(module)) {
6870 astman_send_error(s, m, "Module not loaded");
6871 return 0;
6872 }
6873
6874 astman_append(s, "Response: Success\r\n");
6875
6876 if (!ast_strlen_zero(id)) {
6877 astman_append(s, "ActionID: %s\r\n", id);
6878 }
6879
6880 #if !defined(LOW_MEMORY)
6881 /* When we switched from subversion to git we lost the ability to
6882 * retrieve the 'ASTERISK_FILE_VERSION' from that file, but we retain
6883 * the response header here for backwards compatibility. */
6884 astman_append(s, "Version: \r\n");
6885 #endif
6886
6887 astman_append(s, "\r\n");
6888
6889 return 0;
6890 }
6891
6892 /**
6893 * \brief Check if the given file path is in the modules dir or not
6894 *
6895 * \note When the module is being loaded / reloaded / unloaded, the modules dir is
6896 * automatically prepended
6897 *
6898 * \return 1 if inside modules dir
6899 * \return 0 if outside modules dir
6900 * \return -1 on failure
6901 */
6902 static int file_in_modules_dir(const char *filename)
6903 {
6904 char *stripped_filename;
6905 RAII_VAR(char *, path, NULL, ast_free);
6906 RAII_VAR(char *, real_path, NULL, ast_free);
6907
6908 /* Don't bother checking */
6909 if (live_dangerously) {
6910 return 1;
6911 }
6912
6913 stripped_filename = ast_strip(ast_strdupa(filename));
6914
6915 /* Always prepend the modules dir since that is what the code does for ModuleLoad */
6916 if (ast_asprintf(&path, "%s/%s", ast_config_AST_MODULE_DIR, stripped_filename) == -1) {
6917 return -1;
6918 }
6919
6920 real_path = realpath(path, NULL);
6921 if (!real_path) {
6922 return -1;
6923 }
6924
6925 return ast_begins_with(real_path, ast_config_AST_MODULE_DIR);
6926 }
6927
6928 static int manager_moduleload(struct mansession *s, const struct message *m)
6929 {
6930 int res;
6931 const char *module = astman_get_header(m, "Module");
6932 const char *loadtype = astman_get_header(m, "LoadType");
6933 const char *recursive = astman_get_header(m, "Recursive");
6934
6935 if (!loadtype || strlen(loadtype) == 0) {
6936 astman_send_error(s, m, "Incomplete ModuleLoad action.");
6937 }
6938 if ((!module || strlen(module) == 0) && strcasecmp(loadtype, "reload") != 0) {
6939 astman_send_error(s, m, "Need module name");
6940 }
6941
6942 res = file_in_modules_dir(module);
6943 if (res == 0) {
6944 astman_send_error(s, m, "Module must be in the configured modules directory.");
6945 return 0;
6946 } else if (res == -1) {
6947 astman_send_error(s, m, "Module not found.");
6948 return 0;
6949 }
6950
6951 if (!strcasecmp(loadtype, "load")) {
6952 res = ast_load_resource(module);
6953 if (res) {
6954 astman_send_error(s, m, "Could not load module.");
6955 } else {
6956 astman_send_ack(s, m, "Module loaded.");
6957 }
6958 } else if (!strcasecmp(loadtype, "unload")) {
6959 res = ast_unload_resource(module, AST_FORCE_SOFT);
6960 if (res) {
6961 astman_send_error(s, m, "Could not unload module.");
6962 } else {
6963 astman_send_ack(s, m, "Module unloaded.");
6964 }
6965 } else if (!strcasecmp(loadtype, "refresh")) {
6966 res = ast_refresh_resource(module, AST_FORCE_SOFT, !ast_strlen_zero(recursive) && ast_true(recursive));
6967 if (res) {
6968 astman_send_error(s, m, "Could not refresh module.");
6969 } else {
6970 astman_send_ack(s, m, "Module unloaded and loaded.");
6971 }
6972 } else if (!strcasecmp(loadtype, "reload")) {
6973 /* TODO: Unify the ack/error messages here with action_reload */
6974 if (!ast_strlen_zero(module)) {
6975 enum ast_module_reload_result reload_res = ast_module_reload(module);
6976
6977 switch (reload_res) {
6978 case AST_MODULE_RELOAD_NOT_FOUND:
6979 astman_send_error(s, m, "No such module.");
6980 break;
6981 case AST_MODULE_RELOAD_NOT_IMPLEMENTED:
6982 astman_send_error(s, m, "Module does not support reload action.");
6983 break;
6984 case AST_MODULE_RELOAD_ERROR:
6985 astman_send_error(s, m, "An unknown error occurred");
6986 break;
6987 case AST_MODULE_RELOAD_IN_PROGRESS:
6988 astman_send_error(s, m, "A reload is in progress");
6989 break;
6990 case AST_MODULE_RELOAD_UNINITIALIZED:
6991 astman_send_error(s, m, "Module not initialized");
6992 break;
6993 case AST_MODULE_RELOAD_QUEUED:
6994 case AST_MODULE_RELOAD_SUCCESS:
6995 /* Treat a queued request as success */
6996 astman_send_ack(s, m, "Module reloaded.");
6997 break;
6998 }
6999 } else {
7000 ast_module_reload(NULL); /* Reload all modules */
7001 astman_send_ack(s, m, "All modules reloaded");
7002 }
7003 } else {
7004 astman_send_error(s, m, "Incomplete ModuleLoad action.");
7005 }
7006 return 0;
7007 }
7008
7009 static void log_action(const struct message *m, const char *action)
7010 {
7011 struct ast_str *buf;
7012 int x;
7013
7014 if (!manager_debug) {
7015 return;
7016 }
7017
7018 buf = ast_str_create(256);
7019 if (!buf) {
7020 return;
7021 }
7022
7023 for (x = 0; x < m->hdrcount; ++x) {
7024 if (!strncasecmp(m->headers[x], "Secret", 6)) {
7025 ast_str_append(&buf, 0, "Secret: <redacted from logging>\n");
7026 } else {
7027 ast_str_append(&buf, 0, "%s\n", m->headers[x]);
7028 }
7029 }
7030
7031 ast_verbose("<--- Examining AMI action: -->\n%s\n", ast_str_buffer(buf));
7032 ast_free(buf);
7033 }
7034
7035 /*
7036 * Done with the action handlers here, we start with the code in charge
7037 * of accepting connections and serving them.
7038 * accept_thread() forks a new thread for each connection, session_do(),
7039 * which in turn calls get_input() repeatedly until a full message has
7040 * been accumulated, and then invokes process_message() to pass it to
7041 * the appropriate handler.
7042 */
7043
7044 /*! \brief
7045 * Process an AMI message, performing desired action.
7046 * Return 0 on success, -1 on error that require the session to be destroyed.
7047 */
7048 static int process_message(struct mansession *s, const struct message *m)
7049 {
7050 int ret = 0;
7051 struct manager_action *act_found;
7052 struct ast_manager_user *user = NULL;
7053 const char *username;
7054 const char *action;
7055
7056 action = __astman_get_header(m, "Action", GET_HEADER_SKIP_EMPTY);
7057 if (ast_strlen_zero(action)) {
7058 report_req_bad_format(s, "NONE");
7059 mansession_lock(s);
7060 astman_send_error(s, m, "Missing action in request");
7061 mansession_unlock(s);
7062 return 0;
7063 }
7064
7065 log_action(m, action);
7066
7067 if (ast_shutting_down()) {
7068 ast_log(LOG_ERROR, "Unable to process manager action '%s'. Asterisk is shutting down.\n", action);
7069 mansession_lock(s);
7070 astman_send_error(s, m, "Asterisk is shutting down");
7071 mansession_unlock(s);
7072 return 0;
7073 }
7074
7075 if (!s->session->authenticated
7076 && strcasecmp(action, "Login")
7077 && strcasecmp(action, "Logoff")
7078 && strcasecmp(action, "Challenge")) {
7079 if (!s->session->authenticated) {
7080 report_req_not_allowed(s, action);
7081 }
7082 mansession_lock(s);
7083 astman_send_error(s, m, "Permission denied");
7084 mansession_unlock(s);
7085 return 0;
7086 }
7087
7088 if (!s->session->authenticated
7089 && (!strcasecmp(action, "Login")
7090 || !strcasecmp(action, "Challenge"))) {
7091 username = astman_get_header(m, "Username");
7092
7093 if (!ast_strlen_zero(username) && check_manager_session_inuse(username)) {
7094 AST_RWLIST_WRLOCK(&users);
7095 user = get_manager_by_name_locked(username);
7096 if (user && !user->allowmultiplelogin) {
7097 AST_RWLIST_UNLOCK(&users);
7098 report_session_limit(s);
7099 sleep(1);
7100 mansession_lock(s);
7101 astman_send_error(s, m, "Login Already In Use");
7102 mansession_unlock(s);
7103 return -1;
7104 }
7105 AST_RWLIST_UNLOCK(&users);
7106 }
7107 }
7108
7109 act_found = action_find(action);
7110 if (act_found) {
7111 /* Found the requested AMI action. */
7112 int acted = 0;
7113
7114 if ((s->session->writeperm & act_found->authority)
7115 || act_found->authority == 0) {
7116 /* We have the authority to execute the action. */
7117 ret = -1;
7118 ao2_lock(act_found);
7119 if (act_found->registered && act_found->func) {
7120 struct ast_module *mod_ref = ast_module_running_ref(act_found->module);
7121
7122 ao2_unlock(act_found);
7123 if (mod_ref || !act_found->module) {
7124 ast_debug(1, "Running action '%s'\n", act_found->action);
7125 ret = act_found->func(s, m);
7126 acted = 1;
7127 ast_module_unref(mod_ref);
7128 }
7129 } else {
7130 ao2_unlock(act_found);
7131 }
7132 }
7133 if (!acted) {
7134 /*
7135 * We did not execute the action because access was denied, it
7136 * was no longer registered, or no action was really registered.
7137 * Complain about it and leave.
7138 */
7139 report_req_not_allowed(s, action);
7140 mansession_lock(s);
7141 astman_send_error(s, m, "Permission denied");
7142 mansession_unlock(s);
7143 }
7144 ao2_t_ref(act_found, -1, "done with found action object");
7145 } else {
7146 char buf[512];
7147
7148 report_req_bad_format(s, action);
7149 snprintf(buf, sizeof(buf), "Invalid/unknown command: %s. Use Action: ListCommands to show available commands.", action);
7150 mansession_lock(s);
7151 astman_send_error(s, m, buf);
7152 mansession_unlock(s);
7153 }
7154 if (ret) {
7155 return ret;
7156 }
7157 /* Once done with our message, deliver any pending events unless the
7158 requester doesn't want them as part of this response.
7159 */
7160 if (ast_strlen_zero(astman_get_header(m, "SuppressEvents"))) {
7161 return process_events(s);
7162 } else {
7163 return ret;
7164 }
7165 }
7166
7167 /*!
7168 * Read one full line (including crlf) from the manager socket.
7169 * \note \verbatim
7170 * \r\n is the only valid terminator for the line.
7171 * (Note that, later, '\0' will be considered as the end-of-line marker,
7172 * so everything between the '\0' and the '\r\n' will not be used).
7173 * Also note that we assume output to have at least "maxlen" space.
7174 * \endverbatim
7175 */
7176 static int get_input(struct mansession *s, char *output)
7177 {
7178 int res, x;
7179 int maxlen = sizeof(s->session->inbuf) - 1;
7180 char *src = s->session->inbuf;
7181 int timeout = -1;
7182 time_t now;
7183
7184 /*
7185 * Look for \r\n within the buffer. If found, copy to the output
7186 * buffer and return, trimming the \r\n (not used afterwards).
7187 */
7188 for (x = 0; x < s->session->inlen; x++) {
7189 int cr; /* set if we have \r */
7190 if (src[x] == '\r' && x+1 < s->session->inlen && src[x + 1] == '\n') {
7191 cr = 2; /* Found. Update length to include \r\n */
7192 } else if (src[x] == '\n') {
7193 cr = 1; /* also accept \n only */
7194 } else {
7195 continue;
7196 }
7197 memmove(output, src, x); /*... but trim \r\n */
7198 output[x] = '\0'; /* terminate the string */
7199 x += cr; /* number of bytes used */
7200 s->session->inlen -= x; /* remaining size */
7201 memmove(src, src + x, s->session->inlen); /* remove used bytes */
7202 return 1;
7203 }
7204 if (s->session->inlen >= maxlen) {
7205 /* no crlf found, and buffer full - sorry, too long for us
7206 * keep the last character in case we are in the middle of a CRLF. */
7207 ast_log(LOG_WARNING, "Discarding message from %s. Line too long: %.25s...\n", ast_sockaddr_stringify_addr(&s->session->addr), src);
7208 src[0] = src[s->session->inlen - 1];
7209 s->session->inlen = 1;
7210 s->parsing = MESSAGE_LINE_TOO_LONG;
7211 }
7212 res = 0;
7213 while (res == 0) {
7214 /* calculate a timeout if we are not authenticated */
7215 if (!s->session->authenticated) {
7216 if(time(&now) == -1) {
7217 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
7218 return -1;
7219 }
7220
7221 timeout = (authtimeout - (now - s->session->authstart)) * 1000;
7222 if (timeout < 0) {
7223 /* we have timed out */
7224 return 0;
7225 }
7226 }
7227
7228 ast_mutex_lock(&s->session->notify_lock);
7229 if (s->session->pending_event) {
7230 s->session->pending_event = 0;
7231 ast_mutex_unlock(&s->session->notify_lock);
7232 return 0;
7233 }
7234 s->session->waiting_thread = pthread_self();
7235 ast_mutex_unlock(&s->session->notify_lock);
7236
7237 res = ast_wait_for_input(ast_iostream_get_fd(s->session->stream), timeout);
7238
7239 ast_mutex_lock(&s->session->notify_lock);
7240 s->session->waiting_thread = AST_PTHREADT_NULL;
7241 ast_mutex_unlock(&s->session->notify_lock);
7242 }
7243 if (res < 0) {
7244 if (s->session->kicked) {
7245 ast_debug(1, "Manager session has been kicked\n");
7246 return -1;
7247 }
7248 /* If we get a signal from some other thread (typically because
7249 * there are new events queued), return 0 to notify the caller.
7250 */
7251 if (errno == EINTR || errno == EAGAIN) {
7252 return 0;
7253 }
7254 ast_log(LOG_WARNING, "poll() returned error: %s\n", strerror(errno));
7255 return -1;
7256 }
7257
7258 ao2_lock(s->session);
7259 res = ast_iostream_read(s->session->stream, src + s->session->inlen, maxlen - s->session->inlen);
7260 if (res < 1) {
7261 res = -1; /* error return */
7262 } else {
7263 s->session->inlen += res;
7264 src[s->session->inlen] = '\0';
7265 res = 0;
7266 }
7267 ao2_unlock(s->session);
7268 return res;
7269 }
7270
7271 /*!
7272 * \internal
7273 * \brief Error handling for sending parse errors. This function handles locking, and clearing the
7274 * parse error flag.
7275 *
7276 * \param s AMI session to process action request.
7277 * \param m Message that's in error.
7278 * \param error Error message to send.
7279 */
7280 static void handle_parse_error(struct mansession *s, struct message *m, char *error)
7281 {
7282 mansession_lock(s);
7283 astman_send_error(s, m, error);
7284 s->parsing = MESSAGE_OKAY;
7285 mansession_unlock(s);
7286 }
7287
7288 /*!
7289 * \internal
7290 * \brief Read and process an AMI action request.
7291 *
7292 * \param s AMI session to process action request.
7293 *
7294 * \retval 0 Retain AMI connection for next command.
7295 * \retval -1 Drop AMI connection due to logoff or connection error.
7296 */
7297 static int do_message(struct mansession *s)
7298 {
7299 struct message m = { 0 };
7300 char header_buf[sizeof(s->session->inbuf)] = { '\0' };
7301 int res;
7302 int hdr_loss;
7303 time_t now;
7304
7305 hdr_loss = 0;
7306 for (;;) {
7307 /* Check if any events are pending and do them if needed */
7308 if (process_events(s)) {
7309 res = -1;
7310 break;
7311 }
7312 res = get_input(s, header_buf);
7313 if (res == 0) {
7314 /* No input line received. */
7315 if (!s->session->authenticated) {
7316 if (time(&now) == -1) {
7317 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
7318 res = -1;
7319 break;
7320 }
7321
7322 if (now - s->session->authstart > authtimeout) {
7323 if (displayconnects) {
7324 ast_verb(2, "Client from %s, failed to authenticate in %d seconds\n", ast_sockaddr_stringify_addr(&s->session->addr), authtimeout);
7325 }
7326 res = -1;
7327 break;
7328 }
7329 }
7330 continue;
7331 } else if (res > 0) {
7332 /* Input line received. */
7333 if (ast_strlen_zero(header_buf)) {
7334 if (hdr_loss) {
7335 mansession_lock(s);
7336 astman_send_error(s, &m, "Too many lines in message or allocation failure");
7337 mansession_unlock(s);
7338 res = 0;
7339 } else {
7340 switch (s->parsing) {
7341 case MESSAGE_OKAY:
7342 res = process_message(s, &m) ? -1 : 0;
7343 break;
7344 case MESSAGE_LINE_TOO_LONG:
7345 handle_parse_error(s, &m, "Failed to parse message: line too long");
7346 res = 0;
7347 break;
7348 }
7349 }
7350 break;
7351 } else if (m.hdrcount < ARRAY_LEN(m.headers)) {
7352 m.headers[m.hdrcount] = ast_strdup(header_buf);
7353 if (!m.headers[m.hdrcount]) {
7354 /* Allocation failure. */
7355 hdr_loss = 1;
7356 } else {
7357 ++m.hdrcount;
7358 }
7359 } else {
7360 /* Too many lines in message. */
7361 hdr_loss = 1;
7362 }
7363 } else {
7364 /* Input error. */
7365 break;
7366 }
7367 }
7368
7369 astman_free_headers(&m);
7370
7371 return res;
7372 }
7373
7374 /*! \brief The body of the individual manager session.
7375 * Call get_input() to read one line at a time
7376 * (or be woken up on new events), collect the lines in a
7377 * message until found an empty line, and execute the request.
7378 * In any case, deliver events asynchronously through process_events()
7379 * (called from here if no line is available, or at the end of
7380 * process_message(). )
7381 */
7382 static void *session_do(void *data)
7383 {
7384 struct ast_tcptls_session_instance *ser = data;
7385 struct mansession_session *session;
7386 struct mansession s = {
7387 .tcptls_session = data,
7388 };
7389 int res;
7390 int arg = 1;
7391 struct ast_sockaddr ser_remote_address_tmp;
7392
7393 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
7394 ast_atomic_fetchadd_int(&unauth_sessions, -1);
7395 goto done;
7396 }
7397
7398 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
7399 session = build_mansession(&ser_remote_address_tmp);
7400
7401 if (session == NULL) {
7402 ast_atomic_fetchadd_int(&unauth_sessions, -1);
7403 goto done;
7404 }
7405
7406 /* here we set TCP_NODELAY on the socket to disable Nagle's algorithm.
7407 * This is necessary to prevent delays (caused by buffering) as we
7408 * write to the socket in bits and pieces. */
7409 if (setsockopt(ast_iostream_get_fd(ser->stream), IPPROTO_TCP, TCP_NODELAY, (char *) &arg, sizeof(arg)) < 0) {
7410 ast_log(LOG_WARNING, "Failed to set TCP_NODELAY on manager connection: %s\n", strerror(errno));
7411 }
7412 ast_iostream_nonblock(ser->stream);
7413
7414 ao2_lock(session);
7415 /* Hook to the tail of the event queue */
7416 session->last_ev = grab_last();
7417
7418 ast_mutex_init(&s.lock);
7419
7420 /* these fields duplicate those in the 'ser' structure */
7421 session->stream = s.stream = ser->stream;
7422 ast_sockaddr_copy(&session->addr, &ser_remote_address_tmp);
7423 s.session = session;
7424
7425 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
7426
7427 if(time(&session->authstart) == -1) {
7428 ast_log(LOG_ERROR, "error executing time(): %s; disconnecting client\n", strerror(errno));
7429 ast_atomic_fetchadd_int(&unauth_sessions, -1);
7430 ao2_unlock(session);
7431 session_destroy(session);
7432 goto done;
7433 }
7434 ao2_unlock(session);
7435
7436 /*
7437 * We cannot let the stream exclusively wait for data to arrive.
7438 * We have to wake up the task to send async events.
7439 */
7440 ast_iostream_set_exclusive_input(ser->stream, 0);
7441
7442 ast_iostream_set_timeout_sequence(ser->stream,
7443 ast_tvnow(), authtimeout * 1000);
7444
7445 astman_append(&s, "Asterisk Call Manager/%s\r\n", AMI_VERSION); /* welcome prompt */
7446 for (;;) {
7447 if ((res = do_message(&s)) < 0 || s.write_error || session->kicked) {
7448 break;
7449 }
7450 if (session->authenticated) {
7451 ast_iostream_set_timeout_disable(ser->stream);
7452 }
7453 }
7454 /* session is over, explain why and terminate */
7455 if (session->authenticated) {
7456 if (manager_displayconnects(session)) {
7457 ast_verb(2, "Manager '%s' %s from %s\n", session->username, session->kicked ? "kicked" : "logged off", ast_sockaddr_stringify_addr(&session->addr));
7458 }
7459 } else {
7460 ast_atomic_fetchadd_int(&unauth_sessions, -1);
7461 if (displayconnects) {
7462 ast_verb(2, "Connect attempt from '%s' unable to authenticate\n", ast_sockaddr_stringify_addr(&session->addr));
7463 }
7464 }
7465
7466 session_destroy(session);
7467
7468 ast_mutex_destroy(&s.lock);
7469 done:
7470 ao2_ref(ser, -1);
7471 ser = NULL;
7472 return NULL;
7473 }
7474
7475 /*! \brief remove at most n_max stale session from the list. */
7476 static int purge_sessions(int n_max)
7477 {
7478 struct ao2_container *sessions;
7479 struct mansession_session *session;
7480 time_t now = time(NULL);
7481 struct ao2_iterator i;
7482 int purged = 0;
7483
7484 sessions = ao2_global_obj_ref(mgr_sessions);
7485 if (!sessions) {
7486 return 0;
7487 }
7488 i = ao2_iterator_init(sessions, 0);
7489 ao2_ref(sessions, -1);
7490
7491 /* The order of operations is significant */
7492 while (n_max > 0 && (session = ao2_iterator_next(&i))) {
7493 ao2_lock(session);
7494 if (session->sessiontimeout && (now > session->sessiontimeout) && !session->inuse) {
7495 if (session->authenticated
7496 && VERBOSITY_ATLEAST(2)
7497 && manager_displayconnects(session)) {
7498 ast_verb(2, "HTTP Manager '%s' timed out from %s\n",
7499 session->username, ast_sockaddr_stringify_addr(&session->addr));
7500 }
7501 ao2_unlock(session);
7502 session_destroy(session);
7503 n_max--;
7504 purged++;
7505 } else {
7506 ao2_unlock(session);
7507 unref_mansession(session);
7508 }
7509 }
7510 ao2_iterator_destroy(&i);
7511 return purged;
7512 }
7513
7514 /*! \brief
7515 * events are appended to a queue from where they
7516 * can be dispatched to clients.
7517 */
7518 static int append_event(const char *str, int event_name_hash, int category)
7519 {
7520 struct eventqent *tmp = ast_malloc(sizeof(*tmp) + strlen(str));
7521 static int seq; /* sequence number */
7522
7523 if (!tmp) {
7524 return -1;
7525 }
7526
7527 /* need to init all fields, because ast_malloc() does not */
7528 tmp->usecount = 0;
7529 tmp->category = category;
7530 tmp->seq = ast_atomic_fetchadd_int(&seq, 1);
7531 tmp->tv = ast_tvnow();
7532 tmp->event_name_hash = event_name_hash;
7533 AST_RWLIST_NEXT(tmp, eq_next) = NULL;
7534 strcpy(tmp->eventdata, str);
7535
7536 AST_RWLIST_WRLOCK(&all_events);
7537 AST_RWLIST_INSERT_TAIL(&all_events, tmp, eq_next);
7538 AST_RWLIST_UNLOCK(&all_events);
7539
7540 return 0;
7541 }
7542
7543 static void append_channel_vars(struct ast_str **pbuf, struct ast_channel *chan)
7544 {
7545 struct varshead *vars;
7546 struct ast_var_t *var;
7547
7548 vars = ast_channel_get_manager_vars(chan);
7549 if (!vars) {
7550 return;
7551 }
7552
7553 AST_LIST_TRAVERSE(vars, var, entries) {
7554 ast_str_append(pbuf, 0, "ChanVariable(%s): %s=%s\r\n", ast_channel_name(chan), var->name, var->value);
7555 }
7556 ao2_ref(vars, -1);
7557 }
7558
7559 /* XXX see if can be moved inside the function */
7560 AST_THREADSTORAGE(manager_event_buf);
7561 #define MANAGER_EVENT_BUF_INITSIZE 256
7562
7563 static int __attribute__((format(printf, 9, 0))) __manager_event_sessions_va(
7564 struct ao2_container *sessions,
7565 int category,
7566 const char *event,
7567 int chancount,
7568 struct ast_channel **chans,
7569 const char *file,
7570 int line,
7571 const char *func,
7572 const char *fmt,
7573 va_list ap)
7574 {
7575 struct ast_str *auth = ast_str_alloca(MAX_AUTH_PERM_STRING);
7576 const char *cat_str;
7577 struct timeval now;
7578 struct ast_str *buf;
7579 int i;
7580 int event_name_hash;
7581
7582 if (!ast_strlen_zero(manager_disabledevents)) {
7583 if (ast_in_delimited_string(event, manager_disabledevents, ',')) {
7584 ast_debug(3, "AMI Event '%s' is globally disabled, skipping\n", event);
7585 /* Event is globally disabled */
7586 return -1;
7587 }
7588 }
7589
7590 buf = ast_str_thread_get(&manager_event_buf, MANAGER_EVENT_BUF_INITSIZE);
7591 if (!buf) {
7592 return -1;
7593 }
7594
7595 cat_str = authority_to_str(category, &auth);
7596 ast_str_set(&buf, 0,
7597 "Event: %s\r\n"
7598 "Privilege: %s\r\n",
7599 event, cat_str);
7600
7601 if (timestampevents) {
7602 now = ast_tvnow();
7603 ast_str_append(&buf, 0,
7604 "Timestamp: %ld.%06lu\r\n",
7605 (long)now.tv_sec, (unsigned long) now.tv_usec);
7606 }
7607 if (manager_debug) {
7608 static int seq;
7609
7610 ast_str_append(&buf, 0,
7611 "SequenceNumber: %d\r\n",
7612 ast_atomic_fetchadd_int(&seq, 1));
7613 ast_str_append(&buf, 0,
7614 "File: %s\r\n"
7615 "Line: %d\r\n"
7616 "Func: %s\r\n",
7617 file, line, func);
7618 }
7619 if (!ast_strlen_zero(ast_config_AST_SYSTEM_NAME)) {
7620 ast_str_append(&buf, 0,
7621 "SystemName: %s\r\n",
7622 ast_config_AST_SYSTEM_NAME);
7623 }
7624
7625 ast_str_append_va(&buf, 0, fmt, ap);
7626 for (i = 0; i < chancount; i++) {
7627 append_channel_vars(&buf, chans[i]);
7628 }
7629
7630 ast_str_append(&buf, 0, "\r\n");
7631
7632 event_name_hash = ast_str_hash(event);
7633
7634 append_event(ast_str_buffer(buf), event_name_hash, category);
7635
7636 /* Wake up any sleeping sessions */
7637 if (sessions) {
7638 struct ao2_iterator iter;
7639 struct mansession_session *session;
7640
7641 iter = ao2_iterator_init(sessions, 0);
7642 while ((session = ao2_iterator_next(&iter))) {
7643 ast_mutex_lock(&session->notify_lock);
7644 if (session->waiting_thread != AST_PTHREADT_NULL) {
7645 pthread_kill(session->waiting_thread, SIGURG);
7646 } else {
7647 /* We have an event to process, but the mansession is
7648 * not waiting for it. We still need to indicate that there
7649 * is an event waiting so that get_input processes the pending
7650 * event instead of polling.
7651 */
7652 session->pending_event = 1;
7653 }
7654 ast_mutex_unlock(&session->notify_lock);
7655 unref_mansession(session);
7656 }
7657 ao2_iterator_destroy(&iter);
7658 }
7659
7660 if (category != EVENT_FLAG_SHUTDOWN && !AST_RWLIST_EMPTY(&manager_hooks)) {
7661 struct manager_custom_hook *hook;
7662
7663 AST_RWLIST_RDLOCK(&manager_hooks);
7664 AST_RWLIST_TRAVERSE(&manager_hooks, hook, list) {
7665 hook->helper(category, event, ast_str_buffer(buf));
7666 }
7667 AST_RWLIST_UNLOCK(&manager_hooks);
7668 }
7669
7670 return 0;
7671 }
7672
7673 static int __attribute__((format(printf, 9, 0))) __manager_event_sessions(
7674 struct ao2_container *sessions,
7675 int category,
7676 const char *event,
7677 int chancount,
7678 struct ast_channel **chans,
7679 const char *file,
7680 int line,
7681 const char *func,
7682 const char *fmt,
7683 ...)
7684 {
7685 va_list ap;
7686 int res;
7687
7688 va_start(ap, fmt);
7689 res = __manager_event_sessions_va(sessions, category, event,
7690 chancount, chans, file, line, func, fmt, ap);
7691 va_end(ap);
7692 return res;
7693 }
7694
7695 int __ast_manager_event_multichan(int category, const char *event, int chancount,
7696 struct ast_channel **chans, const char *file, int line, const char *func,
7697 const char *fmt, ...)
7698 {
7699 struct ao2_container *sessions = ao2_global_obj_ref(mgr_sessions);
7700 va_list ap;
7701 int res;
7702
7703 if (!any_manager_listeners(sessions)) {
7704 /* Nobody is listening */
7705 ao2_cleanup(sessions);
7706 return 0;
7707 }
7708
7709 va_start(ap, fmt);
7710 res = __manager_event_sessions_va(sessions, category, event, chancount, chans,
7711 file, line, func, fmt, ap);
7712 va_end(ap);
7713 ao2_cleanup(sessions);
7714 return res;
7715 }
7716
7717 /*! \brief
7718 * support functions to register/unregister AMI action handlers,
7719 */
7720 int ast_manager_unregister(const char *action)
7721 {
7722 struct manager_action *cur;
7723
7724 AST_RWLIST_WRLOCK(&actions);
7725 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&actions, cur, list) {
7726 if (!strcasecmp(action, cur->action)) {
7727 AST_RWLIST_REMOVE_CURRENT(list);
7728 break;
7729 }
7730 }
7731 AST_RWLIST_TRAVERSE_SAFE_END;
7732 AST_RWLIST_UNLOCK(&actions);
7733
7734 if (cur) {
7735 /*
7736 * We have removed the action object from the container so we
7737 * are no longer in a hurry.
7738 */
7739 ao2_lock(cur);
7740 cur->registered = 0;
7741 ao2_unlock(cur);
7742
7743 ao2_t_ref(cur, -1, "action object removed from list");
7744 ast_verb(5, "Manager unregistered action %s\n", action);
7745 }
7746
7747 return 0;
7748 }
7749
7750 static int manager_state_cb(const char *context, const char *exten, struct ast_state_cb_info *info, void *data)
7751 {
7752 /* Notify managers of change */
7753 char hint[512];
7754
7755 hint[0] = '\0';
7756 ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten);
7757
7758 switch(info->reason) {
7759 case AST_HINT_UPDATE_DEVICE:
7760 manager_event(EVENT_FLAG_CALL, "ExtensionStatus",
7761 "Exten: %s\r\n"
7762 "Context: %s\r\n"
7763 "Hint: %s\r\n"
7764 "Status: %d\r\n"
7765 "StatusText: %s\r\n",
7766 exten,
7767 context,
7768 hint,
7769 info->exten_state,
7770 ast_extension_state2str(info->exten_state));
7771 break;
7772 case AST_HINT_UPDATE_PRESENCE:
7773 manager_event(EVENT_FLAG_CALL, "PresenceStatus",
7774 "Exten: %s\r\n"
7775 "Context: %s\r\n"
7776 "Hint: %s\r\n"
7777 "Status: %s\r\n"
7778 "Subtype: %s\r\n"
7779 "Message: %s\r\n",
7780 exten,
7781 context,
7782 hint,
7783 ast_presence_state2str(info->presence_state),
7784 info->presence_subtype,
7785 info->presence_message);
7786 break;
7787 }
7788 return 0;
7789 }
7790
7791 static int ast_manager_register_struct(struct manager_action *act)
7792 {
7793 struct manager_action *cur, *prev = NULL;
7794
7795 AST_RWLIST_WRLOCK(&actions);
7796 AST_RWLIST_TRAVERSE(&actions, cur, list) {
7797 int ret;
7798
7799 ret = strcasecmp(cur->action, act->action);
7800 if (ret == 0) {
7801 ast_log(LOG_WARNING, "Manager: Action '%s' already registered\n", act->action);
7802 AST_RWLIST_UNLOCK(&actions);
7803 return -1;
7804 }
7805 if (ret > 0) { /* Insert these alphabetically */
7806 break;
7807 }
7808 prev = cur;
7809 }
7810
7811 ao2_t_ref(act, +1, "action object added to list");
7812 act->registered = 1;
7813 if (prev) {
7814 AST_RWLIST_INSERT_AFTER(&actions, prev, act, list);
7815 } else {
7816 AST_RWLIST_INSERT_HEAD(&actions, act, list);
7817 }
7818
7819 ast_verb(5, "Manager registered action %s\n", act->action);
7820
7821 AST_RWLIST_UNLOCK(&actions);
7822
7823 return 0;
7824 }
7825
7826 /*!
7827 * \internal
7828 * \brief Destroy the registered AMI action object.
7829 *
7830 * \param obj Object to destroy.
7831 */
7832 static void action_destroy(void *obj)
7833 {
7834 struct manager_action *doomed = obj;
7835
7836 if (doomed->synopsis) {
7837 /* The string fields were initialized. */
7838 ast_string_field_free_memory(doomed);
7839 }
7840 ao2_cleanup(doomed->final_response);
7841 ao2_cleanup(doomed->list_responses);
7842 }
7843
7844 /*! \brief register a new command with manager, including online help. This is
7845 the preferred way to register a manager command */
7846 int ast_manager_register2(const char *action, int auth, int (*func)(struct mansession *s, const struct message *m), struct ast_module *module, const char *synopsis, const char *description)
7847 {
7848 struct manager_action *cur;
7849
7850 cur = ao2_t_alloc(sizeof(*cur), action_destroy, action);
7851 if (!cur) {
7852 return -1;
7853 }
7854 if (ast_string_field_init(cur, 128)) {
7855 ao2_t_ref(cur, -1, "action object creation failed");
7856 return -1;
7857 }
7858
7859 if (ast_string_field_init_extended(cur, since)) {
7860 ao2_t_ref(cur, -1, "action object creation failed");
7861 return -1;
7862 }
7863
7864 if (ast_string_field_init_extended(cur, provided_by)) {
7865 ao2_t_ref(cur, -1, "action object creation failed");
7866 return -1;
7867 }
7868
7869 cur->action = action;
7870 cur->authority = auth;
7871 cur->func = func;
7872 cur->module = module;
7873 #ifdef AST_XML_DOCS
7874 if (ast_strlen_zero(synopsis) && ast_strlen_zero(description)) {
7875 char *tmpxml;
7876
7877 tmpxml = ast_xmldoc_build_since("manager", action, NULL);
7878 ast_string_field_set(cur, since, tmpxml);
7879 ast_free(tmpxml);
7880
7881 tmpxml = ast_xmldoc_build_synopsis("manager", action, NULL);
7882 ast_string_field_set(cur, synopsis, tmpxml);
7883 ast_free(tmpxml);
7884
7885 tmpxml = ast_xmldoc_build_provided_by("manager", action, NULL);
7886 ast_string_field_set(cur, provided_by, tmpxml);
7887 ast_free(tmpxml);
7888
7889 tmpxml = ast_xmldoc_build_syntax("manager", action, NULL);
7890 ast_string_field_set(cur, syntax, tmpxml);
7891 ast_free(tmpxml);
7892
7893 tmpxml = ast_xmldoc_build_description("manager", action, NULL);
7894 ast_string_field_set(cur, description, tmpxml);
7895 ast_free(tmpxml);
7896
7897 tmpxml = ast_xmldoc_build_seealso("manager", action, NULL);
7898 ast_string_field_set(cur, seealso, tmpxml);
7899 ast_free(tmpxml);
7900
7901 tmpxml = ast_xmldoc_build_arguments("manager", action, NULL);
7902 ast_string_field_set(cur, arguments, tmpxml);
7903 ast_free(tmpxml);
7904
7905 cur->final_response = ast_xmldoc_build_final_response("manager", action, NULL);
7906 cur->list_responses = ast_xmldoc_build_list_responses("manager", action, NULL);
7907
7908 cur->docsrc = AST_XML_DOC;
7909 } else
7910 #endif
7911 {
7912 ast_string_field_set(cur, synopsis, synopsis);
7913 ast_string_field_set(cur, description, description);
7914 #ifdef AST_XML_DOCS
7915 cur->docsrc = AST_STATIC_DOC;
7916 #endif
7917 }
7918 if (ast_manager_register_struct(cur)) {
7919 ao2_t_ref(cur, -1, "action object registration failed");
7920 return -1;
7921 }
7922
7923 ao2_t_ref(cur, -1, "action object registration successful");
7924 return 0;
7925 }
7926 /*! @}
7927 END Doxygen group */
7928
7929 /*
7930 * The following are support functions for AMI-over-http.
7931 * The common entry point is generic_http_callback(),
7932 * which extracts HTTP header and URI fields and reformats
7933 * them into AMI messages, locates a proper session
7934 * (using the mansession_id Cookie or GET variable),
7935 * and calls process_message() as for regular AMI clients.
7936 * When done, the output (which goes to a temporary file)
7937 * is read back into a buffer and reformatted as desired,
7938 * then fed back to the client over the original socket.
7939 */
7940
7941 enum output_format {
7942 FORMAT_RAW,
7943 FORMAT_HTML,
7944 FORMAT_XML,
7945 };
7946
7947 static const char * const contenttype[] = {
7948 [FORMAT_RAW] = "plain",
7949 [FORMAT_HTML] = "html",
7950 [FORMAT_XML] = "xml",
7951 };
7952
7953 /*!
7954 * locate an http session in the list. The search key (ident) is
7955 * the value of the mansession_id cookie (0 is not valid and means
7956 * a session on the AMI socket).
7957 */
7958 static struct mansession_session *find_session(uint32_t ident, int incinuse)
7959 {
7960 struct ao2_container *sessions;
7961 struct mansession_session *session;
7962 struct ao2_iterator i;
7963
7964 if (ident == 0) {
7965 return NULL;
7966 }
7967
7968 sessions = ao2_global_obj_ref(mgr_sessions);
7969 if (!sessions) {
7970 return NULL;
7971 }
7972 i = ao2_iterator_init(sessions, 0);
7973 ao2_ref(sessions, -1);
7974 while ((session = ao2_iterator_next(&i))) {
7975 ao2_lock(session);
7976 if (session->managerid == ident && !session->needdestroy) {
7977 ast_atomic_fetchadd_int(&session->inuse, incinuse ? 1 : 0);
7978 break;
7979 }
7980 ao2_unlock(session);
7981 unref_mansession(session);
7982 }
7983 ao2_iterator_destroy(&i);
7984
7985 return session;
7986 }
7987
7988 /*!
7989 * locate an http session in the list.
7990 * The search keys (nonce) and (username) is value from received
7991 * "Authorization" http header.
7992 * As well as in find_session() function, the value of the nonce can't be zero.
7993 * (0 meansi, that the session used for AMI socket connection).
7994 * Flag (stale) is set, if client used valid, but old, nonce value.
7995 *
7996 */
7997 static struct mansession_session *find_session_by_nonce(const char *username, unsigned long nonce, int *stale)
7998 {
7999 struct mansession_session *session;
8000 struct ao2_container *sessions;
8001 struct ao2_iterator i;
8002
8003 if (nonce == 0 || username == NULL || stale == NULL) {
8004 return NULL;
8005 }
8006
8007 sessions = ao2_global_obj_ref(mgr_sessions);
8008 if (!sessions) {
8009 return NULL;
8010 }
8011 i = ao2_iterator_init(sessions, 0);
8012 ao2_ref(sessions, -1);
8013 while ((session = ao2_iterator_next(&i))) {
8014 ao2_lock(session);
8015 if (!strcasecmp(session->username, username) && session->managerid == nonce) {
8016 *stale = 0;
8017 break;
8018 } else if (!strcasecmp(session->username, username) && session->oldnonce == nonce) {
8019 *stale = 1;
8020 break;
8021 }
8022 ao2_unlock(session);
8023 unref_mansession(session);
8024 }
8025 ao2_iterator_destroy(&i);
8026
8027 return session;
8028 }
8029
8030 int astman_is_authed(uint32_t ident)
8031 {
8032 int authed;
8033 struct mansession_session *session;
8034
8035 if (!(session = find_session(ident, 0)))
8036 return 0;
8037
8038 authed = (session->authenticated != 0);
8039
8040 ao2_unlock(session);
8041 unref_mansession(session);
8042
8043 return authed;
8044 }
8045
8046 int astman_verify_session_readpermissions(uint32_t ident, int perm)
8047 {
8048 int result = 0;
8049 struct mansession_session *session;
8050 struct ao2_container *sessions;
8051 struct ao2_iterator i;
8052
8053 if (ident == 0) {
8054 return 0;
8055 }
8056
8057 sessions = ao2_global_obj_ref(mgr_sessions);
8058 if (!sessions) {
8059 return 0;
8060 }
8061 i = ao2_iterator_init(sessions, 0);
8062 ao2_ref(sessions, -1);
8063 while ((session = ao2_iterator_next(&i))) {
8064 ao2_lock(session);
8065 if ((session->managerid == ident) && (session->readperm & perm)) {
8066 result = 1;
8067 ao2_unlock(session);
8068 unref_mansession(session);
8069 break;
8070 }
8071 ao2_unlock(session);
8072 unref_mansession(session);
8073 }
8074 ao2_iterator_destroy(&i);
8075
8076 return result;
8077 }
8078
8079 int astman_verify_session_writepermissions(uint32_t ident, int perm)
8080 {
8081 int result = 0;
8082 struct mansession_session *session;
8083 struct ao2_container *sessions;
8084 struct ao2_iterator i;
8085
8086 if (ident == 0) {
8087 return 0;
8088 }
8089
8090 sessions = ao2_global_obj_ref(mgr_sessions);
8091 if (!sessions) {
8092 return 0;
8093 }
8094 i = ao2_iterator_init(sessions, 0);
8095 ao2_ref(sessions, -1);
8096 while ((session = ao2_iterator_next(&i))) {
8097 ao2_lock(session);
8098 if ((session->managerid == ident) && (session->writeperm & perm)) {
8099 result = 1;
8100 ao2_unlock(session);
8101 unref_mansession(session);
8102 break;
8103 }
8104 ao2_unlock(session);
8105 unref_mansession(session);
8106 }
8107 ao2_iterator_destroy(&i);
8108
8109 return result;
8110 }
8111
8112 /*
8113 * convert to xml with various conversion:
8114 * mode & 1 -> lowercase;
8115 * mode & 2 -> replace non-alphanumeric chars with underscore
8116 */
8117 static void xml_copy_escape(struct ast_str **out, const char *src, int mode)
8118 {
8119 /* store in a local buffer to avoid calling ast_str_append too often */
8120 char buf[256];
8121 char *dst = buf;
8122 const char *save = src;
8123 int space = sizeof(buf);
8124 /* repeat until done and nothing to flush */
8125 for ( ; *src || dst != buf ; src++) {
8126 if (*src == '\0' || space < 10) { /* flush */
8127 *dst++ = '\0';
8128 ast_str_append(out, 0, "%s", buf);
8129 dst = buf;
8130 space = sizeof(buf);
8131 if (*src == '\0') {
8132 break;
8133 }
8134 }
8135
8136 if (mode & 2) {
8137 if (save == src && isdigit(*src)) {
8138 /* The first character of an XML attribute cannot be a digit */
8139 *dst++ = '_';
8140 *dst++ = *src;
8141 space -= 2;
8142 continue;
8143 } else if (!isalnum(*src)) {
8144 /* Replace non-alphanumeric with an underscore */
8145 *dst++ = '_';
8146 space--;
8147 continue;
8148 }
8149 }
8150 switch (*src) {
8151 case '<':
8152 strcpy(dst, "&lt;");
8153 dst += 4;
8154 space -= 4;
8155 break;
8156 case '>':
8157 strcpy(dst, "&gt;");
8158 dst += 4;
8159 space -= 4;
8160 break;
8161 case '\"':
8162 strcpy(dst, "&quot;");
8163 dst += 6;
8164 space -= 6;
8165 break;
8166 case '\'':
8167 strcpy(dst, "&apos;");
8168 dst += 6;
8169 space -= 6;
8170 break;
8171 case '&':
8172 strcpy(dst, "&amp;");
8173 dst += 5;
8174 space -= 5;
8175 break;
8176
8177 default:
8178 *dst++ = mode ? tolower(*src) : *src;
8179 space--;
8180 }
8181 }
8182 }
8183
8184 struct variable_count {
8185 char *varname;
8186 int count;
8187 };
8188
8189 static int variable_count_hash_fn(const void *vvc, const int flags)
8190 {
8191 const struct variable_count *vc = vvc;
8192
8193 return ast_str_hash(vc->varname);
8194 }
8195
8196 static int variable_count_cmp_fn(void *obj, void *vstr, int flags)
8197 {
8198 /* Due to the simplicity of struct variable_count, it makes no difference
8199 * if you pass in objects or strings, the same operation applies. This is
8200 * due to the fact that the hash occurs on the first element, which means
8201 * the address of both the struct and the string are exactly the same. */
8202 struct variable_count *vc = obj;
8203 char *str = vstr;
8204 return !strcmp(vc->varname, str) ? CMP_MATCH | CMP_STOP : 0;
8205 }
8206
8207 /*! \brief Convert the input into XML or HTML.
8208 * The input is supposed to be a sequence of lines of the form
8209 * Name: value
8210 * optionally followed by a blob of unformatted text.
8211 * A blank line is a section separator. Basically, this is a
8212 * mixture of the format of Manager Interface and CLI commands.
8213 * The unformatted text is considered as a single value of a field
8214 * named 'Opaque-data'.
8215 *
8216 * At the moment the output format is the following (but it may
8217 * change depending on future requirements so don't count too
8218 * much on it when writing applications):
8219 *
8220 * General: the unformatted text is used as a value of
8221 * XML output: to be completed
8222 *
8223 * \verbatim
8224 * Each section is within <response type="object" id="xxx">
8225 * where xxx is taken from ajaxdest variable or defaults to unknown
8226 * Each row is reported as an attribute Name="value" of an XML
8227 * entity named from the variable ajaxobjtype, default to "generic"
8228 * \endverbatim
8229 *
8230 * HTML output:
8231 * each Name-value pair is output as a single row of a two-column table.
8232 * Sections (blank lines in the input) are separated by a <HR>
8233 *
8234 */
8235 static void xml_translate(struct ast_str **out, char *in, struct ast_variable *get_vars, enum output_format format)
8236 {
8237 struct ast_variable *v;
8238 const char *dest = NULL;
8239 char *var, *val;
8240 const char *objtype = NULL;
8241 int in_data = 0; /* parsing data */
8242 int inobj = 0;
8243 int xml = (format == FORMAT_XML);
8244 struct variable_count *vc = NULL;
8245 struct ao2_container *vco = NULL;
8246
8247 if (xml) {
8248 /* dest and objtype need only for XML format */
8249 for (v = get_vars; v; v = v->next) {
8250 if (!strcasecmp(v->name, "ajaxdest")) {
8251 dest = v->value;
8252 } else if (!strcasecmp(v->name, "ajaxobjtype")) {
8253 objtype = v->value;
8254 }
8255 }
8256 if (ast_strlen_zero(dest)) {
8257 dest = "unknown";
8258 }
8259 if (ast_strlen_zero(objtype)) {
8260 objtype = "generic";
8261 }
8262 }
8263
8264 /* we want to stop when we find an empty line */
8265 while (in && *in) {
8266 val = strsep(&in, "\r\n"); /* mark start and end of line */
8267 if (in && *in == '\n') { /* remove trailing \n if any */
8268 in++;
8269 }
8270 ast_trim_blanks(val);
8271 ast_debug(5, "inobj %d in_data %d line <%s>\n", inobj, in_data, val);
8272 if (ast_strlen_zero(val)) {
8273 /* empty line */
8274 if (in_data) {
8275 /* close data in Opaque mode */
8276 ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
8277 in_data = 0;
8278 }
8279
8280 if (inobj) {
8281 /* close block */
8282 ast_str_append(out, 0, xml ? " /></response>\n" :
8283 "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
8284 inobj = 0;
8285 ao2_ref(vco, -1);
8286 vco = NULL;
8287 }
8288 continue;
8289 }
8290
8291 if (!inobj) {
8292 /* start new block */
8293 if (xml) {
8294 ast_str_append(out, 0, "<response type='object' id='%s'><%s", dest, objtype);
8295 }
8296 vco = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 37,
8297 variable_count_hash_fn, NULL, variable_count_cmp_fn);
8298 inobj = 1;
8299 }
8300
8301 if (in_data) {
8302 /* Process data field in Opaque mode. This is a
8303 * followup, so we re-add line feeds. */
8304 ast_str_append(out, 0, xml ? "\n" : "<br>\n");
8305 xml_copy_escape(out, val, 0); /* data field */
8306 continue;
8307 }
8308
8309 /* We expect "Name: value" line here */
8310 var = strsep(&val, ":");
8311 if (val) {
8312 /* found the field name */
8313 val = ast_skip_blanks(val);
8314 ast_trim_blanks(var);
8315 } else {
8316 /* field name not found, switch to opaque mode */
8317 val = var;
8318 var = "Opaque-data";
8319 in_data = 1;
8320 }
8321
8322
8323 ast_str_append(out, 0, xml ? " " : "<tr><td>");
8324 if ((vc = ao2_find(vco, var, 0))) {
8325 vc->count++;
8326 } else {
8327 /* Create a new entry for this one */
8328 vc = ao2_alloc(sizeof(*vc), NULL);
8329 vc->varname = var;
8330 vc->count = 1;
8331 ao2_link(vco, vc);
8332 }
8333
8334 xml_copy_escape(out, var, xml ? 1 | 2 : 0); /* data name */
8335 if (vc->count > 1) {
8336 ast_str_append(out, 0, "-%d", vc->count);
8337 }
8338 ao2_ref(vc, -1);
8339 ast_str_append(out, 0, xml ? "='" : "</td><td>");
8340 xml_copy_escape(out, val, 0); /* data field */
8341 if (!in_data || !*in) {
8342 ast_str_append(out, 0, xml ? "'" : "</td></tr>\n");
8343 }
8344 }
8345
8346 if (inobj) {
8347 ast_str_append(out, 0, xml ? " /></response>\n" :
8348 "<tr><td colspan=\"2\"><hr></td></tr>\r\n");
8349 ao2_ref(vco, -1);
8350 }
8351 }
8352
8353 static void close_mansession_file(struct mansession *s)
8354 {
8355 if (s->stream) {
8356 ast_iostream_close(s->stream);
8357 s->stream = NULL;
8358 } else {
8359 ast_log(LOG_ERROR, "Attempted to close file/file descriptor on mansession without a valid file or file descriptor.\n");
8360 }
8361 }
8362
8363 static void process_output(struct mansession *s, struct ast_str **out, struct ast_variable *params, enum output_format format)
8364 {
8365 char *buf;
8366 off_t l;
8367 int fd;
8368
8369 if (!s->stream)
8370 return;
8371
8372 /* Ensure buffer is NULL-terminated */
8373 ast_iostream_write(s->stream, "", 1);
8374
8375 fd = ast_iostream_get_fd(s->stream);
8376
8377 l = lseek(fd, 0, SEEK_CUR);
8378 if (l > 0) {
8379 if (MAP_FAILED == (buf = mmap(NULL, l, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0))) {
8380 ast_log(LOG_WARNING, "mmap failed. Manager output was not processed\n");
8381 } else {
8382 if (format == FORMAT_XML || format == FORMAT_HTML) {
8383 xml_translate(out, buf, params, format);
8384 } else {
8385 ast_str_append(out, 0, "%s", buf);
8386 }
8387 munmap(buf, l);
8388 }
8389 } else if (format == FORMAT_XML || format == FORMAT_HTML) {
8390 xml_translate(out, "", params, format);
8391 }
8392
8393 close_mansession_file(s);
8394 }
8395
8396 static int generic_http_callback(struct ast_tcptls_session_instance *ser,
8397 enum ast_http_method method,
8398 enum output_format format,
8399 const struct ast_sockaddr *remote_address, const char *uri,
8400 struct ast_variable *get_params,
8401 struct ast_variable *headers)
8402 {
8403 struct mansession s = { .session = NULL, .tcptls_session = ser };
8404 struct mansession_session *session = NULL;
8405 uint32_t ident;
8406 int fd;
8407 int blastaway = 0;
8408 struct ast_variable *params = get_params;
8409 char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
8410 struct ast_str *http_header = NULL, *out = NULL;
8411 struct message m = { 0 };
8412
8413 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
8414 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
8415 return 0;
8416 }
8417
8418 ident = ast_http_manid_from_vars(headers);
8419
8420 if (!(session = find_session(ident, 1))) {
8421
8422 /**/
8423 /* Create new session.
8424 * While it is not in the list we don't need any locking
8425 */
8426 if (!(session = build_mansession(remote_address))) {
8427 ast_http_request_close_on_completion(ser);
8428 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
8429 return 0;
8430 }
8431 ao2_lock(session);
8432 session->send_events = 0;
8433 session->inuse = 1;
8434 /*!
8435 * \note There is approximately a 1 in 1.8E19 chance that the following
8436 * calculation will produce 0, which is an invalid ID, but due to the
8437 * properties of the rand() function (and the constancy of s), that
8438 * won't happen twice in a row.
8439 */
8440 while ((session->managerid = ast_random() ^ (unsigned long) session) == 0) {
8441 }
8442 session->last_ev = grab_last();
8443 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
8444 }
8445 ao2_unlock(session);
8446
8447 http_header = ast_str_create(128);
8448 out = ast_str_create(2048);
8449
8450 ast_mutex_init(&s.lock);
8451
8452 if (http_header == NULL || out == NULL) {
8453 ast_http_request_close_on_completion(ser);
8454 ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)");
8455 goto generic_callback_out;
8456 }
8457
8458 s.session = session;
8459 fd = mkstemp(template); /* create a temporary file for command output */
8460 unlink(template);
8461 if (fd <= -1) {
8462 ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)");
8463 goto generic_callback_out;
8464 }
8465 s.stream = ast_iostream_from_fd(&fd);
8466 if (!s.stream) {
8467 ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
8468 ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)");
8469 close(fd);
8470 goto generic_callback_out;
8471 }
8472
8473 if (method == AST_HTTP_POST) {
8474 params = ast_http_get_post_vars(ser, headers);
8475 if (!params) {
8476 switch (errno) {
8477 case EFBIG:
8478 ast_http_error(ser, 413, "Request Entity Too Large", "Body too large");
8479 close_mansession_file(&s);
8480 goto generic_callback_out;
8481 case ENOMEM:
8482 ast_http_request_close_on_completion(ser);
8483 ast_http_error(ser, 500, "Server Error", "Out of memory");
8484 close_mansession_file(&s);
8485 goto generic_callback_out;
8486 case EIO:
8487 ast_http_error(ser, 400, "Bad Request", "Error parsing request body");
8488 close_mansession_file(&s);
8489 goto generic_callback_out;
8490 }
8491 }
8492 }
8493
8494 astman_append_headers(&m, params);
8495
8496 if (process_message(&s, &m)) {
8497 if (session->authenticated) {
8498 if (manager_displayconnects(session)) {
8499 ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
8500 }
8501 } else {
8502 if (displayconnects) {
8503 ast_verb(2, "HTTP Connect attempt from '%s' unable to authenticate\n", ast_sockaddr_stringify_addr(&session->addr));
8504 }
8505 }
8506 session->needdestroy = 1;
8507 }
8508
8509 astman_free_headers(&m);
8510
8511 ast_str_append(&http_header, 0,
8512 "Content-type: text/%s\r\n"
8513 "Set-Cookie: mansession_id=\"%08x\"; Version=1; Max-Age=%d\r\n"
8514 "Pragma: SuppressEvents\r\n",
8515 contenttype[format],
8516 session->managerid, httptimeout);
8517
8518 if (format == FORMAT_XML) {
8519 ast_str_append(&out, 0, "<ajax-response>\n");
8520 } else if (format == FORMAT_HTML) {
8521 /*
8522 * When handling AMI-over-HTTP in HTML format, we provide a simple form for
8523 * debugging purposes. This HTML code should not be here, we
8524 * should read from some config file...
8525 */
8526
8527 #define ROW_FMT "<tr><td colspan=\"2\" bgcolor=\"#f1f1ff\">%s</td></tr>\r\n"
8528 #define TEST_STRING \
8529 "<form action=\"manager\" method=\"post\">\n\
8530 Action: <select name=\"action\">\n\
8531 <option value=\"\">-----&gt;</option>\n\
8532 <option value=\"login\">login</option>\n\
8533 <option value=\"command\">Command</option>\n\
8534 <option value=\"waitevent\">waitevent</option>\n\
8535 <option value=\"listcommands\">listcommands</option>\n\
8536 </select>\n\
8537 or <input name=\"action\"><br/>\n\
8538 CLI Command <input name=\"command\"><br>\n\
8539 user <input name=\"username\"> pass <input type=\"password\" name=\"secret\"><br>\n\
8540 <input type=\"submit\">\n</form>\n"
8541
8542 ast_str_append(&out, 0, "<title>Asterisk&trade; Manager Interface</title>");
8543 ast_str_append(&out, 0, "<body bgcolor=\"#ffffff\"><table align=center bgcolor=\"#f1f1f1\" width=\"500\">\r\n");
8544 ast_str_append(&out, 0, ROW_FMT, "<h1>Manager Tester</h1>");
8545 ast_str_append(&out, 0, ROW_FMT, TEST_STRING);
8546 }
8547
8548 process_output(&s, &out, params, format);
8549
8550 if (format == FORMAT_XML) {
8551 ast_str_append(&out, 0, "</ajax-response>\n");
8552 } else if (format == FORMAT_HTML) {
8553 ast_str_append(&out, 0, "</table></body>\r\n");
8554 }
8555
8556 ao2_lock(session);
8557 /* Reset HTTP timeout. If we're not authenticated, keep it extremely short */
8558 session->sessiontimeout = time(NULL) + ((session->authenticated || httptimeout < 5) ? httptimeout : 5);
8559
8560 if (session->needdestroy) {
8561 if (session->inuse == 1) {
8562 ast_debug(1, "Need destroy, doing it now!\n");
8563 blastaway = 1;
8564 } else {
8565 ast_debug(1, "Need destroy, but can't do it yet!\n");
8566 ast_mutex_lock(&session->notify_lock);
8567 if (session->waiting_thread != AST_PTHREADT_NULL) {
8568 pthread_kill(session->waiting_thread, SIGURG);
8569 }
8570 ast_mutex_unlock(&session->notify_lock);
8571 session->inuse--;
8572 }
8573 } else {
8574 session->inuse--;
8575 }
8576 ao2_unlock(session);
8577
8578 ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
8579 http_header = NULL;
8580 out = NULL;
8581
8582 generic_callback_out:
8583 ast_mutex_destroy(&s.lock);
8584
8585 /* Clear resource */
8586
8587 if (method == AST_HTTP_POST && params) {
8588 ast_variables_destroy(params);
8589 }
8590 ast_free(http_header);
8591 ast_free(out);
8592
8593 if (session) {
8594 if (blastaway) {
8595 session_destroy(session);
8596 } else {
8597 if (session->stream) {
8598 ast_iostream_close(session->stream);
8599 session->stream = NULL;
8600 }
8601 unref_mansession(session);
8602 }
8603 }
8604
8605 return 0;
8606 }
8607
8608 static int auth_http_callback(struct ast_tcptls_session_instance *ser,
8609 enum ast_http_method method,
8610 enum output_format format,
8611 const struct ast_sockaddr *remote_address, const char *uri,
8612 struct ast_variable *get_params,
8613 struct ast_variable *headers)
8614 {
8615 struct mansession_session *session = NULL;
8616 struct mansession s = { .session = NULL, .tcptls_session = ser };
8617 struct ast_variable *v, *params = get_params;
8618 char template[] = "/tmp/ast-http-XXXXXX"; /* template for temporary file */
8619 struct ast_str *http_header = NULL, *out = NULL;
8620 size_t result_size;
8621 struct message m = { 0 };
8622 int fd;
8623
8624 time_t time_now = time(NULL);
8625 unsigned long nonce = 0, nc;
8626 struct ast_http_digest d = { NULL, };
8627 struct ast_manager_user *user = NULL;
8628 int stale = 0;
8629 char resp_hash[256]="";
8630 /* Cache for user data */
8631 char u_username[80];
8632 int u_readperm;
8633 int u_writeperm;
8634 int u_writetimeout;
8635 int u_displayconnects;
8636
8637 if (method != AST_HTTP_GET && method != AST_HTTP_HEAD && method != AST_HTTP_POST) {
8638 ast_http_error(ser, 501, "Not Implemented", "Attempt to use unimplemented / unsupported method");
8639 return 0;
8640 }
8641
8642 /* Find "Authorization: " header */
8643 for (v = headers; v; v = v->next) {
8644 if (!strcasecmp(v->name, "Authorization")) {
8645 break;
8646 }
8647 }
8648
8649 if (!v || ast_strlen_zero(v->value)) {
8650 goto out_401; /* Authorization Header not present - send auth request */
8651 }
8652
8653 /* Digest found - parse */
8654 if (ast_string_field_init(&d, 128)) {
8655 ast_http_request_close_on_completion(ser);
8656 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
8657 return 0;
8658 }
8659
8660 if (ast_parse_digest(v->value, &d, 0, 1)) {
8661 /* Error in Digest - send new one */
8662 nonce = 0;
8663 goto out_401;
8664 }
8665 if (sscanf(d.nonce, "%30lx", &nonce) != 1) {
8666 ast_log(LOG_WARNING, "Received incorrect nonce in Digest <%s>\n", d.nonce);
8667 nonce = 0;
8668 goto out_401;
8669 }
8670
8671 AST_RWLIST_WRLOCK(&users);
8672 user = get_manager_by_name_locked(d.username);
8673 if(!user) {
8674 AST_RWLIST_UNLOCK(&users);
8675 ast_log(LOG_NOTICE, "%s tried to authenticate with nonexistent user '%s'\n", ast_sockaddr_stringify_addr(remote_address), d.username);
8676 nonce = 0;
8677 goto out_401;
8678 }
8679
8680 /* --- We have User for this auth, now check ACL */
8681 if (user->acl && !ast_apply_acl(user->acl, remote_address, "Manager User ACL:")) {
8682 AST_RWLIST_UNLOCK(&users);
8683 ast_log(LOG_NOTICE, "%s failed to pass IP ACL as '%s'\n", ast_sockaddr_stringify_addr(remote_address), d.username);
8684 ast_http_request_close_on_completion(ser);
8685 ast_http_error(ser, 403, "Permission denied", "Permission denied");
8686 return 0;
8687 }
8688
8689 /* --- We have auth, so check it */
8690
8691 /* compute the expected response to compare with what we received */
8692 {
8693 char *a2;
8694 /* ast_md5_hash outputs 32 characters plus NULL terminator. */
8695 char a2_hash[33];
8696 char resp[256];
8697
8698 /* XXX Now request method are hardcoded in A2 */
8699 if (ast_asprintf(&a2, "%s:%s", ast_get_http_method(method), d.uri) < 0) {
8700 AST_RWLIST_UNLOCK(&users);
8701 ast_http_request_close_on_completion(ser);
8702 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
8703 return 0;
8704 }
8705
8706 ast_md5_hash(a2_hash, a2);
8707 ast_free(a2);
8708
8709 if (d.qop) {
8710 /* RFC 2617 */
8711 snprintf(resp, sizeof(resp), "%s:%08lx:%s:%s:auth:%s", user->a1_hash, nonce, d.nc, d.cnonce, a2_hash);
8712 } else {
8713 /* RFC 2069 */
8714 snprintf(resp, sizeof(resp), "%s:%08lx:%s", user->a1_hash, nonce, a2_hash);
8715 }
8716 ast_md5_hash(resp_hash, resp);
8717 }
8718
8719 if (strncasecmp(d.response, resp_hash, strlen(resp_hash))) {
8720 /* Something was wrong, so give the client to try with a new challenge */
8721 AST_RWLIST_UNLOCK(&users);
8722 nonce = 0;
8723 goto out_401;
8724 }
8725
8726 /*
8727 * User are pass Digest authentication.
8728 * Now, cache the user data and unlock user list.
8729 */
8730 ast_copy_string(u_username, user->username, sizeof(u_username));
8731 u_readperm = user->readperm;
8732 u_writeperm = user->writeperm;
8733 u_displayconnects = user->displayconnects;
8734 u_writetimeout = user->writetimeout;
8735 AST_RWLIST_UNLOCK(&users);
8736
8737 if (!(session = find_session_by_nonce(d.username, nonce, &stale))) {
8738 /*
8739 * Create new session.
8740 * While it is not in the list we don't need any locking
8741 */
8742 if (!(session = build_mansession(remote_address))) {
8743 ast_http_request_close_on_completion(ser);
8744 ast_http_error(ser, 500, "Server Error", "Internal Server Error (out of memory)");
8745 return 0;
8746 }
8747 ao2_lock(session);
8748
8749 ast_copy_string(session->username, u_username, sizeof(session->username));
8750 session->managerid = nonce;
8751 session->last_ev = grab_last();
8752 AST_LIST_HEAD_INIT_NOLOCK(&session->datastores);
8753
8754 session->readperm = u_readperm;
8755 session->writeperm = u_writeperm;
8756 session->writetimeout = u_writetimeout;
8757
8758 if (u_displayconnects) {
8759 ast_verb(2, "HTTP Manager '%s' logged in from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
8760 }
8761 session->noncetime = session->sessionstart = time_now;
8762 session->authenticated = 1;
8763 } else if (stale) {
8764 /*
8765 * Session found, but nonce is stale.
8766 *
8767 * This could be because an old request (w/old nonce) arrived.
8768 *
8769 * This may be as the result of http proxy usage (separate delay or
8770 * multipath) or in a situation where a page was refreshed too quickly
8771 * (seen in Firefox).
8772 *
8773 * In this situation, we repeat the 401 auth with the current nonce
8774 * value.
8775 */
8776 nonce = session->managerid;
8777 ao2_unlock(session);
8778 stale = 1;
8779 goto out_401;
8780 } else {
8781 sscanf(d.nc, "%30lx", &nc);
8782 if (session->nc >= nc || ((time_now - session->noncetime) > 62) ) {
8783 /*
8784 * Nonce time expired (> 2 minutes) or something wrong with nonce
8785 * counter.
8786 *
8787 * Create new nonce key and resend Digest auth request. Old nonce
8788 * is saved for stale checking...
8789 */
8790 session->nc = 0; /* Reset nonce counter */
8791 session->oldnonce = session->managerid;
8792 nonce = session->managerid = ast_random();
8793 session->noncetime = time_now;
8794 ao2_unlock(session);
8795 stale = 1;
8796 goto out_401;
8797 } else {
8798 session->nc = nc; /* All OK, save nonce counter */
8799 }
8800 }
8801
8802
8803 /* Reset session timeout. */
8804 session->sessiontimeout = time(NULL) + (httptimeout > 5 ? httptimeout : 5);
8805 ao2_unlock(session);
8806
8807 ast_mutex_init(&s.lock);
8808 s.session = session;
8809 fd = mkstemp(template); /* create a temporary file for command output */
8810 unlink(template);
8811 if (fd <= -1) {
8812 ast_http_error(ser, 500, "Server Error", "Internal Server Error (mkstemp failed)");
8813 goto auth_callback_out;
8814 }
8815 s.stream = ast_iostream_from_fd(&fd);
8816 if (!s.stream) {
8817 ast_log(LOG_WARNING, "HTTP Manager, fdopen failed: %s!\n", strerror(errno));
8818 ast_http_error(ser, 500, "Server Error", "Internal Server Error (fdopen failed)");
8819 close(fd);
8820 goto auth_callback_out;
8821 }
8822
8823 if (method == AST_HTTP_POST) {
8824 params = ast_http_get_post_vars(ser, headers);
8825 if (!params) {
8826 switch (errno) {
8827 case EFBIG:
8828 ast_http_error(ser, 413, "Request Entity Too Large", "Body too large");
8829 close_mansession_file(&s);
8830 goto auth_callback_out;
8831 case ENOMEM:
8832 ast_http_request_close_on_completion(ser);
8833 ast_http_error(ser, 500, "Server Error", "Out of memory");
8834 close_mansession_file(&s);
8835 goto auth_callback_out;
8836 case EIO:
8837 ast_http_error(ser, 400, "Bad Request", "Error parsing request body");
8838 close_mansession_file(&s);
8839 goto auth_callback_out;
8840 }
8841 }
8842 }
8843
8844 astman_append_headers(&m, params);
8845
8846 if (process_message(&s, &m)) {
8847 if (u_displayconnects) {
8848 ast_verb(2, "HTTP Manager '%s' logged off from %s\n", session->username, ast_sockaddr_stringify_addr(&session->addr));
8849 }
8850
8851 session->needdestroy = 1;
8852 }
8853
8854 astman_free_headers(&m);
8855
8856 result_size = lseek(ast_iostream_get_fd(s.stream), 0, SEEK_CUR); /* Calculate approx. size of result */
8857
8858 http_header = ast_str_create(80);
8859 out = ast_str_create(result_size * 2 + 512);
8860 if (http_header == NULL || out == NULL) {
8861 ast_http_request_close_on_completion(ser);
8862 ast_http_error(ser, 500, "Server Error", "Internal Server Error (ast_str_create() out of memory)");
8863 close_mansession_file(&s);
8864 goto auth_callback_out;
8865 }
8866
8867 ast_str_append(&http_header, 0, "Content-type: text/%s\r\n", contenttype[format]);
8868
8869 if (format == FORMAT_XML) {
8870 ast_str_append(&out, 0, "<ajax-response>\n");
8871 } else if (format == FORMAT_HTML) {
8872 ast_str_append(&out, 0,
8873 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n"
8874 "<html><head>\r\n"
8875 "<title>Asterisk&trade; Manager Interface</title>\r\n"
8876 "</head><body style=\"background-color: #ffffff;\">\r\n"
8877 "<form method=\"POST\">\r\n"
8878 "<table align=\"center\" style=\"background-color: #f1f1f1;\" width=\"500\">\r\n"
8879 "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\"><h1>Manager Tester</h1></th></tr>\r\n"
8880 "<tr><th colspan=\"2\" style=\"background-color: #f1f1ff;\">Action: <input name=\"action\" /> Cmd: <input name=\"command\" /><br>"
8881 "<input type=\"submit\" value=\"Send request\" /></th></tr>\r\n");
8882 }
8883
8884 process_output(&s, &out, params, format);
8885
8886 if (format == FORMAT_XML) {
8887 ast_str_append(&out, 0, "</ajax-response>\n");
8888 } else if (format == FORMAT_HTML) {
8889 ast_str_append(&out, 0, "</table></form></body></html>\r\n");
8890 }
8891
8892 ast_http_send(ser, method, 200, NULL, http_header, out, 0, 0);
8893 http_header = NULL;
8894 out = NULL;
8895
8896 auth_callback_out:
8897 ast_mutex_destroy(&s.lock);
8898
8899 /* Clear resources and unlock manager session */
8900 if (method == AST_HTTP_POST && params) {
8901 ast_variables_destroy(params);
8902 }
8903
8904 ast_free(http_header);
8905 ast_free(out);
8906
8907 ao2_lock(session);
8908 if (session->stream) {
8909 ast_iostream_close(session->stream);
8910 session->stream = NULL;
8911 }
8912 ao2_unlock(session);
8913
8914 if (session->needdestroy) {
8915 ast_debug(1, "Need destroy, doing it now!\n");
8916 session_destroy(session);
8917 }
8918 ast_string_field_free_memory(&d);
8919 return 0;
8920
8921 out_401:
8922 if (!nonce) {
8923 nonce = ast_random();
8924 }
8925
8926 ast_http_auth(ser, global_realm, nonce, nonce, stale, NULL);
8927 ast_string_field_free_memory(&d);
8928 return 0;
8929 }
8930
8931 static int manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
8932 {
8933 int retval;
8934 struct ast_sockaddr ser_remote_address_tmp;
8935
8936 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
8937 retval = generic_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
8938 ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
8939 return retval;
8940 }
8941
8942 static int mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
8943 {
8944 int retval;
8945 struct ast_sockaddr ser_remote_address_tmp;
8946
8947 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
8948 retval = generic_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
8949 ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
8950 return retval;
8951 }
8952
8953 static int rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
8954 {
8955 int retval;
8956 struct ast_sockaddr ser_remote_address_tmp;
8957
8958 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
8959 retval = generic_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
8960 ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
8961 return retval;
8962 }
8963
8964 static struct ast_http_uri rawmanuri = {
8965 .description = "Raw HTTP Manager Event Interface",
8966 .uri = "rawman",
8967 .callback = rawman_http_callback,
8968 .data = NULL,
8969 .key = __FILE__,
8970 };
8971
8972 static struct ast_http_uri manageruri = {
8973 .description = "HTML Manager Event Interface",
8974 .uri = "manager",
8975 .callback = manager_http_callback,
8976 .data = NULL,
8977 .key = __FILE__,
8978 };
8979
8980 static struct ast_http_uri managerxmluri = {
8981 .description = "XML Manager Event Interface",
8982 .uri = "mxml",
8983 .callback = mxml_http_callback,
8984 .data = NULL,
8985 .key = __FILE__,
8986 };
8987
8988
8989 /* Callback with Digest authentication */
8990 static int auth_manager_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
8991 {
8992 int retval;
8993 struct ast_sockaddr ser_remote_address_tmp;
8994
8995 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
8996 retval = auth_http_callback(ser, method, FORMAT_HTML, &ser_remote_address_tmp, uri, get_params, headers);
8997 ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
8998 return retval;
8999 }
9000
9001 static int auth_mxml_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
9002 {
9003 int retval;
9004 struct ast_sockaddr ser_remote_address_tmp;
9005
9006 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
9007 retval = auth_http_callback(ser, method, FORMAT_XML, &ser_remote_address_tmp, uri, get_params, headers);
9008 ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
9009 return retval;
9010 }
9011
9012 static int auth_rawman_http_callback(struct ast_tcptls_session_instance *ser, const struct ast_http_uri *urih, const char *uri, enum ast_http_method method, struct ast_variable *get_params, struct ast_variable *headers)
9013 {
9014 int retval;
9015 struct ast_sockaddr ser_remote_address_tmp;
9016
9017 ast_sockaddr_copy(&ser_remote_address_tmp, &ser->remote_address);
9018 retval = auth_http_callback(ser, method, FORMAT_RAW, &ser_remote_address_tmp, uri, get_params, headers);
9019 ast_sockaddr_copy(&ser->remote_address, &ser_remote_address_tmp);
9020 return retval;
9021 }
9022
9023 static struct ast_http_uri arawmanuri = {
9024 .description = "Raw HTTP Manager Event Interface w/Digest authentication",
9025 .uri = "arawman",
9026 .has_subtree = 0,
9027 .callback = auth_rawman_http_callback,
9028 .data = NULL,
9029 .key = __FILE__,
9030 };
9031
9032 static struct ast_http_uri amanageruri = {
9033 .description = "HTML Manager Event Interface w/Digest authentication",
9034 .uri = "amanager",
9035 .has_subtree = 0,
9036 .callback = auth_manager_http_callback,
9037 .data = NULL,
9038 .key = __FILE__,
9039 };
9040
9041 static struct ast_http_uri amanagerxmluri = {
9042 .description = "XML Manager Event Interface w/Digest authentication",
9043 .uri = "amxml",
9044 .has_subtree = 0,
9045 .callback = auth_mxml_http_callback,
9046 .data = NULL,
9047 .key = __FILE__,
9048 };
9049
9050 /*! \brief Get number of logged in sessions for a login name */
9051 static int get_manager_sessions_cb(void *obj, void *arg, void *data, int flags)
9052 {
9053 struct mansession_session *session = obj;
9054 const char *login = (char *)arg;
9055 int *no_sessions = data;
9056
9057 if (strcasecmp(session->username, login) == 0) {
9058 (*no_sessions)++;
9059 }
9060
9061 return 0;
9062 }
9063
9064
9065 /*! \brief ${AMI_CLIENT()} Dialplan function - reads manager client data */
9066 static int function_amiclient(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
9067 {
9068 struct ast_manager_user *user = NULL;
9069
9070 AST_DECLARE_APP_ARGS(args,
9071 AST_APP_ARG(name);
9072 AST_APP_ARG(param);
9073 );
9074
9075
9076 if (ast_strlen_zero(data) ) {
9077 ast_log(LOG_WARNING, "AMI_CLIENT() requires two arguments: AMI_CLIENT(<name>[,<arg>])\n");
9078 return -1;
9079 }
9080 AST_STANDARD_APP_ARGS(args, data);
9081 args.name = ast_strip(args.name);
9082 args.param = ast_strip(args.param);
9083
9084 AST_RWLIST_RDLOCK(&users);
9085 if (!(user = get_manager_by_name_locked(args.name))) {
9086 AST_RWLIST_UNLOCK(&users);
9087 ast_log(LOG_ERROR, "There's no manager user called : \"%s\"\n", args.name);
9088 return -1;
9089 }
9090 AST_RWLIST_UNLOCK(&users);
9091
9092 if (!strcasecmp(args.param, "sessions")) {
9093 int no_sessions = 0;
9094 struct ao2_container *sessions;
9095
9096 sessions = ao2_global_obj_ref(mgr_sessions);
9097 if (sessions) {
9098 ao2_callback_data(sessions, 0, get_manager_sessions_cb, /*login name*/ data, &no_sessions);
9099 ao2_ref(sessions, -1);
9100 }
9101 snprintf(buf, len, "%d", no_sessions);
9102 } else {
9103 ast_log(LOG_ERROR, "Invalid arguments provided to function AMI_CLIENT: %s\n", args.param);
9104 return -1;
9105
9106 }
9107
9108 return 0;
9109 }
9110
9111
9112 /*! \brief description of AMI_CLIENT dialplan function */
9113 static struct ast_custom_function managerclient_function = {
9114 .name = "AMI_CLIENT",
9115 .read = function_amiclient,
9116 .read_max = 12,
9117 };
9118
9119 static int webregged = 0;
9120
9121 /*! \brief cleanup code called at each iteration of server_root,
9122 * guaranteed to happen every 5 seconds at most
9123 */
9124 static void purge_old_stuff(void *data)
9125 {
9126 struct ast_tcptls_session_args *ser = data;
9127 /* purge_sessions will return the number of sessions actually purged,
9128 * up to a maximum of it's arguments, purge one at a time, keeping a
9129 * purge interval of 1ms as long as we purged a session, otherwise
9130 * revert to a purge check every 5s
9131 */
9132 if (purge_sessions(1) == 1) {
9133 ser->poll_timeout = 1;
9134 } else {
9135 ser->poll_timeout = 5000;
9136 }
9137 purge_events();
9138 }
9139
9140 static struct ast_tls_config ami_tls_cfg;
9141 static struct ast_tcptls_session_args ami_desc = {
9142 .accept_fd = -1,
9143 .master = AST_PTHREADT_NULL,
9144 .tls_cfg = NULL,
9145 .poll_timeout = 5000, /* wake up every 5 seconds */
9146 .periodic_fn = purge_old_stuff,
9147 .name = "AMI server",
9148 .accept_fn = ast_tcptls_server_root, /* thread doing the accept() */
9149 .worker_fn = session_do, /* thread handling the session */
9150 };
9151
9152 static struct ast_tcptls_session_args amis_desc = {
9153 .accept_fd = -1,
9154 .master = AST_PTHREADT_NULL,
9155 .tls_cfg = &ami_tls_cfg,
9156 .poll_timeout = -1, /* the other does the periodic cleanup */
9157 .name = "AMI TLS server",
9158 .accept_fn = ast_tcptls_server_root, /* thread doing the accept() */
9159 .worker_fn = session_do, /* thread handling the session */
9160 };
9161
9162 /*! \brief CLI command manager show settings */
9163 static char *handle_manager_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9164 {
9165 switch (cmd) {
9166 case CLI_INIT:
9167 e->command = "manager show settings";
9168 e->usage =
9169 "Usage: manager show settings\n"
9170 " Provides detailed list of the configuration of the Manager.\n";
9171 return NULL;
9172 case CLI_GENERATE:
9173 return NULL;
9174 }
9175 #define FORMAT " %-25.25s %-15.55s\n"
9176 #define FORMAT2 " %-25.25s %-15d\n"
9177 #define FORMAT3 " %-25.25s %s\n"
9178 if (a->argc != 3) {
9179 return CLI_SHOWUSAGE;
9180 }
9181 ast_cli(a->fd, "\nGlobal Settings:\n");
9182 ast_cli(a->fd, "----------------\n");
9183 ast_cli(a->fd, FORMAT, "Manager (AMI):", AST_CLI_YESNO(manager_enabled));
9184 ast_cli(a->fd, FORMAT, "Web Manager (AMI/HTTP):", AST_CLI_YESNO(webmanager_enabled));
9185 ast_cli(a->fd, FORMAT, "TCP Bindaddress:", manager_enabled != 0 ? ast_sockaddr_stringify(&ami_desc.local_address) : "Disabled");
9186 ast_cli(a->fd, FORMAT2, "HTTP Timeout (seconds):", httptimeout);
9187 ast_cli(a->fd, FORMAT, "TLS Enable:", AST_CLI_YESNO(ami_tls_cfg.enabled));
9188 ast_cli(a->fd, FORMAT, "TLS Bindaddress:", ami_tls_cfg.enabled != 0 ? ast_sockaddr_stringify(&amis_desc.local_address) : "Disabled");
9189 ast_cli(a->fd, FORMAT, "TLS Certfile:", ami_tls_cfg.certfile);
9190 ast_cli(a->fd, FORMAT, "TLS Privatekey:", ami_tls_cfg.pvtfile);
9191 ast_cli(a->fd, FORMAT, "TLS Cipher:", ami_tls_cfg.cipher);
9192 ast_cli(a->fd, FORMAT, "Allow multiple login:", AST_CLI_YESNO(allowmultiplelogin));
9193 ast_cli(a->fd, FORMAT, "Display connects:", AST_CLI_YESNO(displayconnects));
9194 ast_cli(a->fd, FORMAT, "Timestamp events:", AST_CLI_YESNO(timestampevents));
9195 ast_cli(a->fd, FORMAT3, "Channel vars:", S_OR(manager_channelvars, ""));
9196 ast_cli(a->fd, FORMAT3, "Disabled events:", S_OR(manager_disabledevents, ""));
9197 ast_cli(a->fd, FORMAT, "Debug:", AST_CLI_YESNO(manager_debug));
9198 #undef FORMAT
9199 #undef FORMAT2
9200 #undef FORMAT3
9201
9202 return CLI_SUCCESS;
9203 }
9204
9205 #ifdef AST_XML_DOCS
9206
9207 /* Sort function for ast_xml_doc_item by name field */
9208 AO2_STRING_FIELD_SORT_FN(ast_xml_doc_item, name);
9209
9210 static int event_max_name_len_cb(void *obj, void *arg, void *data, int flags)
9211 {
9212 struct ast_xml_doc_item *item = obj;
9213 int *max_len = data;
9214 int len = strlen(item->name);
9215
9216 if (len > *max_len) {
9217 *max_len = len;
9218 }
9219
9220 return 0;
9221 }
9222
9223 static char *handle_manager_show_events(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9224 {
9225 struct ao2_container *events;
9226 struct ao2_container *sorted_events;
9227 struct ao2_iterator it_events;
9228 struct ast_xml_doc_item *item;
9229 struct ast_str *buffer;
9230 int col = 0;
9231 int maxlen = 0;
9232 const char *dashes = "--------------------------------------------------------------------------------";
9233
9234 switch (cmd) {
9235 case CLI_INIT:
9236 e->command = "manager show events";
9237 e->usage =
9238 "Usage: manager show events\n"
9239 " Prints a listing of the available Asterisk manager interface events.\n";
9240 return NULL;
9241 case CLI_GENERATE:
9242 return NULL;
9243 }
9244 if (a->argc != 3) {
9245 return CLI_SHOWUSAGE;
9246 }
9247
9248 buffer = ast_str_create(128);
9249 if (!buffer) {
9250 return CLI_SUCCESS;
9251 }
9252
9253 events = ao2_global_obj_ref(event_docs);
9254 if (!events) {
9255 ast_cli(a->fd, "No manager event documentation loaded\n");
9256 ast_free(buffer);
9257 return CLI_SUCCESS;
9258 }
9259
9260 ao2_lock(events);
9261 sorted_events = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_NOLOCK,
9262 AO2_CONTAINER_ALLOC_OPT_DUPS_REPLACE,
9263 ast_xml_doc_item_sort_fn, NULL);
9264 if (!sorted_events) {
9265 ao2_unlock(events);
9266 ast_log(AST_LOG_ERROR, "Unable to create sorted container for events\n");
9267 ast_free(buffer);
9268 ao2_ref(events, -1);
9269 return CLI_SUCCESS;
9270 }
9271 ao2_container_dup(sorted_events, events, 0);
9272 ao2_unlock(events);
9273 ao2_ref(events, -1);
9274
9275 ao2_callback_data(sorted_events, OBJ_NODATA, event_max_name_len_cb, NULL, &maxlen);
9276 it_events = ao2_iterator_init(sorted_events, AO2_ITERATOR_DONTLOCK);
9277
9278 ast_cli(a->fd, "Events:\n");
9279 ast_cli(a->fd, " %.*s %.*s %.*s \n", maxlen, dashes, maxlen, dashes, maxlen, dashes);
9280
9281 while ((item = ao2_iterator_next(&it_events))) {
9282 ast_str_append(&buffer, 0, " %-*s", maxlen, item->name);
9283 if (++col % 3 == 0) {
9284 ast_cli(a->fd, "%s\n", ast_str_buffer(buffer));
9285 ast_str_set(&buffer, 0, "%s", "");
9286 }
9287 ao2_ref(item, -1);
9288 }
9289 ao2_iterator_destroy(&it_events);
9290
9291 if (col % 3 != 0) {
9292 ast_cli(a->fd, "%s\n", ast_str_buffer(buffer));
9293 }
9294 ast_cli(a->fd, "\n%d events registered.\n", col);
9295
9296 ao2_ref(sorted_events, -1);
9297 ast_free(buffer);
9298
9299 return CLI_SUCCESS;
9300 }
9301
9302 static void print_event_instance(struct ast_cli_args *a, struct ast_xml_doc_item *instance)
9303 {
9304 char *since, *syntax, *provided_by, *description, *synopsis, *seealso, *arguments;
9305
9306 synopsis = ast_xmldoc_printable(AS_OR(instance->synopsis, "Not available"), 1);
9307 provided_by = ast_xmldoc_printable(AS_OR(instance->provided_by, "Not available"), 1);
9308 since = ast_xmldoc_printable(AS_OR(instance->since, "Not available"), 1);
9309 description = ast_xmldoc_printable(AS_OR(instance->description, "Not available"), 1);
9310 syntax = ast_xmldoc_printable(AS_OR(instance->syntax, "Not available"), 1);
9311 arguments = ast_xmldoc_printable(AS_OR(instance->arguments, "Not available"), 1);
9312 seealso = ast_xmldoc_printable(AS_OR(instance->seealso, "Not available"), 1);
9313
9314 if (!synopsis || !provided_by || !since || !description || !syntax || !arguments || !seealso) {
9315 ast_cli(a->fd, "Error: Memory allocation failed\n");
9316 goto free_docs;
9317 }
9318
9319 ast_cli(a->fd, "\n"
9320 "%s -= Info about Manager Event '%s' =- %s\n\n"
9321 COLORIZE_FMT "\n"
9322 "%s\n\n"
9323 COLORIZE_FMT "\n"
9324 "%s\n\n"
9325 COLORIZE_FMT "\n"
9326 "%s\n\n"
9327 COLORIZE_FMT "\n"
9328 "%s\n\n"
9329 COLORIZE_FMT "\n"
9330 "%s\n\n"
9331 COLORIZE_FMT "\n"
9332 "%s\n\n"
9333 COLORIZE_FMT "\n"
9334 "%s\n\n",
9335 ast_term_color(COLOR_MAGENTA, 0), instance->name, ast_term_reset(),
9336 COLORIZE(COLOR_MAGENTA, 0, "[Synopsis]"), synopsis,
9337 COLORIZE(COLOR_MAGENTA, 0, "[Provided By]"), provided_by,
9338 COLORIZE(COLOR_MAGENTA, 0, "[Since]"), since,
9339 COLORIZE(COLOR_MAGENTA, 0, "[Description]"), description,
9340 COLORIZE(COLOR_MAGENTA, 0, "[Syntax]"), syntax,
9341 COLORIZE(COLOR_MAGENTA, 0, "[Arguments]"), arguments,
9342 COLORIZE(COLOR_MAGENTA, 0, "[See Also]"), seealso
9343 );
9344
9345 free_docs:
9346 ast_free(synopsis);
9347 ast_free(since);
9348 ast_free(description);
9349 ast_free(syntax);
9350 ast_free(arguments);
9351 ast_free(seealso);
9352 }
9353
9354 static char *handle_manager_show_event(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9355 {
9356 RAII_VAR(struct ao2_container *, events, NULL, ao2_cleanup);
9357 struct ao2_iterator it_events;
9358 struct ast_xml_doc_item *item, *temp;
9359 int length;
9360
9361 if (cmd == CLI_INIT) {
9362 e->command = "manager show event";
9363 e->usage =
9364 "Usage: manager show event <eventname>\n"
9365 " Provides a detailed description a Manager interface event.\n";
9366 return NULL;
9367 }
9368
9369 events = ao2_global_obj_ref(event_docs);
9370 if (!events) {
9371 ast_cli(a->fd, "No manager event documentation loaded\n");
9372 return CLI_SUCCESS;
9373 }
9374
9375 if (cmd == CLI_GENERATE) {
9376 if (a->pos != 3) {
9377 return NULL;
9378 }
9379
9380 length = strlen(a->word);
9381 it_events = ao2_iterator_init(events, 0);
9382 while ((item = ao2_iterator_next(&it_events))) {
9383 if (!strncasecmp(a->word, item->name, length)) {
9384 if (ast_cli_completion_add(ast_strdup(item->name))) {
9385 ao2_ref(item, -1);
9386 break;
9387 }
9388 }
9389 ao2_ref(item, -1);
9390 }
9391 ao2_iterator_destroy(&it_events);
9392
9393 return NULL;
9394 }
9395
9396 if (a->argc != 4) {
9397 return CLI_SHOWUSAGE;
9398 }
9399
9400 if (!(item = ao2_find(events, a->argv[3], OBJ_KEY))) {
9401 ast_cli(a->fd, "Could not find event '%s'\n", a->argv[3]);
9402 return CLI_SUCCESS;
9403 }
9404
9405 ast_cli(a->fd, "Event: %s\n", a->argv[3]);
9406 for (temp = item; temp; temp = AST_LIST_NEXT(temp, next)) {
9407 print_event_instance(a, temp);
9408 }
9409
9410 ao2_ref(item, -1);
9411 return CLI_SUCCESS;
9412 }
9413
9414 #endif
9415
9416 static struct ast_cli_entry cli_manager[] = {
9417 AST_CLI_DEFINE(handle_showmancmd, "Show a manager interface command"),
9418 AST_CLI_DEFINE(handle_showmancmds, "List manager interface commands"),
9419 AST_CLI_DEFINE(handle_showmanconn, "List connected manager interface users"),
9420 AST_CLI_DEFINE(handle_kickmanconn, "Kick a connected manager interface connection"),
9421 AST_CLI_DEFINE(handle_showmaneventq, "List manager interface queued events"),
9422 AST_CLI_DEFINE(handle_showmanagers, "List configured manager users"),
9423 AST_CLI_DEFINE(handle_showmanager, "Display information on a specific manager user"),
9424 AST_CLI_DEFINE(handle_mandebug, "Show, enable, disable debugging of the manager code"),
9425 AST_CLI_DEFINE(handle_manager_reload, "Reload manager configurations"),
9426 AST_CLI_DEFINE(handle_manager_show_settings, "Show manager global settings"),
9427 #ifdef AST_XML_DOCS
9428 AST_CLI_DEFINE(handle_manager_show_events, "List manager interface events"),
9429 AST_CLI_DEFINE(handle_manager_show_event, "Show a manager interface event"),
9430 #endif
9431 };
9432
9433 /*!
9434 * \internal
9435 * \brief Load the config channelvars variable.
9436 *
9437 * \param var Config variable to load.
9438 */
9439 static void load_channelvars(struct ast_variable *var)
9440 {
9441 char *parse = NULL;
9442 AST_DECLARE_APP_ARGS(args,
9443 AST_APP_ARG(vars)[MAX_VARS];
9444 );
9445
9446 ast_free(manager_channelvars);
9447 manager_channelvars = ast_strdup(var->value);
9448
9449 /* parse the setting */
9450 parse = ast_strdupa(manager_channelvars);
9451 AST_STANDARD_APP_ARGS(args, parse);
9452
9453 ast_channel_set_manager_vars(args.argc, args.vars);
9454 }
9455
9456 /*!
9457 * \internal
9458 * \brief Load the config disabledevents variable.
9459 *
9460 * \param var Config variable to load.
9461 */
9462 static void load_disabledevents(struct ast_variable *var)
9463 {
9464 ast_free(manager_disabledevents);
9465 manager_disabledevents = ast_strdup(var->value);
9466 }
9467
9468 /*!
9469 * \internal
9470 * \brief Free a user record. Should already be removed from the list
9471 */
9472 static void manager_free_user(struct ast_manager_user *user)
9473 {
9474 ast_free(user->a1_hash);
9475 ast_free(user->secret);
9476 if (user->includefilters) {
9477 ao2_t_ref(user->includefilters, -1, "decrement ref for include container, should be last one");
9478 }
9479 if (user->excludefilters) {
9480 ao2_t_ref(user->excludefilters, -1, "decrement ref for exclude container, should be last one");
9481 }
9482 user->acl = ast_free_acl_list(user->acl);
9483 ast_variables_destroy(user->chanvars);
9484 ast_free(user);
9485 }
9486
9487 /*!
9488 * \internal
9489 * \brief Clean up resources on Asterisk shutdown
9490 */
9491 static void manager_shutdown(void)
9492 {
9493 struct ast_manager_user *user;
9494
9495 #ifdef TEST_FRAMEWORK
9496 AST_TEST_UNREGISTER(eventfilter_test_creation);
9497 AST_TEST_UNREGISTER(eventfilter_test_matching);
9498 AST_TEST_UNREGISTER(originate_permissions_test);
9499 #endif
9500
9501 /* This event is not actually transmitted, but causes all TCP sessions to be closed */
9502 manager_event(EVENT_FLAG_SHUTDOWN, "CloseSession", "CloseSession: true\r\n");
9503
9504 ast_manager_unregister("Ping");
9505 ast_manager_unregister("Events");
9506 ast_manager_unregister("Logoff");
9507 ast_manager_unregister("Login");
9508 ast_manager_unregister("Challenge");
9509 ast_manager_unregister("Hangup");
9510 ast_manager_unregister("Status");
9511 ast_manager_unregister("Setvar");
9512 ast_manager_unregister("Getvar");
9513 ast_manager_unregister("GetConfig");
9514 ast_manager_unregister("GetConfigJSON");
9515 ast_manager_unregister("UpdateConfig");
9516 ast_manager_unregister("CreateConfig");
9517 ast_manager_unregister("ListCategories");
9518 ast_manager_unregister("Redirect");
9519 ast_manager_unregister("Atxfer");
9520 ast_manager_unregister("CancelAtxfer");
9521 ast_manager_unregister("Originate");
9522 ast_manager_unregister("Command");
9523 ast_manager_unregister("ExtensionState");
9524 ast_manager_unregister("PresenceState");
9525 ast_manager_unregister("AbsoluteTimeout");
9526 ast_manager_unregister("MailboxStatus");
9527 ast_manager_unregister("MailboxCount");
9528 ast_manager_unregister("ListCommands");
9529 ast_manager_unregister("SendText");
9530 ast_manager_unregister("UserEvent");
9531 ast_manager_unregister("WaitEvent");
9532 ast_manager_unregister("CoreSettings");
9533 ast_manager_unregister("CoreStatus");
9534 ast_manager_unregister("Reload");
9535 ast_manager_unregister("LoggerRotate");
9536 ast_manager_unregister("CoreShowChannels");
9537 ast_manager_unregister("CoreShowChannelMap");
9538 ast_manager_unregister("ModuleLoad");
9539 ast_manager_unregister("ModuleCheck");
9540 ast_manager_unregister("AOCMessage");
9541 ast_manager_unregister("Filter");
9542 ast_manager_unregister("BlindTransfer");
9543 ast_custom_function_unregister(&managerclient_function);
9544 ast_cli_unregister_multiple(cli_manager, ARRAY_LEN(cli_manager));
9545
9546 #ifdef AST_XML_DOCS
9547 ao2_t_global_obj_release(event_docs, "Dispose of event_docs");
9548 #endif
9549
9550 #ifdef TEST_FRAMEWORK
9551 stasis_forward_cancel(test_suite_forwarder);
9552 test_suite_forwarder = NULL;
9553 #endif
9554
9555 if (stasis_router) {
9556 stasis_message_router_unsubscribe_and_join(stasis_router);
9557 stasis_router = NULL;
9558 }
9559 stasis_forward_cancel(rtp_topic_forwarder);
9560 rtp_topic_forwarder = NULL;
9561 stasis_forward_cancel(security_topic_forwarder);
9562 security_topic_forwarder = NULL;
9563 ao2_cleanup(manager_topic);
9564 manager_topic = NULL;
9565 STASIS_MESSAGE_TYPE_CLEANUP(ast_manager_get_generic_type);
9566
9567 ast_tcptls_server_stop(&ami_desc);
9568 ast_tcptls_server_stop(&amis_desc);
9569
9570 ast_free(ami_tls_cfg.certfile);
9571 ami_tls_cfg.certfile = NULL;
9572 ast_free(ami_tls_cfg.pvtfile);
9573 ami_tls_cfg.pvtfile = NULL;
9574 ast_free(ami_tls_cfg.cipher);
9575 ami_tls_cfg.cipher = NULL;
9576 ast_free(ami_tls_cfg.cafile);
9577 ami_tls_cfg.cafile = NULL;
9578 ast_free(ami_tls_cfg.capath);
9579 ami_tls_cfg.capath = NULL;
9580
9581 ao2_global_obj_release(mgr_sessions);
9582
9583 while ((user = AST_LIST_REMOVE_HEAD(&users, list))) {
9584 manager_free_user(user);
9585 }
9586 acl_change_stasis_unsubscribe();
9587
9588 ast_free(manager_channelvars);
9589 ast_free(manager_disabledevents);
9590 }
9591
9592
9593 /*! \brief Initialize all \ref stasis topics and routers used by the various
9594 * sub-components of AMI
9595 */
9596 static int manager_subscriptions_init(void)
9597 {
9598 struct ao2_container *sessions;
9599 int res = 0;
9600
9601 rtp_topic_forwarder = stasis_forward_all(ast_rtp_topic(), manager_topic);
9602 if (!rtp_topic_forwarder) {
9603 return -1;
9604 }
9605
9606 security_topic_forwarder = stasis_forward_all(ast_security_topic(), manager_topic);
9607 if (!security_topic_forwarder) {
9608 return -1;
9609 }
9610
9611 stasis_router = stasis_message_router_create(manager_topic);
9612 if (!stasis_router) {
9613 return -1;
9614 }
9615 stasis_message_router_set_congestion_limits(stasis_router, -1,
9616 6 * AST_TASKPROCESSOR_HIGH_WATER_LEVEL);
9617
9618 /*
9619 * The reference to sessions passes to the stasis router subscription so
9620 * no need to unref here at all. This is also invoked after creating the
9621 * sessions container so it has to exist.
9622 */
9623 sessions = ao2_global_obj_ref(mgr_sessions);
9624
9625 stasis_message_router_set_formatters_default(stasis_router,
9626 manager_default_msg_cb, sessions, STASIS_SUBSCRIPTION_FORMATTER_AMI);
9627
9628 res |= stasis_message_router_add(stasis_router,
9629 ast_manager_get_generic_type(), manager_generic_msg_cb, sessions);
9630
9631 /*
9632 * This specific callback is solely for lifetime management of the sessions
9633 * reference. Once the subscription is finalized the reference is dropped in
9634 * the callback.
9635 */
9636 res |= stasis_message_router_add(stasis_router,
9637 stasis_subscription_change_type(), manager_subscription_change_msg_cb, sessions);
9638
9639 if (res != 0) {
9640 return -1;
9641 }
9642 return 0;
9643 }
9644
9645 static int subscribe_all(void)
9646 {
9647 if (manager_subscriptions_init()) {
9648 ast_log(AST_LOG_ERROR, "Failed to initialize manager subscriptions\n");
9649 return -1;
9650 }
9651 if (manager_system_init()) {
9652 ast_log(AST_LOG_ERROR, "Failed to initialize manager system handling\n");
9653 return -1;
9654 }
9655 if (manager_channels_init()) {
9656 ast_log(AST_LOG_ERROR, "Failed to initialize manager channel handling\n");
9657 return -1;
9658 }
9659 if (manager_mwi_init()) {
9660 ast_log(AST_LOG_ERROR, "Failed to initialize manager MWI handling\n");
9661 return -1;
9662 }
9663 if (manager_bridging_init()) {
9664 return -1;
9665 }
9666 if (manager_endpoints_init()) {
9667 ast_log(AST_LOG_ERROR, "Failed to initialize manager endpoints handling\n");
9668 return -1;
9669 }
9670
9671 subscribed = 1;
9672 return 0;
9673 }
9674
9675 static void manager_set_defaults(void)
9676 {
9677 manager_enabled = 0;
9678 displayconnects = 1;
9679 broken_events_action = 0;
9680 authtimeout = 30;
9681 authlimit = 50;
9682 manager_debug = 0; /* Debug disabled by default */
9683
9684 /* default values */
9685 ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM),
9686 sizeof(global_realm));
9687 ast_sockaddr_setnull(&ami_desc.local_address);
9688 ast_sockaddr_setnull(&amis_desc.local_address);
9689
9690 ami_tls_cfg.enabled = 0;
9691 ast_free(ami_tls_cfg.certfile);
9692 ami_tls_cfg.certfile = ast_strdup(AST_CERTFILE);
9693 ast_free(ami_tls_cfg.pvtfile);
9694 ami_tls_cfg.pvtfile = ast_strdup("");
9695 ast_free(ami_tls_cfg.cipher);
9696 ami_tls_cfg.cipher = ast_strdup("");
9697 ast_free(ami_tls_cfg.cafile);
9698 ami_tls_cfg.cafile = ast_strdup("");
9699 ast_free(ami_tls_cfg.capath);
9700 ami_tls_cfg.capath = ast_strdup("");
9701 }
9702
9703 static int __init_manager(int reload, int by_external_config)
9704 {
9705 struct ast_config *ucfg = NULL, *cfg = NULL;
9706 const char *val;
9707 char *cat = NULL;
9708 int newhttptimeout = 60;
9709 struct ast_manager_user *user = NULL;
9710 struct ast_variable *var;
9711 struct ast_flags config_flags = { (reload && !by_external_config) ? CONFIG_FLAG_FILEUNCHANGED : 0 };
9712 char a1[337];
9713 char a1_hash[256];
9714 struct ast_sockaddr ami_desc_local_address_tmp;
9715 struct ast_sockaddr amis_desc_local_address_tmp;
9716 int tls_was_enabled = 0;
9717 int acl_subscription_flag = 0;
9718
9719 if (!reload) {
9720 struct ao2_container *sessions;
9721 #ifdef AST_XML_DOCS
9722 struct ao2_container *temp_event_docs;
9723 #endif
9724 int res;
9725
9726 res = STASIS_MESSAGE_TYPE_INIT(ast_manager_get_generic_type);
9727 if (res != 0) {
9728 return -1;
9729 }
9730 manager_topic = stasis_topic_create("manager:core");
9731 if (!manager_topic) {
9732 return -1;
9733 }
9734
9735 /* Register default actions */
9736 ast_manager_register_xml_core("Ping", 0, action_ping);
9737 ast_manager_register_xml_core("Events", 0, action_events);
9738 ast_manager_register_xml_core("Logoff", 0, action_logoff);
9739 ast_manager_register_xml_core("Login", 0, action_login);
9740 ast_manager_register_xml_core("Challenge", 0, action_challenge);
9741 ast_manager_register_xml_core("Hangup", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_hangup);
9742 ast_manager_register_xml_core("Status", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_status);
9743 ast_manager_register_xml_core("Setvar", EVENT_FLAG_CALL, action_setvar);
9744 ast_manager_register_xml_core("Getvar", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_getvar);
9745 ast_manager_register_xml_core("GetConfig", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfig);
9746 ast_manager_register_xml_core("GetConfigJSON", EVENT_FLAG_SYSTEM | EVENT_FLAG_CONFIG, action_getconfigjson);
9747 ast_manager_register_xml_core("UpdateConfig", EVENT_FLAG_CONFIG, action_updateconfig);
9748 ast_manager_register_xml_core("CreateConfig", EVENT_FLAG_CONFIG, action_createconfig);
9749 ast_manager_register_xml_core("ListCategories", EVENT_FLAG_CONFIG, action_listcategories);
9750 ast_manager_register_xml_core("Redirect", EVENT_FLAG_CALL, action_redirect);
9751 ast_manager_register_xml_core("Atxfer", EVENT_FLAG_CALL, action_atxfer);
9752 ast_manager_register_xml_core("CancelAtxfer", EVENT_FLAG_CALL, action_cancel_atxfer);
9753 ast_manager_register_xml_core("Originate", EVENT_FLAG_ORIGINATE, action_originate);
9754 ast_manager_register_xml_core("Command", EVENT_FLAG_COMMAND, action_command);
9755 ast_manager_register_xml_core("ExtensionState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_extensionstate);
9756 ast_manager_register_xml_core("PresenceState", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_presencestate);
9757 ast_manager_register_xml_core("AbsoluteTimeout", EVENT_FLAG_SYSTEM | EVENT_FLAG_CALL, action_timeout);
9758 ast_manager_register_xml_core("MailboxStatus", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxstatus);
9759 ast_manager_register_xml_core("MailboxCount", EVENT_FLAG_CALL | EVENT_FLAG_REPORTING, action_mailboxcount);
9760 ast_manager_register_xml_core("ListCommands", 0, action_listcommands);
9761 ast_manager_register_xml_core("SendText", EVENT_FLAG_CALL, action_sendtext);
9762 ast_manager_register_xml_core("UserEvent", EVENT_FLAG_USER, action_userevent);
9763 ast_manager_register_xml_core("WaitEvent", 0, action_waitevent);
9764 ast_manager_register_xml_core("CoreSettings", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coresettings);
9765 ast_manager_register_xml_core("CoreStatus", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_corestatus);
9766 ast_manager_register_xml_core("Reload", EVENT_FLAG_CONFIG | EVENT_FLAG_SYSTEM, action_reload);
9767 ast_manager_register_xml_core("LoggerRotate", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_loggerrotate);
9768 ast_manager_register_xml_core("CoreShowChannels", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannels);
9769 ast_manager_register_xml_core("CoreShowChannelMap", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, action_coreshowchannelmap);
9770 ast_manager_register_xml_core("ModuleLoad", EVENT_FLAG_SYSTEM, manager_moduleload);
9771 ast_manager_register_xml_core("ModuleCheck", EVENT_FLAG_SYSTEM, manager_modulecheck);
9772 ast_manager_register_xml_core("AOCMessage", EVENT_FLAG_AOC, action_aocmessage);
9773 ast_manager_register_xml_core("Filter", EVENT_FLAG_SYSTEM, action_filter);
9774 ast_manager_register_xml_core("BlindTransfer", EVENT_FLAG_CALL, action_blind_transfer);
9775
9776 #ifdef TEST_FRAMEWORK
9777 test_suite_forwarder = stasis_forward_all(ast_test_suite_topic(), manager_topic);
9778 #endif
9779
9780 ast_cli_register_multiple(cli_manager, ARRAY_LEN(cli_manager));
9781 __ast_custom_function_register(&managerclient_function, NULL);
9782 ast_extension_state_add(NULL, NULL, manager_state_cb, NULL);
9783
9784 /* Append placeholder event so master_eventq never runs dry */
9785 if (append_event("Event: Placeholder\r\n\r\n",
9786 ast_str_hash("Placeholder"), 0)) {
9787 return -1;
9788 }
9789
9790 #ifdef AST_XML_DOCS
9791 temp_event_docs = ast_xmldoc_build_documentation("managerEvent");
9792 if (temp_event_docs) {
9793 ao2_t_global_obj_replace_unref(event_docs, temp_event_docs, "Toss old event docs");
9794 ao2_t_ref(temp_event_docs, -1, "Remove creation ref - container holds only ref now");
9795 }
9796 #endif
9797
9798 /* If you have a NULL hash fn, you only need a single bucket */
9799 sessions = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, mansession_cmp_fn);
9800 if (!sessions) {
9801 return -1;
9802 }
9803 ao2_global_obj_replace_unref(mgr_sessions, sessions);
9804 ao2_ref(sessions, -1);
9805
9806 /* Initialize all settings before first configuration load. */
9807 manager_set_defaults();
9808 }
9809
9810 cfg = ast_config_load2("manager.conf", "manager", config_flags);
9811 if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
9812 return 0;
9813 } else if (!cfg || cfg == CONFIG_STATUS_FILEINVALID) {
9814 ast_log(LOG_NOTICE, "Unable to open AMI configuration manager.conf, or configuration is invalid.\n");
9815 return 0;
9816 }
9817
9818 /* If this wasn't performed due to a forced reload (because those can be created by ACL change events, we need to unsubscribe to ACL change events. */
9819 if (!by_external_config) {
9820 acl_change_stasis_unsubscribe();
9821 }
9822
9823 if (reload) {
9824 /* Reset all settings before reloading configuration */
9825 tls_was_enabled = ami_tls_cfg.enabled;
9826 manager_set_defaults();
9827 }
9828
9829 ast_sockaddr_parse(&ami_desc_local_address_tmp, "[::]", 0);
9830 ast_sockaddr_set_port(&ami_desc_local_address_tmp, DEFAULT_MANAGER_PORT);
9831
9832 for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
9833 val = var->value;
9834
9835 /* read tls config options while preventing unsupported options from being set */
9836 if (strcasecmp(var->name, "tlscafile")
9837 && strcasecmp(var->name, "tlscapath")
9838 && strcasecmp(var->name, "tlscadir")
9839 && strcasecmp(var->name, "tlsverifyclient")
9840 && strcasecmp(var->name, "tlsdontverifyserver")
9841 && strcasecmp(var->name, "tlsclientmethod")
9842 && strcasecmp(var->name, "sslclientmethod")
9843 && !ast_tls_read_conf(&ami_tls_cfg, &amis_desc, var->name, val)) {
9844 continue;
9845 }
9846
9847 if (!strcasecmp(var->name, "enabled")) {
9848 manager_enabled = ast_true(val);
9849 } else if (!strcasecmp(var->name, "webenabled")) {
9850 webmanager_enabled = ast_true(val);
9851 } else if (!strcasecmp(var->name, "port")) {
9852 int bindport;
9853 if (ast_parse_arg(val, PARSE_UINT32|PARSE_IN_RANGE, &bindport, 1024, 65535)) {
9854 ast_log(LOG_WARNING, "Invalid port number '%s'\n", val);
9855 }
9856 ast_sockaddr_set_port(&ami_desc_local_address_tmp, bindport);
9857 } else if (!strcasecmp(var->name, "bindaddr")) {
9858 /* remember port if it has already been set */
9859 int setport = ast_sockaddr_port(&ami_desc_local_address_tmp);
9860
9861 if (ast_parse_arg(val, PARSE_ADDR|PARSE_PORT_IGNORE, NULL)) {
9862 ast_log(LOG_WARNING, "Invalid address '%s' specified, default '%s' will be used\n", val,
9863 ast_sockaddr_stringify_addr(&ami_desc_local_address_tmp));
9864 } else {
9865 ast_sockaddr_parse(&ami_desc_local_address_tmp, val, PARSE_PORT_IGNORE);
9866 }
9867
9868 if (setport) {
9869 ast_sockaddr_set_port(&ami_desc_local_address_tmp, setport);
9870 }
9871
9872 } else if (!strcasecmp(var->name, "brokeneventsaction")) {
9873 broken_events_action = ast_true(val);
9874 } else if (!strcasecmp(var->name, "allowmultiplelogin")) {
9875 allowmultiplelogin = ast_true(val);
9876 } else if (!strcasecmp(var->name, "displayconnects")) {
9877 displayconnects = ast_true(val);
9878 } else if (!strcasecmp(var->name, "timestampevents")) {
9879 timestampevents = ast_true(val);
9880 } else if (!strcasecmp(var->name, "debug")) {
9881 manager_debug = ast_true(val);
9882 } else if (!strcasecmp(var->name, "httptimeout")) {
9883 newhttptimeout = atoi(val);
9884 } else if (!strcasecmp(var->name, "authtimeout")) {
9885 int timeout = atoi(var->value);
9886
9887 if (timeout < 1) {
9888 ast_log(LOG_WARNING, "Invalid authtimeout value '%s', using default value\n", var->value);
9889 } else {
9890 authtimeout = timeout;
9891 }
9892 } else if (!strcasecmp(var->name, "authlimit")) {
9893 int limit = atoi(var->value);
9894
9895 if (limit < 1) {
9896 ast_log(LOG_WARNING, "Invalid authlimit value '%s', using default value\n", var->value);
9897 } else {
9898 authlimit = limit;
9899 }
9900 } else if (!strcasecmp(var->name, "channelvars")) {
9901 load_channelvars(var);
9902 } else if (!strcasecmp(var->name, "disabledevents")) {
9903 load_disabledevents(var);
9904 } else {
9905 ast_log(LOG_NOTICE, "Invalid keyword <%s> = <%s> in manager.conf [general]\n",
9906 var->name, val);
9907 }
9908 }
9909
9910 if (manager_enabled && !subscribed) {
9911 if (subscribe_all() != 0) {
9912 ast_log(LOG_ERROR, "Manager subscription error\n");
9913 return -1;
9914 }
9915 }
9916
9917 ast_sockaddr_copy(&amis_desc_local_address_tmp, &amis_desc.local_address);
9918
9919 /* if the amis address has not been set, default is the same as non secure ami */
9920 if (ast_sockaddr_isnull(&amis_desc_local_address_tmp)) {
9921 ast_sockaddr_copy(&amis_desc_local_address_tmp, &ami_desc_local_address_tmp);
9922 }
9923
9924 /* if the amis address was not set, it will have non-secure ami port set; if
9925 amis address was set, we need to check that a port was set or not, if not
9926 use the default tls port */
9927 if (ast_sockaddr_port(&amis_desc_local_address_tmp) == 0 ||
9928 (ast_sockaddr_port(&ami_desc_local_address_tmp) == ast_sockaddr_port(&amis_desc_local_address_tmp))) {
9929
9930 ast_sockaddr_set_port(&amis_desc_local_address_tmp, DEFAULT_MANAGER_TLS_PORT);
9931 }
9932
9933 if (manager_enabled) {
9934 ast_sockaddr_copy(&ami_desc.local_address, &ami_desc_local_address_tmp);
9935 ast_sockaddr_copy(&amis_desc.local_address, &amis_desc_local_address_tmp);
9936 }
9937
9938 AST_RWLIST_WRLOCK(&users);
9939
9940 /* First, get users from users.conf */
9941 ucfg = ast_config_load2("users.conf", "manager", config_flags);
9942 if (ucfg && (ucfg != CONFIG_STATUS_FILEUNCHANGED) && ucfg != CONFIG_STATUS_FILEINVALID) {
9943 const char *hasmanager;
9944 int genhasmanager = ast_true(ast_variable_retrieve(ucfg, "general", "hasmanager"));
9945
9946 while ((cat = ast_category_browse(ucfg, cat))) {
9947 if (!strcasecmp(cat, "general")) {
9948 continue;
9949 }
9950
9951 hasmanager = ast_variable_retrieve(ucfg, cat, "hasmanager");
9952 if ((!hasmanager && genhasmanager) || ast_true(hasmanager)) {
9953 const char *user_secret = ast_variable_retrieve(ucfg, cat, "secret");
9954 const char *user_read = ast_variable_retrieve(ucfg, cat, "read");
9955 const char *user_write = ast_variable_retrieve(ucfg, cat, "write");
9956 const char *user_displayconnects = ast_variable_retrieve(ucfg, cat, "displayconnects");
9957 const char *user_allowmultiplelogin = ast_variable_retrieve(ucfg, cat, "allowmultiplelogin");
9958 const char *user_writetimeout = ast_variable_retrieve(ucfg, cat, "writetimeout");
9959
9960 /* Look for an existing entry,
9961 * if none found - create one and add it to the list
9962 */
9963 if (!(user = get_manager_by_name_locked(cat))) {
9964 if (!(user = ast_calloc(1, sizeof(*user)))) {
9965 break;
9966 }
9967
9968 /* Copy name over */
9969 ast_copy_string(user->username, cat, sizeof(user->username));
9970 /* Insert into list */
9971 AST_LIST_INSERT_TAIL(&users, user, list);
9972 user->acl = NULL;
9973 user->keep = 1;
9974 user->readperm = -1;
9975 user->writeperm = -1;
9976 /* Default displayconnect from [general] */
9977 user->displayconnects = displayconnects;
9978 /* Default allowmultiplelogin from [general] */
9979 user->allowmultiplelogin = allowmultiplelogin;
9980 user->writetimeout = 100;
9981 }
9982
9983 if (!user_secret) {
9984 user_secret = ast_variable_retrieve(ucfg, "general", "secret");
9985 }
9986 if (!user_read) {
9987 user_read = ast_variable_retrieve(ucfg, "general", "read");
9988 }
9989 if (!user_write) {
9990 user_write = ast_variable_retrieve(ucfg, "general", "write");
9991 }
9992 if (!user_displayconnects) {
9993 user_displayconnects = ast_variable_retrieve(ucfg, "general", "displayconnects");
9994 }
9995 if (!user_allowmultiplelogin) {
9996 user_allowmultiplelogin = ast_variable_retrieve(ucfg, "general", "allowmultiplelogin");
9997 }
9998 if (!user_writetimeout) {
9999 user_writetimeout = ast_variable_retrieve(ucfg, "general", "writetimeout");
10000 }
10001
10002 if (!ast_strlen_zero(user_secret)) {
10003 ast_free(user->secret);
10004 user->secret = ast_strdup(user_secret);
10005 }
10006
10007 if (user_read) {
10008 user->readperm = get_perm(user_read);
10009 }
10010 if (user_write) {
10011 user->writeperm = get_perm(user_write);
10012 }
10013 if (user_displayconnects) {
10014 user->displayconnects = ast_true(user_displayconnects);
10015 }
10016 if (user_allowmultiplelogin) {
10017 user->allowmultiplelogin = ast_true(user_allowmultiplelogin);
10018 }
10019 if (user_writetimeout) {
10020 int value = atoi(user_writetimeout);
10021 if (value < 100) {
10022 ast_log(LOG_WARNING, "Invalid writetimeout value '%d' in users.conf\n", value);
10023 } else {
10024 user->writetimeout = value;
10025 }
10026 }
10027 }
10028 }
10029 ast_config_destroy(ucfg);
10030 }
10031
10032 /* cat is NULL here in any case */
10033
10034 while ((cat = ast_category_browse(cfg, cat))) {
10035 struct ast_acl_list *oldacl;
10036
10037 if (!strcasecmp(cat, "general")) {
10038 continue;
10039 }
10040
10041 /* Look for an existing entry, if none found - create one and add it to the list */
10042 if (!(user = get_manager_by_name_locked(cat))) {
10043 if (!(user = ast_calloc(1, sizeof(*user)))) {
10044 break;
10045 }
10046 /* Copy name over */
10047 ast_copy_string(user->username, cat, sizeof(user->username));
10048
10049 user->acl = NULL;
10050 user->readperm = 0;
10051 user->writeperm = 0;
10052 /* Default displayconnect from [general] */
10053 user->displayconnects = displayconnects;
10054 /* Default allowmultiplelogin from [general] */
10055 user->allowmultiplelogin = allowmultiplelogin;
10056 user->writetimeout = 100;
10057 user->includefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
10058 user->excludefilters = ao2_container_alloc_list(AO2_ALLOC_OPT_LOCK_MUTEX, 0, NULL, NULL);
10059 if (!user->includefilters || !user->excludefilters) {
10060 manager_free_user(user);
10061 break;
10062 }
10063
10064 /* Insert into list */
10065 AST_RWLIST_INSERT_TAIL(&users, user, list);
10066 } else {
10067 ao2_t_callback(user->includefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all include filters");
10068 ao2_t_callback(user->excludefilters, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, NULL, NULL, "unlink all exclude filters");
10069 }
10070
10071 /* Make sure we keep this user and don't destroy it during cleanup */
10072 user->keep = 1;
10073 oldacl = user->acl;
10074 user->acl = NULL;
10075 ast_variables_destroy(user->chanvars);
10076
10077 var = ast_variable_browse(cfg, cat);
10078 for (; var; var = var->next) {
10079 if (!strcasecmp(var->name, "secret")) {
10080 ast_free(user->secret);
10081 user->secret = ast_strdup(var->value);
10082 } else if (!strcasecmp(var->name, "deny") ||
10083 !strcasecmp(var->name, "permit") ||
10084 !strcasecmp(var->name, "acl")) {
10085 int acl_error = 0;
10086
10087 ast_append_acl(var->name, var->value, &user->acl, &acl_error, &acl_subscription_flag);
10088 if (acl_error) {
10089 ast_log(LOG_ERROR, "Invalid ACL '%s' for manager user '%s' on line %d. Deleting user\n",
10090 var->value, user->username, var->lineno);
10091 user->keep = 0;
10092 }
10093 } else if (!strcasecmp(var->name, "read") ) {
10094 user->readperm = get_perm(var->value);
10095 } else if (!strcasecmp(var->name, "write") ) {
10096 user->writeperm = get_perm(var->value);
10097 } else if (!strcasecmp(var->name, "displayconnects") ) {
10098 user->displayconnects = ast_true(var->value);
10099 } else if (!strcasecmp(var->name, "allowmultiplelogin") ) {
10100 user->allowmultiplelogin = ast_true(var->value);
10101 } else if (!strcasecmp(var->name, "writetimeout")) {
10102 int value = atoi(var->value);
10103 if (value < 100) {
10104 ast_log(LOG_WARNING, "Invalid writetimeout value '%s' at line %d\n", var->value, var->lineno);
10105 } else {
10106 user->writetimeout = value;
10107 }
10108 } else if (!strcasecmp(var->name, "setvar")) {
10109 struct ast_variable *tmpvar;
10110 char varbuf[256];
10111 char *varval;
10112 char *varname;
10113
10114 ast_copy_string(varbuf, var->value, sizeof(varbuf));
10115 varname = varbuf;
10116
10117 if ((varval = strchr(varname,'='))) {
10118 *varval++ = '\0';
10119 if ((tmpvar = ast_variable_new(varname, varval, ""))) {
10120 tmpvar->next = user->chanvars;
10121 user->chanvars = tmpvar;
10122 }
10123 }
10124 } else if (ast_begins_with(var->name, "eventfilter")) {
10125 const char *value = var->value;
10126 manager_add_filter(var->name, value, user->includefilters, user->excludefilters);
10127 } else {
10128 ast_debug(1, "%s is an unknown option.\n", var->name);
10129 }
10130 }
10131
10132 oldacl = ast_free_acl_list(oldacl);
10133 }
10134 ast_config_destroy(cfg);
10135
10136 /* Check the flag for named ACL event subscription and if we need to, register a subscription. */
10137 if (acl_subscription_flag && !by_external_config) {
10138 acl_change_stasis_subscribe();
10139 }
10140
10141 /* Perform cleanup - essentially prune out old users that no longer exist */
10142 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&users, user, list) {
10143 if (user->keep) { /* valid record. clear flag for the next round */
10144 user->keep = 0;
10145
10146 /* Calculate A1 for Digest auth */
10147 snprintf(a1, sizeof(a1), "%s:%s:%s", user->username, global_realm, user->secret);
10148 ast_md5_hash(a1_hash,a1);
10149 ast_free(user->a1_hash);
10150 user->a1_hash = ast_strdup(a1_hash);
10151 continue;
10152 }
10153 /* We do not need to keep this user so take them out of the list */
10154 AST_RWLIST_REMOVE_CURRENT(list);
10155 ast_debug(4, "Pruning user '%s'\n", user->username);
10156 manager_free_user(user);
10157 }
10158 AST_RWLIST_TRAVERSE_SAFE_END;
10159
10160 AST_RWLIST_UNLOCK(&users);
10161
10162 if (webmanager_enabled && manager_enabled) {
10163 if (!webregged) {
10164 ast_http_uri_link(&rawmanuri);
10165 ast_http_uri_link(&manageruri);
10166 ast_http_uri_link(&managerxmluri);
10167
10168 ast_http_uri_link(&arawmanuri);
10169 ast_http_uri_link(&amanageruri);
10170 ast_http_uri_link(&amanagerxmluri);
10171 webregged = 1;
10172 }
10173 } else {
10174 if (webregged) {
10175 ast_http_uri_unlink(&rawmanuri);
10176 ast_http_uri_unlink(&manageruri);
10177 ast_http_uri_unlink(&managerxmluri);
10178
10179 ast_http_uri_unlink(&arawmanuri);
10180 ast_http_uri_unlink(&amanageruri);
10181 ast_http_uri_unlink(&amanagerxmluri);
10182 webregged = 0;
10183 }
10184 }
10185
10186 if (newhttptimeout > 0) {
10187 httptimeout = newhttptimeout;
10188 }
10189
10190 ast_tcptls_server_start(&ami_desc);
10191 if (tls_was_enabled && !ami_tls_cfg.enabled) {
10192 ast_tcptls_server_stop(&amis_desc);
10193 } else if (ast_ssl_setup(amis_desc.tls_cfg)) {
10194 ast_tcptls_server_start(&amis_desc);
10195 }
10196
10197 return 0;
10198 }
10199
10200 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
10201 struct stasis_message *message)
10202 {
10203 if (stasis_message_type(message) != ast_named_acl_change_type()) {
10204 return;
10205 }
10206
10207 /* For now, this is going to be performed simply and just execute a forced reload. */
10208 ast_log(LOG_NOTICE, "Reloading manager in response to ACL change event.\n");
10209 __init_manager(1, 1);
10210 }
10211
10212 static int unload_module(void)
10213 {
10214 return 0;
10215 }
10216
10217 static int load_module(void)
10218 {
10219 int rc = 0;
10220 ast_register_cleanup(manager_shutdown);
10221 rc = __init_manager(0, 0) ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_SUCCESS;
10222 #ifdef TEST_FRAMEWORK
10223 AST_TEST_REGISTER(eventfilter_test_creation);
10224 AST_TEST_REGISTER(eventfilter_test_matching);
10225 AST_TEST_REGISTER(originate_permissions_test);
10226 #endif
10227 return rc;
10228 }
10229
10230 static int reload_module(void)
10231 {
10232 return __init_manager(1, 0) ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_SUCCESS;
10233 }
10234
10235 int astman_datastore_add(struct mansession *s, struct ast_datastore *datastore)
10236 {
10237 AST_LIST_INSERT_HEAD(&s->session->datastores, datastore, entry);
10238
10239 return 0;
10240 }
10241
10242 int astman_datastore_remove(struct mansession *s, struct ast_datastore *datastore)
10243 {
10244 return AST_LIST_REMOVE(&s->session->datastores, datastore, entry) ? 0 : -1;
10245 }
10246
10247 struct ast_datastore *astman_datastore_find(struct mansession *s, const struct ast_datastore_info *info, const char *uid)
10248 {
10249 struct ast_datastore *datastore = NULL;
10250
10251 if (info == NULL)
10252 return NULL;
10253
10254 AST_LIST_TRAVERSE_SAFE_BEGIN(&s->session->datastores, datastore, entry) {
10255 if (datastore->info != info) {
10256 continue;
10257 }
10258
10259 if (uid == NULL) {
10260 /* matched by type only */
10261 break;
10262 }
10263
10264 if ((datastore->uid != NULL) && !strcasecmp(uid, datastore->uid)) {
10265 /* Matched by type AND uid */
10266 break;
10267 }
10268 }
10269 AST_LIST_TRAVERSE_SAFE_END;
10270
10271 return datastore;
10272 }
10273
10274 int ast_str_append_event_header(struct ast_str **fields_string,
10275 const char *header, const char *value)
10276 {
10277 if (!*fields_string) {
10278 *fields_string = ast_str_create(128);
10279 if (!*fields_string) {
10280 return -1;
10281 }
10282 }
10283
10284 return (ast_str_append(fields_string, 0, "%s: %s\r\n", header, value) < 0) ? -1 : 0;
10285 }
10286
10287 static void manager_event_blob_dtor(void *obj)
10288 {
10289 struct ast_manager_event_blob *ev = obj;
10290
10291 ast_string_field_free_memory(ev);
10292 }
10293
10294 struct ast_manager_event_blob *
10295 __attribute__((format(printf, 3, 4)))
10296 ast_manager_event_blob_create(
10297 int event_flags,
10298 const char *manager_event,
10299 const char *extra_fields_fmt,
10300 ...)
10301 {
10302 struct ast_manager_event_blob *ev;
10303 va_list argp;
10304
10305 ast_assert(extra_fields_fmt != NULL);
10306 ast_assert(manager_event != NULL);
10307
10308 ev = ao2_alloc_options(sizeof(*ev), manager_event_blob_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
10309 if (!ev) {
10310 return NULL;
10311 }
10312
10313 if (ast_string_field_init(ev, 20)) {
10314 ao2_ref(ev, -1);
10315 return NULL;
10316 }
10317
10318 ev->manager_event = manager_event;
10319 ev->event_flags = event_flags;
10320
10321 va_start(argp, extra_fields_fmt);
10322 ast_string_field_ptr_build_va(ev, &ev->extra_fields, extra_fields_fmt, argp);
10323 va_end(argp);
10324
10325 return ev;
10326 }
10327
10328 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Asterisk Manager Interface",
10329 .support_level = AST_MODULE_SUPPORT_CORE,
10330 .load = load_module,
10331 .unload = unload_module,
10332 .reload = reload_module,
10333 .load_pri = AST_MODPRI_CORE,
10334 .requires = "extconfig,acl,http",
10335 );