2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
7 * Russell Bryant <russell@digium.com>
9 * See http://www.asterisk.org for more information about
10 * the Asterisk project. Please do not directly contact
11 * any of the maintainers of this project for assistance;
12 * the project provides a web site, mailing lists and IRC
13 * channels for your use.
15 * This program is free software, distributed under the terms of
16 * the GNU General Public License Version 2. See the LICENSE file
17 * at the top of the source tree.
22 * \brief Device state management
24 * \author Mark Spencer <markster@digium.com>
25 * \author Russell Bryant <russell@digium.com>
27 * \arg \ref AstExtState
30 /*! \page AstExtState Extension and device states in Asterisk
32 * (Note that these descriptions of device states and extension
33 * states have not been updated to the way things work
36 * Asterisk has an internal system that reports states
37 * for an extension. By using the dialplan priority -1,
38 * also called a \b hint, a connection can be made from an
39 * extension to one or many devices. The state of the extension
40 * now depends on the combined state of the devices.
42 * The device state is basically based on the current calls.
43 * If the devicestate engine can find a call from or to the
44 * device, it's in use.
46 * Some channel drivers implement a callback function for
47 * a better level of reporting device states. The SIP channel
48 * has a complicated system for this, which is improved
49 * by adding call limits to the configuration.
51 * Functions that want to check the status of an extension
52 * register themself as a \b watcher.
53 * Watchers in this system can subscribe either to all extensions
54 * or just a specific extensions.
56 * For non-device related states, there's an API called
57 * devicestate providers. This is an extendible system for
58 * delivering state information from outside sources or
59 * functions within Asterisk. Currently we have providers
60 * for app_meetme.c - the conference bridge - and call
61 * parking (metermaids).
63 * There are manly three subscribers to extension states
65 * - AMI, the manager interface
66 * - app_queue.c - the Queue dialplan application
67 * - SIP subscriptions, a.k.a. "blinking lamps" or
70 * The CLI command "show hints" show last known state
72 * \note None of these handle user states, like an IM presence
73 * system. res_jabber.c can subscribe and watch such states
74 * in jabber/xmpp based systems.
76 * \section AstDevStateArch Architecture for devicestates
78 * When a channel driver or asterisk app changes state for
79 * a watched object, it alerts the core. The core queues
80 * a change. When the change is processed, there's a query
81 * sent to the channel driver/provider if there's a function
82 * to handle that, otherwise a channel walk is issued to find
83 * a channel that involves the object.
85 * The changes are queued and processed by a separate thread.
86 * This thread calls the watchers subscribing to status
87 * changes for the object. For manager, this results
88 * in events. For SIP, NOTIFY requests.
91 * \arg \ref devicestate.c
92 * \arg \ref devicestate.h
94 * \section AstExtStateArch Architecture for extension states
96 * Hints are connected to extension. If an extension changes state
97 * it checks the hint devices. If there is a hint, the callbacks into
98 * device states are checked. The aggregated state is set for the hint
102 * \arg \ref AstENUM ast_extension_states
106 * - \ref ast_state_cb struct. Callbacks for watchers
107 * - Callback ast_state_cb_type
108 * - \ref ast_hint struct.
110 * - ast_extension_state_add()
111 * - ast_extension_state_del()
116 #include "asterisk.h"
118 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
120 #include "asterisk/_private.h"
121 #include "asterisk/channel.h"
122 #include "asterisk/utils.h"
123 #include "asterisk/lock.h"
124 #include "asterisk/linkedlists.h"
125 #include "asterisk/devicestate.h"
126 #include "asterisk/pbx.h"
127 #include "asterisk/app.h"
128 #include "asterisk/event.h"
130 /*! \brief Device state strings for printing */
131 static const char *devstatestring[] = {
132 /* 0 AST_DEVICE_UNKNOWN */ "Unknown", /*!< Valid, but unknown state */
133 /* 1 AST_DEVICE_NOT_INUSE */ "Not in use", /*!< Not used */
134 /* 2 AST_DEVICE IN USE */ "In use", /*!< In use */
135 /* 3 AST_DEVICE_BUSY */ "Busy", /*!< Busy */
136 /* 4 AST_DEVICE_INVALID */ "Invalid", /*!< Invalid - not known to Asterisk */
137 /* 5 AST_DEVICE_UNAVAILABLE */ "Unavailable", /*!< Unavailable (not registred) */
138 /* 6 AST_DEVICE_RINGING */ "Ringing", /*!< Ring, ring, ring */
139 /* 7 AST_DEVICE_RINGINUSE */ "Ring+Inuse", /*!< Ring and in use */
140 /* 8 AST_DEVICE_ONHOLD */ "On Hold" /*!< On Hold */
143 /*! \brief A device state provider (not a channel) */
144 struct devstate_prov {
146 ast_devstate_prov_cb_type callback;
147 AST_RWLIST_ENTRY(devstate_prov) list;
150 /*! \brief A list of providers */
151 static AST_RWLIST_HEAD_STATIC(devstate_provs, devstate_prov);
153 struct state_change {
154 AST_LIST_ENTRY(state_change) list;
158 /*! \brief The state change queue. State changes are queued
159 for processing by a separate thread */
160 static AST_LIST_HEAD_STATIC(state_changes, state_change);
162 /*! \brief The device state change notification thread */
163 static pthread_t change_thread = AST_PTHREADT_NULL;
165 /*! \brief Flag for the queue */
166 static ast_cond_t change_pending;
168 /*! \brief Whether or not to cache this device state value */
169 enum devstate_cache {
170 /*! Cache this value as it is coming from a device state provider which is
171 * pushing up state change events to us as they happen */
173 /*! Don't cache this result, since it was pulled from the device state provider.
174 * We only want to cache results from device state providers that are being nice
175 * and pushing state change events up to us as they happen. */
179 struct devstate_change {
180 AST_LIST_ENTRY(devstate_change) entry;
188 struct ast_event_sub *event_sub;
191 AST_LIST_HEAD_NOLOCK(, devstate_change) devstate_change_q;
192 } devstate_collector = {
193 .thread = AST_PTHREADT_NULL,
196 /* Forward declarations */
197 static int getproviderstate(const char *provider, const char *address);
199 /*! \brief Find devicestate as text message for output */
200 const char *devstate2str(enum ast_device_state devstate)
202 return devstatestring[devstate];
205 const char *ast_devstate_str(enum ast_device_state state)
207 const char *res = "UNKNOWN";
210 case AST_DEVICE_UNKNOWN:
212 case AST_DEVICE_NOT_INUSE:
215 case AST_DEVICE_INUSE:
218 case AST_DEVICE_BUSY:
221 case AST_DEVICE_INVALID:
224 case AST_DEVICE_UNAVAILABLE:
227 case AST_DEVICE_RINGING:
230 case AST_DEVICE_RINGINUSE:
233 case AST_DEVICE_ONHOLD:
241 enum ast_device_state ast_devstate_val(const char *val)
243 if (!strcasecmp(val, "NOT_INUSE"))
244 return AST_DEVICE_NOT_INUSE;
245 else if (!strcasecmp(val, "INUSE"))
246 return AST_DEVICE_INUSE;
247 else if (!strcasecmp(val, "BUSY"))
248 return AST_DEVICE_BUSY;
249 else if (!strcasecmp(val, "INVALID"))
250 return AST_DEVICE_INVALID;
251 else if (!strcasecmp(val, "UNAVAILABLE"))
252 return AST_DEVICE_UNAVAILABLE;
253 else if (!strcasecmp(val, "RINGING"))
254 return AST_DEVICE_RINGING;
255 else if (!strcasecmp(val, "RINGINUSE"))
256 return AST_DEVICE_RINGINUSE;
257 else if (!strcasecmp(val, "ONHOLD"))
258 return AST_DEVICE_ONHOLD;
260 return AST_DEVICE_UNKNOWN;
263 /*! \brief Find out if device is active in a call or not
264 \note find channels with the device's name in it
265 This function is only used for channels that does not implement
268 enum ast_device_state ast_parse_device_state(const char *device)
270 struct ast_channel *chan;
271 char match[AST_CHANNEL_NAME];
272 enum ast_device_state res;
274 ast_copy_string(match, device, sizeof(match)-1);
276 chan = ast_get_channel_by_name_prefix_locked(match, strlen(match));
279 return AST_DEVICE_UNKNOWN;
281 if (chan->_state == AST_STATE_RINGING)
282 res = AST_DEVICE_RINGING;
284 res = AST_DEVICE_INUSE;
286 ast_channel_unlock(chan);
291 static enum ast_device_state devstate_cached(const char *device)
293 enum ast_device_state res = AST_DEVICE_UNKNOWN;
294 struct ast_event *event;
296 event = ast_event_get_cached(AST_EVENT_DEVICE_STATE_CHANGE,
297 AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device,
303 res = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
305 ast_event_destroy(event);
310 /*! \brief Check device state through channel specific function or generic function */
311 enum ast_device_state ast_device_state(const char *device)
315 const struct ast_channel_tech *chan_tech;
316 enum ast_device_state res;
317 /*! \brief Channel driver that provides device state */
319 /*! \brief Another provider of device state */
320 char *provider = NULL;
322 /* If the last known state is cached, just return that */
323 res = devstate_cached(device);
324 if (res != AST_DEVICE_UNKNOWN)
327 buf = ast_strdupa(device);
328 tech = strsep(&buf, "/");
329 if (!(number = buf)) {
330 if (!(provider = strsep(&tech, ":")))
331 return AST_DEVICE_INVALID;
332 /* We have a provider */
338 ast_debug(3, "Checking if I can find provider for \"%s\" - number: %s\n", provider, number);
339 return getproviderstate(provider, number);
342 ast_debug(4, "No provider found, checking channel drivers for %s - %s\n", tech, number);
344 if (!(chan_tech = ast_get_channel_tech(tech)))
345 return AST_DEVICE_INVALID;
347 if (!(chan_tech->devicestate)) /* Does the channel driver support device state notification? */
348 return ast_parse_device_state(device); /* No, try the generic function */
350 res = chan_tech->devicestate(number);
352 if (res != AST_DEVICE_UNKNOWN)
355 res = ast_parse_device_state(device);
357 if (res == AST_DEVICE_UNKNOWN)
358 return AST_DEVICE_NOT_INUSE;
363 /*! \brief Add device state provider */
364 int ast_devstate_prov_add(const char *label, ast_devstate_prov_cb_type callback)
366 struct devstate_prov *devprov;
368 if (!callback || !(devprov = ast_calloc(1, sizeof(*devprov))))
371 devprov->callback = callback;
372 ast_copy_string(devprov->label, label, sizeof(devprov->label));
374 AST_RWLIST_WRLOCK(&devstate_provs);
375 AST_RWLIST_INSERT_HEAD(&devstate_provs, devprov, list);
376 AST_RWLIST_UNLOCK(&devstate_provs);
381 /*! \brief Remove device state provider */
382 int ast_devstate_prov_del(const char *label)
384 struct devstate_prov *devcb;
387 AST_RWLIST_WRLOCK(&devstate_provs);
388 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&devstate_provs, devcb, list) {
389 if (!strcasecmp(devcb->label, label)) {
390 AST_RWLIST_REMOVE_CURRENT(list);
396 AST_RWLIST_TRAVERSE_SAFE_END;
397 AST_RWLIST_UNLOCK(&devstate_provs);
402 /*! \brief Get provider device state */
403 static int getproviderstate(const char *provider, const char *address)
405 struct devstate_prov *devprov;
406 int res = AST_DEVICE_INVALID;
408 AST_RWLIST_RDLOCK(&devstate_provs);
409 AST_RWLIST_TRAVERSE(&devstate_provs, devprov, list) {
410 ast_debug(5, "Checking provider %s with %s\n", devprov->label, provider);
412 if (!strcasecmp(devprov->label, provider)) {
413 res = devprov->callback(address);
417 AST_RWLIST_UNLOCK(&devstate_provs);
422 static void devstate_event(const char *device, enum ast_device_state state, enum devstate_cache cache)
424 struct ast_event *event;
426 ast_debug(1, "device '%s' state '%d'\n", device, state);
428 if (!(event = ast_event_new(AST_EVENT_DEVICE_STATE_CHANGE,
429 AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device,
430 AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, state,
431 AST_EVENT_IE_END))) {
435 if (cache == CACHE_ON) {
436 /* Cache this event, replacing an event in the cache with the same
437 * device name if it exists. */
438 ast_event_queue_and_cache(event,
439 AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR,
440 AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, sizeof(struct ast_eid),
443 ast_event_queue(event);
447 /*! Called by the state change thread to find out what the state is, and then
448 * to queue up the state change event */
449 static void do_state_change(const char *device)
451 enum ast_device_state state;
453 state = ast_device_state(device);
455 ast_debug(3, "Changing state for %s - state %d (%s)\n", device, state, devstate2str(state));
457 devstate_event(device, state, CACHE_OFF);
460 static int __ast_devstate_changed_literal(enum ast_device_state state, char *buf, int norecurse)
463 struct state_change *change;
466 ast_debug(3, "Notification of state change to be queued on device/channel %s\n", buf);
470 if (state != AST_DEVICE_UNKNOWN) {
471 devstate_event(device, state, CACHE_ON);
472 } else if (change_thread == AST_PTHREADT_NULL || !(change = ast_calloc(1, sizeof(*change) + strlen(device)))) {
473 /* we could not allocate a change struct, or */
474 /* there is no background thread, so process the change now */
475 do_state_change(device);
477 /* queue the change */
478 strcpy(change->device, device);
479 AST_LIST_LOCK(&state_changes);
480 AST_LIST_INSERT_TAIL(&state_changes, change, list);
481 ast_cond_signal(&change_pending);
482 AST_LIST_UNLOCK(&state_changes);
485 /* The problem with this API is that a device may be called with the unique
486 * identifier appended or not, but it's separated from the channel name
487 * with a '-', which is also a legitimate character in a channel name. So,
488 * we have to force both names to get their names checked for state changes
489 * to ensure that the right one gets notified. Not a huge performance hit,
490 * but it might could be fixed by an enterprising programmer in trunk.
492 if (!norecurse && (tmp = strrchr(device, '-'))) {
494 __ast_devstate_changed_literal(state, device, 1);
500 int ast_devstate_changed_literal(enum ast_device_state state, const char *dev)
504 buf = ast_strdupa(dev);
506 return __ast_devstate_changed_literal(state, buf, 0);
509 int ast_device_state_changed_literal(const char *dev)
513 buf = ast_strdupa(dev);
515 return __ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, buf, 0);
518 int ast_devstate_changed(enum ast_device_state state, const char *fmt, ...)
520 char buf[AST_MAX_EXTENSION];
524 vsnprintf(buf, sizeof(buf), fmt, ap);
527 return __ast_devstate_changed_literal(state, buf, 0);
530 /*! \brief Accept change notification, add it to change queue */
531 int ast_device_state_changed(const char *fmt, ...)
533 char buf[AST_MAX_EXTENSION];
537 vsnprintf(buf, sizeof(buf), fmt, ap);
540 return __ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, buf, 0);
543 /*! \brief Go through the dev state change queue and update changes in the dev state thread */
544 static void *do_devstate_changes(void *data)
546 struct state_change *next, *current;
549 /* This basically pops off any state change entries, resets the list back to NULL, unlocks, and processes each state change */
550 AST_LIST_LOCK(&state_changes);
551 if (AST_LIST_EMPTY(&state_changes))
552 ast_cond_wait(&change_pending, &state_changes.lock);
553 next = AST_LIST_FIRST(&state_changes);
554 AST_LIST_HEAD_INIT_NOLOCK(&state_changes);
555 AST_LIST_UNLOCK(&state_changes);
557 /* Process each state change */
558 while ((current = next)) {
559 next = AST_LIST_NEXT(current, list);
560 do_state_change(current->device);
568 static void destroy_devstate_change(struct devstate_change *sc)
573 #define MAX_SERVERS 64
574 struct change_collection {
575 struct devstate_change states[MAX_SERVERS];
579 static void devstate_cache_cb(const struct ast_event *event, void *data)
581 struct change_collection *collection = data;
583 const struct ast_eid *eid;
585 if (collection->num_states == ARRAY_LEN(collection->states)) {
586 ast_log(LOG_ERROR, "More per-server state values than we have room for (MAX_SERVERS is %d)\n",
591 if (!(eid = ast_event_get_ie_raw(event, AST_EVENT_IE_EID))) {
592 ast_log(LOG_ERROR, "Device state change event with no EID\n");
596 i = collection->num_states;
598 collection->states[i].state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
599 collection->states[i].eid = *eid;
601 collection->num_states++;
604 static void process_collection(const char *device, struct change_collection *collection)
607 struct ast_devstate_aggregate agg;
608 enum ast_device_state state;
609 struct ast_event *event;
611 ast_devstate_aggregate_init(&agg);
613 for (i = 0; i < collection->num_states; i++) {
614 ast_debug(1, "Adding per-server state of '%s' for '%s'\n",
615 devstate2str(collection->states[i].state), device);
616 ast_devstate_aggregate_add(&agg, collection->states[i].state);
619 state = ast_devstate_aggregate_result(&agg);
621 ast_debug(1, "Aggregate devstate result is %d\n", state);
623 event = ast_event_get_cached(AST_EVENT_DEVICE_STATE,
624 AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device,
628 enum ast_device_state old_state;
630 old_state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
632 ast_event_destroy(event);
634 if (state == old_state) {
635 /* No change since last reported device state */
636 ast_debug(1, "Aggregate state for device '%s' has not changed from '%s'\n",
637 device, devstate2str(state));
642 ast_debug(1, "Aggregate state for device '%s' has changed to '%s'\n",
643 device, devstate2str(state));
645 event = ast_event_new(AST_EVENT_DEVICE_STATE,
646 AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device,
647 AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, state,
653 ast_event_queue_and_cache(event,
654 AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR,
658 static void handle_devstate_change(struct devstate_change *sc)
660 struct ast_event_sub *tmp_sub;
661 struct change_collection collection = {
665 ast_debug(1, "Processing device state change for '%s'\n", sc->device);
667 if (!(tmp_sub = ast_event_subscribe_new(AST_EVENT_DEVICE_STATE_CHANGE, devstate_cache_cb, &collection))) {
668 ast_log(LOG_ERROR, "Failed to create subscription\n");
672 if (ast_event_sub_append_ie_str(tmp_sub, AST_EVENT_IE_DEVICE, sc->device)) {
673 ast_log(LOG_ERROR, "Failed to append device IE\n");
674 ast_event_sub_destroy(tmp_sub);
678 /* Populate the collection of device states from the cache */
679 ast_event_dump_cache(tmp_sub);
681 process_collection(sc->device, &collection);
683 ast_event_sub_destroy(tmp_sub);
686 static void *run_devstate_collector(void *data)
689 struct devstate_change *sc;
691 ast_mutex_lock(&devstate_collector.lock);
692 while (!(sc = AST_LIST_REMOVE_HEAD(&devstate_collector.devstate_change_q, entry)))
693 ast_cond_wait(&devstate_collector.cond, &devstate_collector.lock);
694 ast_mutex_unlock(&devstate_collector.lock);
696 handle_devstate_change(sc);
698 destroy_devstate_change(sc);
704 static void devstate_change_collector_cb(const struct ast_event *event, void *data)
706 struct devstate_change *sc;
708 const struct ast_eid *eid;
711 device = ast_event_get_ie_str(event, AST_EVENT_IE_DEVICE);
712 eid = ast_event_get_ie_raw(event, AST_EVENT_IE_EID);
713 state = ast_event_get_ie_uint(event, AST_EVENT_IE_STATE);
715 if (ast_strlen_zero(device) || !eid) {
716 ast_log(LOG_ERROR, "Invalid device state change event received\n");
720 if (!(sc = ast_calloc(1, sizeof(*sc) + strlen(device))))
723 strcpy(sc->device, device);
727 ast_mutex_lock(&devstate_collector.lock);
728 AST_LIST_INSERT_TAIL(&devstate_collector.devstate_change_q, sc, entry);
729 ast_cond_signal(&devstate_collector.cond);
730 ast_mutex_unlock(&devstate_collector.lock);
733 /*! \brief Initialize the device state engine in separate thread */
734 int ast_device_state_engine_init(void)
736 devstate_collector.event_sub = ast_event_subscribe(AST_EVENT_DEVICE_STATE_CHANGE,
737 devstate_change_collector_cb, NULL, AST_EVENT_IE_END);
739 if (!devstate_collector.event_sub) {
740 ast_log(LOG_ERROR, "Failed to create subscription for the device state change collector\n");
744 ast_mutex_init(&devstate_collector.lock);
745 ast_cond_init(&devstate_collector.cond, NULL);
746 if (ast_pthread_create_background(&devstate_collector.thread, NULL, run_devstate_collector, NULL) < 0) {
747 ast_log(LOG_ERROR, "Unable to start device state collector thread.\n");
751 ast_cond_init(&change_pending, NULL);
752 if (ast_pthread_create_background(&change_thread, NULL, do_devstate_changes, NULL) < 0) {
753 ast_log(LOG_ERROR, "Unable to start device state change thread.\n");
760 void ast_devstate_aggregate_init(struct ast_devstate_aggregate *agg)
762 memset(agg, 0, sizeof(*agg));
764 agg->all_unavail = 1;
767 agg->all_on_hold = 1;
770 void ast_devstate_aggregate_add(struct ast_devstate_aggregate *agg, enum ast_device_state state)
773 case AST_DEVICE_NOT_INUSE:
774 agg->all_unavail = 0;
776 agg->all_on_hold = 0;
778 case AST_DEVICE_INUSE:
781 agg->all_unavail = 0;
783 agg->all_on_hold = 0;
785 case AST_DEVICE_RINGING:
788 agg->all_unavail = 0;
790 agg->all_on_hold = 0;
792 case AST_DEVICE_RINGINUSE:
796 agg->all_unavail = 0;
798 agg->all_on_hold = 0;
800 case AST_DEVICE_ONHOLD:
801 agg->all_unavail = 0;
804 case AST_DEVICE_BUSY:
805 agg->all_unavail = 0;
807 agg->all_on_hold = 0;
810 case AST_DEVICE_UNAVAILABLE:
811 case AST_DEVICE_INVALID:
814 agg->all_on_hold = 0;
816 case AST_DEVICE_UNKNOWN:
821 enum ast_device_state ast_devstate_aggregate_result(struct ast_devstate_aggregate *agg)
824 return AST_DEVICE_NOT_INUSE;
826 if (agg->all_on_hold)
827 return AST_DEVICE_ONHOLD;
830 return AST_DEVICE_BUSY;
832 if (agg->all_unavail)
833 return AST_DEVICE_UNAVAILABLE;
836 return agg->in_use ? AST_DEVICE_RINGINUSE : AST_DEVICE_RINGING;
839 return AST_DEVICE_INUSE;
842 return AST_DEVICE_BUSY;
844 return AST_DEVICE_NOT_INUSE;