Skip to content
Snippets Groups Projects
cdr.c 137 KiB
Newer Older
  • Learn to ignore specific revisions
  • Mark Spencer's avatar
    Mark Spencer committed
    /*
    
     * Asterisk -- An open source telephony toolkit.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Copyright (C) 1999 - 2006, Digium, Inc.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * Mark Spencer <markster@digium.com>
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * See http://www.asterisk.org for more information about
     * the Asterisk project. Please do not directly contact
     * any of the maintainers of this project for assistance;
     * the project provides a web site, mailing lists and IRC
     * channels for your use.
     *
    
    Mark Spencer's avatar
    Mark Spencer committed
     * This program is free software, distributed under the terms of
    
     * the GNU General Public License Version 2. See the LICENSE file
     * at the top of the source tree.
     */
    
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * \brief Call Detail Record API
    
     *
     * \author Mark Spencer <markster@digium.com>
    
    Russell Bryant's avatar
    Russell Bryant committed
     * \note Includes code and algorithms from the Zapata library.
    
    Mark Spencer's avatar
    Mark Spencer committed
     *
    
     * \note We do a lot of checking here in the CDR code to try to be sure we don't ever let a CDR slip
     * through our fingers somehow.  If someone allocates a CDR, it must be completely handled normally
     * or a WARNING shall be logged, so that we can best keep track of any escape condition where the CDR
     * isn't properly generated and posted.
    
    /*! \li \ref cdr.c uses the configuration file \ref cdr.conf
     * \addtogroup configuration_file Configuration Files
     */
    
    /*!
     * \page cdr.conf cdr.conf
     * \verbinclude cdr.conf.sample
     */
    
    /*** MODULEINFO
    	<support_level>core</support_level>
     ***/
    
    
    ASTERISK_REGISTER_FILE()
    
    #include "asterisk/lock.h"
    #include "asterisk/channel.h"
    #include "asterisk/cdr.h"
    #include "asterisk/callerid.h"
    
    #include "asterisk/manager.h"
    
    Kevin P. Fleming's avatar
    Kevin P. Fleming committed
    #include "asterisk/linkedlists.h"
    
    #include "asterisk/sched.h"
    #include "asterisk/config.h"
    #include "asterisk/cli.h"
    
    #include "asterisk/stringfields.h"
    
    #include "asterisk/config_options.h"
    #include "asterisk/json.h"
    
    #include "asterisk/parking.h"
    
    #include "asterisk/stasis.h"
    #include "asterisk/stasis_channels.h"
    
    #include "asterisk/stasis_bridges.h"
    
    #include "asterisk/stasis_message_router.h"
    #include "asterisk/astobj2.h"
    
    	<configInfo name="cdr" language="en_US">
    		<synopsis>Call Detail Record configuration</synopsis>
    		<description>
    			<para>CDR is Call Detail Record, which provides logging services via a variety of
    			pluggable backend modules. Detailed call information can be recorded to
    			databases, files, etc. Useful for billing, fraud prevention, compliance with
    			Sarbanes-Oxley aka The Enron Act, QOS evaluations, and more.</para>
    		</description>
    		<configFile name="cdr.conf">
    			<configObject name="general">
    				<synopsis>Global settings applied to the CDR engine.</synopsis>
    				<configOption name="debug">
    					<synopsis>Enable/disable verbose CDR debugging.</synopsis>
    					<description><para>When set to <literal>True</literal>, verbose updates
    					of changes in CDR information will be logged. Note that this is only
    					of use when debugging CDR behavior.</para>
    					</description>
    				</configOption>
    				<configOption name="enable">
    					<synopsis>Enable/disable CDR logging.</synopsis>
    					<description><para>Define whether or not to use CDR logging. Setting this to "no" will override
    					any loading of backend CDR modules.  Default is "yes".</para>
    					</description>
    				</configOption>
    				<configOption name="unanswered">
    
    					<synopsis>Log calls that are never answered and don't set an outgoing party.</synopsis>
    					<description><para>
    					Define whether or not to log unanswered calls that don't involve an outgoing party. Setting
    					this to "yes" will make calls to extensions that don't answer and don't set a side B channel
    					(such as by using the Dial application) receive CDR log entries. If this option is set to
    					"no", then those log entries will not be created. Unanswered calls which get offered to an
    					outgoing line will always receive log entries regardless of this option, and that is the
    					intended behavior.
    					</para>
    
    					</description>
    				</configOption>
    				<configOption name="congestion">
    					<synopsis>Log congested calls.</synopsis>
    					<description><para>Define whether or not to log congested calls. Setting this to "yes" will
    					report each call that fails to complete due to congestion conditions.</para>
    					</description>
    				</configOption>
    				<configOption name="endbeforehexten">
    
    					<synopsis>Don't produce CDRs while executing hangup logic</synopsis>
    					<description>
    						<para>As each CDR for a channel is finished, its end time is updated
    						and the CDR is finalized. When a channel is hung up and hangup
    						logic is present (in the form of a hangup handler or the
    						<literal>h</literal> extension), a new CDR is generated for the
    						channel. Any statistics are gathered from this new CDR. By enabling
    						this option, no new CDR is created for the dialplan logic that is
    						executed in <literal>h</literal> extensions or attached hangup handler
    
    						subroutines. The default value is <literal>yes</literal>, indicating
    
    						that a CDR will be generated during hangup logic.</para>
    
    					</description>
    				</configOption>
    				<configOption name="initiatedseconds">
    					<synopsis>Count microseconds for billsec purposes</synopsis>
    					<description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
    					is simply the end time (hangup time) minus the answer time in seconds. Internally,
    					asterisk stores the time in terms of microseconds and seconds. By setting
    					initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
    					that were initiated (a sort of round up method). Technically, this is
    					when the microsecond part of the end time is greater than the microsecond
    					part of the answer time, then the billsec time is incremented one second.</para>
    					</description>
    				</configOption>
    				<configOption name="batch">
    					<synopsis>Submit CDRs to the backends for processing in batches</synopsis>
    					<description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
    					every call, the data will be stored in a buffer to help alleviate load on the
    					asterisk server.</para>
    					<warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
    					i.e., software crash, power failure, kill -9, etc.</para>
    					</warning>
    					</description>
    				</configOption>
    				<configOption name="size">
    					<synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
    					<description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
    					them to the backend engines. batch must be set to <literal>yes</literal>.</para>
    					</description>
    				</configOption>
    				<configOption name="time">
    					<synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
    					<description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
    					backend engines. If this time limit is reached, then it will post the records, regardless of the value
    					defined for size. batch must be set to <literal>yes</literal>.</para>
    					<note><para>Time is expressed in seconds.</para></note>
    					</description>
    				</configOption>
    				<configOption name="scheduleronly">
    					<synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
    					<description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
    					records.  Posting can either occur inside the scheduler thread, or a new
    					thread can be spawned for the submission of every batch.  For small batches,
    					it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
    					For large batches, say anything over size=10, a new thread is recommended, so
    					set this to <literal>no</literal>.</para>
    					</description>
    				</configOption>
    				<configOption name="safeshutdown">
    					<synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
    					<description><para>When shutting down asterisk, you can block until the CDRs are submitted.  If
    					you don't, then data will likely be lost.  You can always check the size of
    					the CDR batch buffer with the CLI <astcli>cdr status</astcli> command.  To enable blocking on
    					submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
    					</description>
    				</configOption>
    			</configObject>
    		</configFile>
    	</configInfo>
    
    /* The prime here should be similar in size to the channel container. */
    #ifdef LOW_MEMORY
    #define NUM_CDR_BUCKETS 61
    #else
    #define NUM_CDR_BUCKETS 769
    #endif
    
    
    #define DEFAULT_ENABLED "1"
    #define DEFAULT_BATCHMODE "0"
    #define DEFAULT_UNANSWERED "0"
    #define DEFAULT_CONGESTION "0"
    
    #define DEFAULT_END_BEFORE_H_EXTEN "1"
    
    #define DEFAULT_INITIATED_SECONDS "0"
    
    #define DEFAULT_BATCH_SIZE "100"
    #define MAX_BATCH_SIZE 1000
    #define DEFAULT_BATCH_TIME "300"
    #define MAX_BATCH_TIME 86400
    #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
    #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
    
    #define CDR_DEBUG(mod_cfg, fmt, ...) \
    	do { \
    
    		if (ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG)) { \
    			ast_verbose((fmt), ##__VA_ARGS__); \
    		} \
    	} while (0)
    
    
    static void cdr_detach(struct ast_cdr *cdr);
    static void cdr_submit_batch(int shutdown);
    
    static int cdr_toggle_runtime_options(void);
    
    
    /*! \brief The configuration settings for this module */
    struct module_config {
    	struct ast_cdr_config *general;		/*< CDR global settings */
    };
    
    /*! \brief The container for the module configuration */
    static AO2_GLOBAL_OBJ_STATIC(module_configs);
    
    /*! \brief The type definition for general options */
    static struct aco_type general_option = {
    	.type = ACO_GLOBAL,
    	.name = "general",
    	.item_offset = offsetof(struct module_config, general),
    	.category = "^general$",
    	.category_match = ACO_WHITELIST,
    };
    
    static void *module_config_alloc(void);
    static void module_config_destructor(void *obj);
    
    /*! \brief The file definition */
    static struct aco_file module_file_conf = {
    	.filename = "cdr.conf",
    	.skip_category = "(^csv$|^custom$|^manager$|^odbc$|^pgsql$|^radius$|^sqlite$|^tds$|^mysql$)",
    	.types = ACO_TYPES(&general_option),
    };
    
    CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
    	.files = ACO_FILES(&module_file_conf),
    );
    
    static struct aco_type *general_options[] = ACO_TYPES(&general_option);
    
    /*! \brief Dispose of a module config object */
    static void module_config_destructor(void *obj)
    {
    	struct module_config *cfg = obj;
    
    	if (!cfg) {
    		return;
    	}
    	ao2_ref(cfg->general, -1);
    }
    
    /*! \brief Create a new module config object */
    static void *module_config_alloc(void)
    {
    	struct module_config *mod_cfg;
    	struct ast_cdr_config *cdr_config;
    
    	mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
    	if (!mod_cfg) {
    		return NULL;
    	}
    
    	cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
    	if (!cdr_config) {
    		ao2_ref(cdr_config, -1);
    		return NULL;
    	}
    	mod_cfg->general = cdr_config;
    
    	return mod_cfg;
    }
    
    /*! \brief Registration object for CDR backends */
    struct cdr_beitem {
    
    Mark Spencer's avatar
    Mark Spencer committed
    	char name[20];
    	char desc[80];
    	ast_cdrbe be;
    
    	AST_RWLIST_ENTRY(cdr_beitem) list;
    
    };
    
    /*! \brief List of registered backends */
    static AST_RWLIST_HEAD_STATIC(be_list, cdr_beitem);
    
    
    /*! \brief List of registered modifiers */
    static AST_RWLIST_HEAD_STATIC(mo_list, cdr_beitem);
    
    
    /*! \brief Queued CDR waiting to be batched */
    struct cdr_batch_item {
    	struct ast_cdr *cdr;
    	struct cdr_batch_item *next;
    };
    
    /*! \brief The actual batch queue */
    static struct cdr_batch {
    	int size;
    	struct cdr_batch_item *head;
    	struct cdr_batch_item *tail;
    } *batch = NULL;
    
    /*! \brief The global sequence counter used for CDRs */
    static int global_cdr_sequence =  0;
    
    /*! \brief Scheduler items */
    static struct ast_sched_context *sched;
    static int cdr_sched = -1;
    AST_MUTEX_DEFINE_STATIC(cdr_sched_lock);
    static pthread_t cdr_thread = AST_PTHREADT_NULL;
    
    /*! \brief Lock protecting modifications to the batch queue */
    AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
    
    /*! \brief These are used to wake up the CDR thread when there's work to do */
    AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
    static ast_cond_t cdr_pending_cond;
    
    
    /*! \brief A container of the active CDRs indexed by Party A channel id */
    
    static struct ao2_container *active_cdrs_by_channel;
    
    /*! \brief Message router for stasis messages regarding channel state */
    static struct stasis_message_router *stasis_router;
    
    /*! \brief Our subscription for bridges */
    
    static struct stasis_forward *bridge_subscription;
    
    
    /*! \brief Our subscription for channels */
    
    static struct stasis_forward *channel_subscription;
    
    /*! \brief Our subscription for parking */
    
    static struct stasis_forward *parking_subscription;
    
    /*! \brief The parent topic for all topics we want to aggregate for CDRs */
    static struct stasis_topic *cdr_topic;
    
    
    /*! \brief A message type used to synchronize with the CDR topic */
    STASIS_MESSAGE_TYPE_DEFN_LOCAL(cdr_sync_message_type);
    
    
    /*! \brief Return types for \ref process_bridge_enter functions */
    enum process_bridge_enter_results {
    	/*!
    	 * The CDR was the only party in the bridge.
    	 */
    	BRIDGE_ENTER_ONLY_PARTY,
    	/*!
    	 * The CDR was able to obtain a Party B from some other party already in the bridge
    	 */
    	BRIDGE_ENTER_OBTAINED_PARTY_B,
    	/*!
    	 * The CDR was not able to obtain a Party B
    	 */
    	BRIDGE_ENTER_NO_PARTY_B,
    	/*!
    	 * This CDR can't handle a bridge enter message and a new CDR needs to be created
    	 */
    	BRIDGE_ENTER_NEED_CDR,
    };
    
    
    /*!
     * \brief A virtual table used for \ref cdr_object.
     *
     * Note that all functions are optional - if a subclass does not need an
     * implementation, it is safe to leave it NULL.
     */
    struct cdr_object_fn_table {
    	/*! \brief Name of the subclass */
    	const char *name;
    
    	/*!
    	 * \brief An initialization function. This will be called automatically
    	 * when a \ref cdr_object is switched to this type in
    	 * \ref cdr_object_transition_state
    	 *
    	 * \param cdr The \ref cdr_object that was just transitioned
    	 */
    	void (* const init_function)(struct cdr_object *cdr);
    
    	/*!
    	 * \brief Process a Party A update for the \ref cdr_object
    	 *
    	 * \param cdr The \ref cdr_object to process the update
    	 * \param snapshot The snapshot for the CDR's Party A
    	 * \retval 0 the CDR handled the update or ignored it
    	 * \retval 1 the CDR is finalized and a new one should be made to handle it
    	 */
    	int (* const process_party_a)(struct cdr_object *cdr,
    			struct ast_channel_snapshot *snapshot);
    
    	/*!
    	 * \brief Process a Party B update for the \ref cdr_object
    	 *
    	 * \param cdr The \ref cdr_object to process the update
    	 * \param snapshot The snapshot for the CDR's Party B
    	 */
    	void (* const process_party_b)(struct cdr_object *cdr,
    			struct ast_channel_snapshot *snapshot);
    
    	/*!
    	 * \brief Process the beginning of a dial. A dial message implies one of two
    	 * things:
    	 * The \ref cdr_object's Party A has been originated
    	 * The \ref cdr_object's Party A is dialing its Party B
    	 *
    	 * \param cdr The \ref cdr_object
    	 * \param caller The originator of the dial attempt
    	 * \param peer The destination of the dial attempt
    	 *
    	 * \retval 0 if the parties in the dial were handled by this CDR
    	 * \retval 1 if the parties could not be handled by this CDR
    	 */
    	int (* const process_dial_begin)(struct cdr_object *cdr,
    			struct ast_channel_snapshot *caller,
    			struct ast_channel_snapshot *peer);
    
    	/*!
    	 * \brief Process the end of a dial. At the end of a dial, a CDR can be
    	 * transitioned into one of two states - DialedPending
    	 * (\ref dialed_pending_state_fn_table) or Finalized
    	 * (\ref finalized_state_fn_table).
    	 *
    	 * \param cdr The \ref cdr_object
    	 * \param caller The originator of the dial attempt
    	 * \param peer the Destination of the dial attempt
    	 * \param dial_status What happened
    	 *
    	 * \retval 0 if the parties in the dial were handled by this CDR
    	 * \retval 1 if the parties could not be handled by this CDR
    	 */
    	int (* const process_dial_end)(struct cdr_object *cdr,
    			struct ast_channel_snapshot *caller,
    			struct ast_channel_snapshot *peer,
    			const char *dial_status);
    
    	/*!
    	 * \brief Process the entering of a bridge by this CDR. The purpose of this
    	 * callback is to have the CDR prepare itself for the bridge and attempt to
    	 * find a valid Party B. The act of creating new CDRs based on the entering
    	 * of this channel into the bridge is handled by the higher level message
    	 * handler.
    	 *
    
    	 * Note that this handler is for when a channel enters into a "normal"
    	 * bridge, where people actually talk to each other. Parking is its own
    	 * thing.
    	 *
    
    	 * \param cdr The \ref cdr_object
    	 * \param bridge The bridge that the Party A just entered into
    	 * \param channel The \ref ast_channel_snapshot for this CDR's Party A
    	 *
    
    	 * \retval process_bridge_enter_results Defines whether or not this CDR was able
    	 * to fully handle the bridge enter message.
    
    	enum process_bridge_enter_results (* const process_bridge_enter)(
    			struct cdr_object *cdr,
    
    			struct ast_bridge_snapshot *bridge,
    			struct ast_channel_snapshot *channel);
    
    
    	/*!
    	 * \brief Process entering into a parking bridge.
    	 *
    	 * \param cdr The \ref cdr_object
    	 * \param bridge The parking bridge that Party A just entered into
    	 * \param channel The \ref ast_channel_snapshot for this CDR's Party A
    	 *
    	 * \retval 0 This CDR successfully transitioned itself into the parked state
    	 * \retval 1 This CDR couldn't handle the parking transition and we need a
    	 *  new CDR.
    	 */
    	int (* const process_parking_bridge_enter)(struct cdr_object *cdr,
    			struct ast_bridge_snapshot *bridge,
    			struct ast_channel_snapshot *channel);
    
    
    	/*!
    	 * \brief Process the leaving of a bridge by this CDR.
    	 *
    	 * \param cdr The \ref cdr_object
    	 * \param bridge The bridge that the Party A just left
    	 * \param channel The \ref ast_channel_snapshot for this CDR's Party A
    	 *
    	 * \retval 0 This CDR left successfully
    	 * \retval 1 Error
    	 */
    	int (* const process_bridge_leave)(struct cdr_object *cdr,
    			struct ast_bridge_snapshot *bridge,
    			struct ast_channel_snapshot *channel);
    
    
    	/*!
    	 * \brief Process an update informing us that the channel got itself parked
    	 *
    	 * \param cdr The \ref cdr_object
    	 * \param channel The parking information for this CDR's party A
    	 *
    	 * \retval 0 This CDR successfully parked itself
    	 * \retval 1 This CDR couldn't handle the park
    	 */
    	int (* const process_parked_channel)(struct cdr_object *cdr,
    			struct ast_parked_call_payload *parking_info);
    
    };
    
    static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
    
    static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
    
    static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info);
    
    
    static void single_state_init_function(struct cdr_object *cdr);
    static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
    static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
    
    static enum process_bridge_enter_results single_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    
    /*!
     * \brief The virtual table for the Single state.
     *
     * A \ref cdr_object starts off in this state. This represents a channel that
     * has no Party B information itself.
     *
     * A \ref cdr_object from this state can go into any of the following states:
     * * \ref dial_state_fn_table
     * * \ref bridge_state_fn_table
     * * \ref finalized_state_fn_table
     */
    struct cdr_object_fn_table single_state_fn_table = {
    	.name = "Single",
    	.init_function = single_state_init_function,
    	.process_party_a = base_process_party_a,
    	.process_party_b = single_state_process_party_b,
    	.process_dial_begin = single_state_process_dial_begin,
    	.process_dial_end = base_process_dial_end,
    	.process_bridge_enter = single_state_process_bridge_enter,
    
    	.process_parking_bridge_enter = single_state_process_parking_bridge_enter,
    
    	.process_bridge_leave = base_process_bridge_leave,
    
    	.process_parked_channel = base_process_parked_channel,
    
    };
    
    static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
    static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
    static int dial_state_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
    
    static enum process_bridge_enter_results dial_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    
    /*!
     * \brief The virtual table for the Dial state.
     *
     * A \ref cdr_object that has begun a dial operation. This state is entered when
     * the Party A for a CDR is determined to be dialing out to a Party B or when
     * a CDR is for an originated channel (in which case the Party A information is
     * the originated channel, and there is no Party B).
     *
     * A \ref cdr_object from this state can go in any of the following states:
     * * \ref dialed_pending_state_fn_table
     * * \ref bridge_state_fn_table
     * * \ref finalized_state_fn_table
     */
    struct cdr_object_fn_table dial_state_fn_table = {
    	.name = "Dial",
    	.process_party_a = base_process_party_a,
    	.process_party_b = dial_state_process_party_b,
    	.process_dial_begin = dial_state_process_dial_begin,
    	.process_dial_end = dial_state_process_dial_end,
    	.process_bridge_enter = dial_state_process_bridge_enter,
    	.process_bridge_leave = base_process_bridge_leave,
    };
    
    static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
    static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
    
    static enum process_bridge_enter_results dialed_pending_state_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    
    /*!
     * \brief The virtual table for the Dialed Pending state.
     *
     * A \ref cdr_object that has successfully finished a dial operation, but we
     * don't know what they're going to do yet. It's theoretically possible to dial
     * a party and then have that party not be bridged with the caller; likewise,
     * an origination can complete and the channel go off and execute dialplan. The
     * pending state acts as a bridge between either:
     * * Entering a bridge
     * * Getting a new CDR for new dialplan execution
     * * Switching from being originated to executing dialplan
     *
     * A \ref cdr_object from this state can go in any of the following states:
     * * \ref single_state_fn_table
     * * \ref dialed_pending_state_fn_table
     * * \ref bridge_state_fn_table
     * * \ref finalized_state_fn_table
     */
    struct cdr_object_fn_table dialed_pending_state_fn_table = {
    	.name = "DialedPending",
    	.process_party_a = dialed_pending_state_process_party_a,
    	.process_dial_begin = dialed_pending_state_process_dial_begin,
    	.process_bridge_enter = dialed_pending_state_process_bridge_enter,
    
    	.process_parking_bridge_enter = dialed_pending_state_process_parking_bridge_enter,
    
    	.process_bridge_leave = base_process_bridge_leave,
    
    	.process_parked_channel = base_process_parked_channel,
    
    };
    
    static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
    static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    /*!
     * \brief The virtual table for the Bridged state
     *
     * A \ref cdr_object enters this state when it receives notification that the
     * channel has entered a bridge.
     *
     * A \ref cdr_object from this state can go to:
     * * \ref finalized_state_fn_table
     */
    struct cdr_object_fn_table bridge_state_fn_table = {
    	.name = "Bridged",
    	.process_party_a = base_process_party_a,
    	.process_party_b = bridge_state_process_party_b,
    	.process_bridge_leave = bridge_state_process_bridge_leave,
    
    	.process_parked_channel = base_process_parked_channel,
    
    static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
    
    /*!
     * \brief The virtual table for the Parked state
     *
     * Parking is weird. Unlike typical bridges, it has to be treated somewhat
     * uniquely - a channel in a parking bridge (which is a subclass of a holding
     * bridge) has to be handled as if the channel went into an application.
     * However, when the channel comes out, we need a new CDR - unlike the Single
     * state.
     */
    struct cdr_object_fn_table parked_state_fn_table = {
    	.name = "Parked",
    	.process_party_a = base_process_party_a,
    	.process_bridge_leave = parked_state_process_bridge_leave,
    	.process_parked_channel = base_process_parked_channel,
    
    };
    
    static void finalized_state_init_function(struct cdr_object *cdr);
    static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
    
    /*!
     * \brief The virtual table for the finalized state.
     *
     * Once in the finalized state, the CDR is done. No modifications can be made
     * to the CDR.
     */
    struct cdr_object_fn_table finalized_state_fn_table = {
    	.name = "Finalized",
    	.init_function = finalized_state_init_function,
    	.process_party_a = finalized_state_process_party_a,
    
    	.process_bridge_enter = base_process_bridge_enter,
    
    };
    
    /*! \brief A wrapper object around a snapshot.
     * Fields that are mutable by the CDR engine are replicated here.
     */
    struct cdr_object_snapshot {
    	struct ast_channel_snapshot *snapshot;  /*!< The channel snapshot */
    	char userfield[AST_MAX_USER_FIELD];     /*!< Userfield for the channel */
    	unsigned int flags;                     /*!< Specific flags for this party */
    	struct varshead variables;              /*!< CDR variables for the channel */
    };
    
    /*! \brief An in-memory representation of an active CDR */
    struct cdr_object {
    	struct cdr_object_snapshot party_a;     /*!< The Party A information */
    	struct cdr_object_snapshot party_b;     /*!< The Party B information */
    	struct cdr_object_fn_table *fn_table;   /*!< The current virtual table */
    
    	enum ast_cdr_disposition disposition;   /*!< The disposition of the CDR */
    	struct timeval start;                   /*!< When this CDR was created */
    	struct timeval answer;                  /*!< Either when the channel was answered, or when the path between channels was established */
    	struct timeval end;                     /*!< When this CDR was finalized */
    	unsigned int sequence;                  /*!< A monotonically increasing number for each CDR */
    	struct ast_flags flags;                 /*!< Flags on the CDR */
    	AST_DECLARE_STRING_FIELDS(
    		AST_STRING_FIELD(linkedid);         /*!< Linked ID. Cached here as it may change out from party A, which must be immutable */
    
    		AST_STRING_FIELD(uniqueid);			/*!< Unique id of party A. Cached here as it is the primary key of this CDR */
    
    		AST_STRING_FIELD(name);             /*!< Channel name of party A. Cached here as the party A address may change */
    		AST_STRING_FIELD(bridge);           /*!< The bridge the party A happens to be in. */
    		AST_STRING_FIELD(appl);             /*!< The last accepted application party A was in */
    		AST_STRING_FIELD(data);             /*!< The data for the last accepted application party A was in */
    
    		AST_STRING_FIELD(context);          /*!< The accepted context for Party A */
    		AST_STRING_FIELD(exten);            /*!< The accepted extension for Party A */
    
    	);
    	struct cdr_object *next;                /*!< The next CDR object in the chain */
    	struct cdr_object *last;                /*!< The last CDR object in the chain */
    };
    
    /*!
     * \brief Copy variables from one list to another
     * \param to_list destination
     * \param from_list source
     * \retval The number of copied variables
     */
    static int copy_variables(struct varshead *to_list, struct varshead *from_list)
    {
    
    	struct ast_var_t *variables;
    	struct ast_var_t *newvariable;
    	const char *var;
    	const char *val;
    
    	int x = 0;
    
    	AST_LIST_TRAVERSE(from_list, variables, entries) {
    
    		var = ast_var_name(variables);
    		if (ast_strlen_zero(var)) {
    			continue;
    		}
    		val = ast_var_value(variables);
    		if (ast_strlen_zero(val)) {
    			continue;
    		}
    		newvariable = ast_var_assign(var, val);
    		if (newvariable) {
    
    			AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
    
    		}
    	}
    
    	return x;
    }
    
    /*!
     * \brief Delete all variables from a variable list
     * \param headp The head pointer to the variable list to delete
     */
    static void free_variables(struct varshead *headp)
    {
    	struct ast_var_t *vardata;
    
    	while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
    		ast_var_delete(vardata);
    	}
    }
    
    /*!
     * \brief Copy a snapshot and its details
     * \param dst The destination
     * \param src The source
     */
    static void cdr_object_snapshot_copy(struct cdr_object_snapshot *dst, struct cdr_object_snapshot *src)
    {
    	if (dst->snapshot) {
    		ao2_t_ref(dst->snapshot, -1, "release old snapshot during copy");
    	}
    	dst->snapshot = src->snapshot;
    	ao2_t_ref(dst->snapshot, +1, "bump new snapshot during copy");
    	strcpy(dst->userfield, src->userfield);
    	dst->flags = src->flags;
    	copy_variables(&dst->variables, &src->variables);
    }
    
    /*!
     * \brief Transition a \ref cdr_object to a new state
     * \param cdr The \ref cdr_object to transition
     * \param fn_table The \ref cdr_object_fn_table state to go to
     */
    static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
    {
    	RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
    
    	CDR_DEBUG(mod_cfg, "%p - Transitioning CDR for %s from state %s to %s\n",
    		cdr, cdr->party_a.snapshot->name,
    		cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
    	cdr->fn_table = fn_table;
    	if (cdr->fn_table->init_function) {
    		cdr->fn_table->init_function(cdr);
    	}
    }
    /*! \internal
    
     * \brief Hash function for containers of CDRs indexing by Party A uniqueid */
    
    static int cdr_object_channel_hash_fn(const void *obj, const int flags)
    {
    
    	const struct cdr_object *cdr;
    	const char *key;
    
    	switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
    	case OBJ_KEY:
    		key = obj;
    		break;
    	case OBJ_POINTER:
    		cdr = obj;
    		key = cdr->uniqueid;
    		break;
    	default:
    		ast_assert(0);
    		return 0;
    	}
    	return ast_str_case_hash(key);
    
     * \brief Comparison function for containers of CDRs indexing by Party A uniqueid
    
    static int cdr_object_channel_cmp_fn(void *obj, void *arg, int flags)
    
        struct cdr_object *left = obj;
        struct cdr_object *right = arg;
        const char *right_key = arg;
        int cmp;
    
        switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
        case OBJ_POINTER:
            right_key = right->uniqueid;
            /* Fall through */
        case OBJ_KEY:
            cmp = strcmp(left->uniqueid, right_key);
            break;
        case OBJ_PARTIAL_KEY:
            /*
             * We could also use a partial key struct containing a length
             * so strlen() does not get called for every comparison instead.
             */
            cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
            break;
        default:
            /* Sort can only work on something with a full or partial key. */
            ast_assert(0);
            cmp = 0;
            break;
        }
        return cmp ? 0 : CMP_MATCH;
    
    }
    
    /*!
     * \brief \ref cdr_object Destructor
     */
    static void cdr_object_dtor(void *obj)
    {
    	struct cdr_object *cdr = obj;
    	struct ast_var_t *it_var;
    
    	ao2_cleanup(cdr->party_a.snapshot);
    	ao2_cleanup(cdr->party_b.snapshot);
    	while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
    		ast_var_delete(it_var);
    	}
    	while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
    		ast_var_delete(it_var);
    	}
    	ast_string_field_free_memory(cdr);
    
    
    	ao2_cleanup(cdr->next);
    
    }
    
    /*!
     * \brief \ref cdr_object constructor
     * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
     *
     * This implicitly sets the state of the newly created CDR to the Single state
     * (\ref single_state_fn_table)
     */
    static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
    {
    	RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
    	struct cdr_object *cdr;
    
    	ast_assert(chan != NULL);
    
    	cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
    	if (!cdr) {
    		return NULL;
    	}
    	cdr->last = cdr;
    	if (ast_string_field_init(cdr, 64)) {
    
    		ao2_cleanup(cdr);
    
    	ast_string_field_set(cdr, uniqueid, chan->uniqueid);
    
    	ast_string_field_set(cdr, name, chan->name);
    	ast_string_field_set(cdr, linkedid, chan->linkedid);
    	cdr->disposition = AST_CDR_NULL;
    	cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
    
    	cdr->party_a.snapshot = chan;
    	ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
    
    	CDR_DEBUG(mod_cfg, "%p - Created CDR for channel %s\n", cdr, chan->name);
    
    	cdr_object_transition_state(cdr, &single_state_fn_table);
    
    	return cdr;
    }
    
    /*!
     * \brief Create a new \ref cdr_object and append it to an existing chain
     * \param cdr The \ref cdr_object to append to
     */
    static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
    {
    	struct cdr_object *new_cdr;
    	struct cdr_object *it_cdr;
    	struct cdr_object *cdr_last;
    
    	cdr_last = cdr->last;
    	new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
    	if (!new_cdr) {
    		return NULL;
    	}
    	new_cdr->disposition = AST_CDR_NULL;
    
    	/* Copy over the linkedid, as it may have changed */
    	ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
    	ast_string_field_set(new_cdr, appl, cdr_last->appl);
    	ast_string_field_set(new_cdr, data, cdr_last->data);
    
    	ast_string_field_set(new_cdr, context, cdr_last->context);
    	ast_string_field_set(new_cdr, exten, cdr_last->exten);
    
    	/*
    	 * If the current CDR says to disable all future ones,
    	 * keep the disable chain going
    	 */
    	if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
    		ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
    	}
    
    
    	/* Copy over other Party A information */
    	cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
    
    	/* Append the CDR to the end of the list */
    	for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
    		it_cdr->last = new_cdr;
    	}
    	it_cdr->last = new_cdr;
    	it_cdr->next = new_cdr;
    
    	return new_cdr;
    }
    
    
    /*!
     * \brief Return whether or not a channel has changed its state in the dialplan, subject
     * to endbeforehexten logic
     *
     * \param old_snapshot The previous state
     * \param new_snapshot The new state
     *
     * \retval 0 if the state has not changed
     * \retval 1 if the state changed
     */
    static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
    	struct ast_channel_snapshot *new_snapshot)
    {
    	RAII_VAR(struct module_config *, mod_cfg,
    		ao2_global_obj_ref(module_configs), ao2_cleanup);
    
    	/* If we ignore hangup logic, don't indicate that we're executing anything new */
    	if (ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)
    		&& ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
    		return 0;
    	}
    
    
    	/* When Party A is originated to an application and the application exits, the stack
    	 * will attempt to clear the application and restore the dummy originate application
    	 * of "AppDialX". Ignore application changes to AppDialX as a result.
    	 */
    
    	if (strcmp(new_snapshot->appl, old_snapshot->appl) && strncasecmp(new_snapshot->appl, "appdial", 7)
    		&& (strcmp(new_snapshot->context, old_snapshot->context)
    		|| strcmp(new_snapshot->exten, old_snapshot->exten)
    		|| new_snapshot->priority != old_snapshot->priority)) {
    
    /*!
     * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
     * that was created as the result of a dial operation
     *
     * \retval 0 the channel was not created as the result of a dial
     * \retval 1 the channel was created as the result of a dial
     */
    static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
    {
    	return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
    			&& !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
    }
    
    /*!
     * \brief Given two CDR snapshots, figure out who should be Party A for the
     * resulting CDR
     * \param left One of the snapshots
     * \param right The other snapshot
     * \retval The snapshot that won
     */
    static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
    {
    	/* Check whether or not the party is dialed. A dialed party is never the