stasis: Don't hold app_registry and session locks unnecessarily
[asterisk/asterisk.git] / main / cdr.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Call Detail Record API
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * \note Includes code and algorithms from the Zapata library.
26  *
27  * \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
28  * through our fingers somehow.  If someone allocates a CDR, it must be completely handled normally
29  * or a WARNING shall be logged, so that we can best keep track of any escape condition where the CDR
30  * isn't properly generated and posted.
31  */
32
33 /*! \li \ref cdr.c uses the configuration file \ref cdr.conf
34  * \addtogroup configuration_file Configuration Files
35  */
36
37 /*!
38  * \page cdr.conf cdr.conf
39  * \verbinclude cdr.conf.sample
40  */
41
42 /*** MODULEINFO
43         <support_level>core</support_level>
44  ***/
45
46 #include "asterisk.h"
47
48 #include <signal.h>
49 #include <inttypes.h>
50
51 #include "asterisk/lock.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/cdr.h"
54 #include "asterisk/callerid.h"
55 #include "asterisk/manager.h"
56 #include "asterisk/module.h"
57 #include "asterisk/causes.h"
58 #include "asterisk/linkedlists.h"
59 #include "asterisk/utils.h"
60 #include "asterisk/sched.h"
61 #include "asterisk/config.h"
62 #include "asterisk/cli.h"
63 #include "asterisk/stringfields.h"
64 #include "asterisk/config_options.h"
65 #include "asterisk/json.h"
66 #include "asterisk/parking.h"
67 #include "asterisk/stasis.h"
68 #include "asterisk/stasis_channels.h"
69 #include "asterisk/stasis_bridges.h"
70 #include "asterisk/stasis_message_router.h"
71 #include "asterisk/astobj2.h"
72 #include "asterisk/taskprocessor.h"
73
74 /*** DOCUMENTATION
75         <configInfo name="cdr" language="en_US">
76                 <synopsis>Call Detail Record configuration</synopsis>
77                 <description>
78                         <para>CDR is Call Detail Record, which provides logging services via a variety of
79                         pluggable backend modules. Detailed call information can be recorded to
80                         databases, files, etc. Useful for billing, fraud prevention, compliance with
81                         Sarbanes-Oxley aka The Enron Act, QOS evaluations, and more.</para>
82                 </description>
83                 <configFile name="cdr.conf">
84                         <configObject name="general">
85                                 <synopsis>Global settings applied to the CDR engine.</synopsis>
86                                 <configOption name="debug">
87                                         <synopsis>Enable/disable verbose CDR debugging.</synopsis>
88                                         <description><para>When set to <literal>True</literal>, verbose updates
89                                         of changes in CDR information will be logged. Note that this is only
90                                         of use when debugging CDR behavior.</para>
91                                         </description>
92                                 </configOption>
93                                 <configOption name="enable">
94                                         <synopsis>Enable/disable CDR logging.</synopsis>
95                                         <description><para>Define whether or not to use CDR logging. Setting this to "no" will override
96                                         any loading of backend CDR modules.  Default is "yes".</para>
97                                         </description>
98                                 </configOption>
99                                 <configOption name="unanswered">
100                                         <synopsis>Log calls that are never answered and don't set an outgoing party.</synopsis>
101                                         <description><para>
102                                         Define whether or not to log unanswered calls that don't involve an outgoing party. Setting
103                                         this to "yes" will make calls to extensions that don't answer and don't set a side B channel
104                                         (such as by using the Dial application) receive CDR log entries. If this option is set to
105                                         "no", then those log entries will not be created. Unanswered calls which get offered to an
106                                         outgoing line will always receive log entries regardless of this option, and that is the
107                                         intended behavior.
108                                         </para>
109                                         </description>
110                                 </configOption>
111                                 <configOption name="congestion">
112                                         <synopsis>Log congested calls.</synopsis>
113                                         <description><para>Define whether or not to log congested calls. Setting this to "yes" will
114                                         report each call that fails to complete due to congestion conditions.</para>
115                                         </description>
116                                 </configOption>
117                                 <configOption name="endbeforehexten">
118                                         <synopsis>Don't produce CDRs while executing hangup logic</synopsis>
119                                         <description>
120                                                 <para>As each CDR for a channel is finished, its end time is updated
121                                                 and the CDR is finalized. When a channel is hung up and hangup
122                                                 logic is present (in the form of a hangup handler or the
123                                                 <literal>h</literal> extension), a new CDR is generated for the
124                                                 channel. Any statistics are gathered from this new CDR. By enabling
125                                                 this option, no new CDR is created for the dialplan logic that is
126                                                 executed in <literal>h</literal> extensions or attached hangup handler
127                                                 subroutines. The default value is <literal>yes</literal>, indicating
128                                                 that a CDR will be generated during hangup logic.</para>
129                                         </description>
130                                 </configOption>
131                                 <configOption name="initiatedseconds">
132                                         <synopsis>Count microseconds for billsec purposes</synopsis>
133                                         <description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
134                                         is simply the end time (hangup time) minus the answer time in seconds. Internally,
135                                         asterisk stores the time in terms of microseconds and seconds. By setting
136                                         initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
137                                         that were initiated (a sort of round up method). Technically, this is
138                                         when the microsecond part of the end time is greater than the microsecond
139                                         part of the answer time, then the billsec time is incremented one second.</para>
140                                         </description>
141                                 </configOption>
142                                 <configOption name="batch">
143                                         <synopsis>Submit CDRs to the backends for processing in batches</synopsis>
144                                         <description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
145                                         every call, the data will be stored in a buffer to help alleviate load on the
146                                         asterisk server.</para>
147                                         <warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
148                                         i.e., software crash, power failure, kill -9, etc.</para>
149                                         </warning>
150                                         </description>
151                                 </configOption>
152                                 <configOption name="size">
153                                         <synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
154                                         <description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
155                                         them to the backend engines. batch must be set to <literal>yes</literal>.</para>
156                                         </description>
157                                 </configOption>
158                                 <configOption name="time">
159                                         <synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
160                                         <description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
161                                         backend engines. If this time limit is reached, then it will post the records, regardless of the value
162                                         defined for size. batch must be set to <literal>yes</literal>.</para>
163                                         <note><para>Time is expressed in seconds.</para></note>
164                                         </description>
165                                 </configOption>
166                                 <configOption name="scheduleronly">
167                                         <synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
168                                         <description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
169                                         records.  Posting can either occur inside the scheduler thread, or a new
170                                         thread can be spawned for the submission of every batch.  For small batches,
171                                         it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
172                                         For large batches, say anything over size=10, a new thread is recommended, so
173                                         set this to <literal>no</literal>.</para>
174                                         </description>
175                                 </configOption>
176                                 <configOption name="safeshutdown">
177                                         <synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
178                                         <description><para>When shutting down asterisk, you can block until the CDRs are submitted.  If
179                                         you don't, then data will likely be lost.  You can always check the size of
180                                         the CDR batch buffer with the CLI <astcli>cdr status</astcli> command.  To enable blocking on
181                                         submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
182                                         </description>
183                                 </configOption>
184                         </configObject>
185                 </configFile>
186         </configInfo>
187  ***/
188
189 #define DEFAULT_ENABLED "1"
190 #define DEFAULT_BATCHMODE "0"
191 #define DEFAULT_UNANSWERED "0"
192 #define DEFAULT_CONGESTION "0"
193 #define DEFAULT_END_BEFORE_H_EXTEN "1"
194 #define DEFAULT_INITIATED_SECONDS "0"
195
196 #define DEFAULT_BATCH_SIZE "100"
197 #define MAX_BATCH_SIZE 1000
198 #define DEFAULT_BATCH_TIME "300"
199 #define MAX_BATCH_TIME 86400
200 #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
201 #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
202
203 #define cdr_set_debug_mode(mod_cfg) \
204         do { \
205                 cdr_debug_enabled = ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG); \
206         } while (0)
207
208 static int cdr_debug_enabled;
209
210 #define CDR_DEBUG(fmt, ...) \
211         do { \
212                 if (cdr_debug_enabled) { \
213                         ast_verbose((fmt), ##__VA_ARGS__); \
214                 } \
215         } while (0)
216
217 static void cdr_detach(struct ast_cdr *cdr);
218 static void cdr_submit_batch(int shutdown);
219 static int cdr_toggle_runtime_options(void);
220
221 /*! \brief The configuration settings for this module */
222 struct module_config {
223         struct ast_cdr_config *general;         /*!< CDR global settings */
224 };
225
226 /*! \brief The container for the module configuration */
227 static AO2_GLOBAL_OBJ_STATIC(module_configs);
228
229 /*! \brief The type definition for general options */
230 static struct aco_type general_option = {
231         .type = ACO_GLOBAL,
232         .name = "general",
233         .item_offset = offsetof(struct module_config, general),
234         .category = "general",
235         .category_match = ACO_WHITELIST_EXACT,
236 };
237
238 /*! Config sections used by existing modules. Do not add to this list. */
239 static const char *ignore_categories[] = {
240         "csv",
241         "custom",
242         "manager",
243         "odbc",
244         "pgsql",
245         "radius",
246         "sqlite",
247         "tds",
248         "mysql",
249         NULL,
250 };
251
252 static struct aco_type ignore_option = {
253         .type = ACO_IGNORE,
254         .name = "modules",
255         .category = (const char*)ignore_categories,
256         .category_match = ACO_WHITELIST_ARRAY,
257 };
258
259 static void *module_config_alloc(void);
260 static void module_config_destructor(void *obj);
261 static void module_config_post_apply(void);
262
263 /*! \brief The file definition */
264 static struct aco_file module_file_conf = {
265         .filename = "cdr.conf",
266         .types = ACO_TYPES(&general_option, &ignore_option),
267 };
268
269 CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
270         .files = ACO_FILES(&module_file_conf),
271         .post_apply_config = module_config_post_apply,
272 );
273
274 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
275
276 static void module_config_post_apply(void)
277 {
278         struct module_config *mod_cfg;
279
280         mod_cfg = ao2_global_obj_ref(module_configs);
281         if (!mod_cfg) {
282                 return;
283         }
284         cdr_set_debug_mode(mod_cfg);
285         ao2_cleanup(mod_cfg);
286 }
287
288 /*! \brief Dispose of a module config object */
289 static void module_config_destructor(void *obj)
290 {
291         struct module_config *cfg = obj;
292
293         if (!cfg) {
294                 return;
295         }
296         ao2_ref(cfg->general, -1);
297 }
298
299 /*! \brief Create a new module config object */
300 static void *module_config_alloc(void)
301 {
302         struct module_config *mod_cfg;
303         struct ast_cdr_config *cdr_config;
304
305         mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
306         if (!mod_cfg) {
307                 return NULL;
308         }
309
310         cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
311         if (!cdr_config) {
312                 ao2_ref(cdr_config, -1);
313                 return NULL;
314         }
315         mod_cfg->general = cdr_config;
316
317         return mod_cfg;
318 }
319
320 /*! \brief Registration object for CDR backends */
321 struct cdr_beitem {
322         char name[20];
323         char desc[80];
324         ast_cdrbe be;
325         AST_RWLIST_ENTRY(cdr_beitem) list;
326         int suspended:1;
327 };
328
329 /*! \brief List of registered backends */
330 static AST_RWLIST_HEAD_STATIC(be_list, cdr_beitem);
331
332 /*! \brief List of registered modifiers */
333 static AST_RWLIST_HEAD_STATIC(mo_list, cdr_beitem);
334
335 /*! \brief Queued CDR waiting to be batched */
336 struct cdr_batch_item {
337         struct ast_cdr *cdr;
338         struct cdr_batch_item *next;
339 };
340
341 /*! \brief The actual batch queue */
342 static struct cdr_batch {
343         int size;
344         struct cdr_batch_item *head;
345         struct cdr_batch_item *tail;
346 } *batch = NULL;
347
348 /*! \brief The global sequence counter used for CDRs */
349 static int global_cdr_sequence =  0;
350
351 /*! \brief Scheduler items */
352 static struct ast_sched_context *sched;
353 static int cdr_sched = -1;
354 AST_MUTEX_DEFINE_STATIC(cdr_sched_lock);
355 static pthread_t cdr_thread = AST_PTHREADT_NULL;
356
357 /*! \brief Lock protecting modifications to the batch queue */
358 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
359
360 /*! \brief These are used to wake up the CDR thread when there's work to do */
361 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
362 static ast_cond_t cdr_pending_cond;
363
364 /*! \brief A container of the active master CDRs indexed by Party A channel uniqueid */
365 static struct ao2_container *active_cdrs_master;
366
367 /*! \brief A container of all active CDRs with a Party B indexed by Party B channel name */
368 static struct ao2_container *active_cdrs_all;
369
370 /*! \brief Message router for stasis messages regarding channel state */
371 static struct stasis_message_router *stasis_router;
372
373 /*! \brief Our subscription for bridges */
374 static struct stasis_forward *bridge_subscription;
375
376 /*! \brief Our subscription for channels */
377 static struct stasis_forward *channel_subscription;
378
379 /*! \brief Our subscription for parking */
380 static struct stasis_forward *parking_subscription;
381
382 /*! \brief The parent topic for all topics we want to aggregate for CDRs */
383 static struct stasis_topic *cdr_topic;
384
385 /*! \brief A message type used to synchronize with the CDR topic */
386 STASIS_MESSAGE_TYPE_DEFN_LOCAL(cdr_sync_message_type);
387
388 struct cdr_object;
389
390 /*! \brief Return types for \ref process_bridge_enter functions */
391 enum process_bridge_enter_results {
392         /*!
393          * The CDR was the only party in the bridge.
394          */
395         BRIDGE_ENTER_ONLY_PARTY,
396         /*!
397          * The CDR was able to obtain a Party B from some other party already in the bridge
398          */
399         BRIDGE_ENTER_OBTAINED_PARTY_B,
400         /*!
401          * The CDR was not able to obtain a Party B
402          */
403         BRIDGE_ENTER_NO_PARTY_B,
404         /*!
405          * This CDR can't handle a bridge enter message and a new CDR needs to be created
406          */
407         BRIDGE_ENTER_NEED_CDR,
408 };
409
410 /*!
411  * \brief A virtual table used for \ref cdr_object.
412  *
413  * Note that all functions are optional - if a subclass does not need an
414  * implementation, it is safe to leave it NULL.
415  */
416 struct cdr_object_fn_table {
417         /*! \brief Name of the subclass */
418         const char *name;
419
420         /*!
421          * \brief An initialization function. This will be called automatically
422          * when a \ref cdr_object is switched to this type in
423          * \ref cdr_object_transition_state
424          *
425          * \param cdr The \ref cdr_object that was just transitioned
426          */
427         void (* const init_function)(struct cdr_object *cdr);
428
429         /*!
430          * \brief Process a Party A update for the \ref cdr_object
431          *
432          * \param cdr The \ref cdr_object to process the update
433          * \param snapshot The snapshot for the CDR's Party A
434          * \retval 0 the CDR handled the update or ignored it
435          * \retval 1 the CDR is finalized and a new one should be made to handle it
436          */
437         int (* const process_party_a)(struct cdr_object *cdr,
438                         struct ast_channel_snapshot *snapshot);
439
440         /*!
441          * \brief Process a Party B update for the \ref cdr_object
442          *
443          * \param cdr The \ref cdr_object to process the update
444          * \param snapshot The snapshot for the CDR's Party B
445          */
446         void (* const process_party_b)(struct cdr_object *cdr,
447                         struct ast_channel_snapshot *snapshot);
448
449         /*!
450          * \brief Process the beginning of a dial. A dial message implies one of two
451          * things:
452          * The \ref cdr_object's Party A has been originated
453          * The \ref cdr_object's Party A is dialing its Party B
454          *
455          * \param cdr The \ref cdr_object
456          * \param caller The originator of the dial attempt
457          * \param peer The destination of the dial attempt
458          *
459          * \retval 0 if the parties in the dial were handled by this CDR
460          * \retval 1 if the parties could not be handled by this CDR
461          */
462         int (* const process_dial_begin)(struct cdr_object *cdr,
463                         struct ast_channel_snapshot *caller,
464                         struct ast_channel_snapshot *peer);
465
466         /*!
467          * \brief Process the end of a dial. At the end of a dial, a CDR can be
468          * transitioned into one of two states - DialedPending
469          * (\ref dialed_pending_state_fn_table) or Finalized
470          * (\ref finalized_state_fn_table).
471          *
472          * \param cdr The \ref cdr_object
473          * \param caller The originator of the dial attempt
474          * \param peer the Destination of the dial attempt
475          * \param dial_status What happened
476          *
477          * \retval 0 if the parties in the dial were handled by this CDR
478          * \retval 1 if the parties could not be handled by this CDR
479          */
480         int (* const process_dial_end)(struct cdr_object *cdr,
481                         struct ast_channel_snapshot *caller,
482                         struct ast_channel_snapshot *peer,
483                         const char *dial_status);
484
485         /*!
486          * \brief Process the entering of a bridge by this CDR. The purpose of this
487          * callback is to have the CDR prepare itself for the bridge and attempt to
488          * find a valid Party B. The act of creating new CDRs based on the entering
489          * of this channel into the bridge is handled by the higher level message
490          * handler.
491          *
492          * Note that this handler is for when a channel enters into a "normal"
493          * bridge, where people actually talk to each other. Parking is its own
494          * thing.
495          *
496          * \param cdr The \ref cdr_object
497          * \param bridge The bridge that the Party A just entered into
498          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
499          *
500          * \retval process_bridge_enter_results Defines whether or not this CDR was able
501          * to fully handle the bridge enter message.
502          */
503         enum process_bridge_enter_results (* const process_bridge_enter)(
504                         struct cdr_object *cdr,
505                         struct ast_bridge_snapshot *bridge,
506                         struct ast_channel_snapshot *channel);
507
508         /*!
509          * \brief Process entering into a parking bridge.
510          *
511          * \param cdr The \ref cdr_object
512          * \param bridge The parking bridge that Party A just entered into
513          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
514          *
515          * \retval 0 This CDR successfully transitioned itself into the parked state
516          * \retval 1 This CDR couldn't handle the parking transition and we need a
517          *  new CDR.
518          */
519         int (* const process_parking_bridge_enter)(struct cdr_object *cdr,
520                         struct ast_bridge_snapshot *bridge,
521                         struct ast_channel_snapshot *channel);
522
523         /*!
524          * \brief Process the leaving of a bridge by this CDR.
525          *
526          * \param cdr The \ref cdr_object
527          * \param bridge The bridge that the Party A just left
528          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
529          *
530          * \retval 0 This CDR left successfully
531          * \retval 1 Error
532          */
533         int (* const process_bridge_leave)(struct cdr_object *cdr,
534                         struct ast_bridge_snapshot *bridge,
535                         struct ast_channel_snapshot *channel);
536
537         /*!
538          * \brief Process an update informing us that the channel got itself parked
539          *
540          * \param cdr The \ref cdr_object
541          * \param channel The parking information for this CDR's party A
542          *
543          * \retval 0 This CDR successfully parked itself
544          * \retval 1 This CDR couldn't handle the park
545          */
546         int (* const process_parked_channel)(struct cdr_object *cdr,
547                         struct ast_parked_call_payload *parking_info);
548 };
549
550 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
551 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
552 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
553 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
554 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info);
555
556 static void single_state_init_function(struct cdr_object *cdr);
557 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
558 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
559 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);
560 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
561
562 /*!
563  * \brief The virtual table for the Single state.
564  *
565  * A \ref cdr_object starts off in this state. This represents a channel that
566  * has no Party B information itself.
567  *
568  * A \ref cdr_object from this state can go into any of the following states:
569  * * \ref dial_state_fn_table
570  * * \ref bridge_state_fn_table
571  * * \ref finalized_state_fn_table
572  */
573 struct cdr_object_fn_table single_state_fn_table = {
574         .name = "Single",
575         .init_function = single_state_init_function,
576         .process_party_a = base_process_party_a,
577         .process_party_b = single_state_process_party_b,
578         .process_dial_begin = single_state_process_dial_begin,
579         .process_dial_end = base_process_dial_end,
580         .process_bridge_enter = single_state_process_bridge_enter,
581         .process_parking_bridge_enter = single_state_process_parking_bridge_enter,
582         .process_bridge_leave = base_process_bridge_leave,
583         .process_parked_channel = base_process_parked_channel,
584 };
585
586 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
587 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
588 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);
589 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);
590
591 /*!
592  * \brief The virtual table for the Dial state.
593  *
594  * A \ref cdr_object that has begun a dial operation. This state is entered when
595  * the Party A for a CDR is determined to be dialing out to a Party B or when
596  * a CDR is for an originated channel (in which case the Party A information is
597  * the originated channel, and there is no Party B).
598  *
599  * A \ref cdr_object from this state can go in any of the following states:
600  * * \ref dialed_pending_state_fn_table
601  * * \ref bridge_state_fn_table
602  * * \ref finalized_state_fn_table
603  */
604 struct cdr_object_fn_table dial_state_fn_table = {
605         .name = "Dial",
606         .process_party_a = base_process_party_a,
607         .process_party_b = dial_state_process_party_b,
608         .process_dial_begin = dial_state_process_dial_begin,
609         .process_dial_end = dial_state_process_dial_end,
610         .process_bridge_enter = dial_state_process_bridge_enter,
611         .process_bridge_leave = base_process_bridge_leave,
612 };
613
614 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
615 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
616 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);
617 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
618
619 /*!
620  * \brief The virtual table for the Dialed Pending state.
621  *
622  * A \ref cdr_object that has successfully finished a dial operation, but we
623  * don't know what they're going to do yet. It's theoretically possible to dial
624  * a party and then have that party not be bridged with the caller; likewise,
625  * an origination can complete and the channel go off and execute dialplan. The
626  * pending state acts as a bridge between either:
627  * * Entering a bridge
628  * * Getting a new CDR for new dialplan execution
629  * * Switching from being originated to executing dialplan
630  *
631  * A \ref cdr_object from this state can go in any of the following states:
632  * * \ref single_state_fn_table
633  * * \ref dialed_pending_state_fn_table
634  * * \ref bridge_state_fn_table
635  * * \ref finalized_state_fn_table
636  */
637 struct cdr_object_fn_table dialed_pending_state_fn_table = {
638         .name = "DialedPending",
639         .process_party_a = dialed_pending_state_process_party_a,
640         .process_dial_begin = dialed_pending_state_process_dial_begin,
641         .process_bridge_enter = dialed_pending_state_process_bridge_enter,
642         .process_parking_bridge_enter = dialed_pending_state_process_parking_bridge_enter,
643         .process_bridge_leave = base_process_bridge_leave,
644         .process_parked_channel = base_process_parked_channel,
645 };
646
647 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
648 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
649
650 /*!
651  * \brief The virtual table for the Bridged state
652  *
653  * A \ref cdr_object enters this state when it receives notification that the
654  * channel has entered a bridge.
655  *
656  * A \ref cdr_object from this state can go to:
657  * * \ref finalized_state_fn_table
658  */
659 struct cdr_object_fn_table bridge_state_fn_table = {
660         .name = "Bridged",
661         .process_party_a = base_process_party_a,
662         .process_party_b = bridge_state_process_party_b,
663         .process_bridge_leave = bridge_state_process_bridge_leave,
664         .process_parked_channel = base_process_parked_channel,
665 };
666
667 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
668
669 /*!
670  * \brief The virtual table for the Parked state
671  *
672  * Parking is weird. Unlike typical bridges, it has to be treated somewhat
673  * uniquely - a channel in a parking bridge (which is a subclass of a holding
674  * bridge) has to be handled as if the channel went into an application.
675  * However, when the channel comes out, we need a new CDR - unlike the Single
676  * state.
677  */
678 struct cdr_object_fn_table parked_state_fn_table = {
679         .name = "Parked",
680         .process_party_a = base_process_party_a,
681         .process_bridge_leave = parked_state_process_bridge_leave,
682         .process_parked_channel = base_process_parked_channel,
683 };
684
685 static void finalized_state_init_function(struct cdr_object *cdr);
686 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
687
688 /*!
689  * \brief The virtual table for the finalized state.
690  *
691  * Once in the finalized state, the CDR is done. No modifications can be made
692  * to the CDR.
693  */
694 struct cdr_object_fn_table finalized_state_fn_table = {
695         .name = "Finalized",
696         .init_function = finalized_state_init_function,
697         .process_party_a = finalized_state_process_party_a,
698         .process_bridge_enter = base_process_bridge_enter,
699 };
700
701 /*! \brief A wrapper object around a snapshot.
702  * Fields that are mutable by the CDR engine are replicated here.
703  */
704 struct cdr_object_snapshot {
705         struct ast_channel_snapshot *snapshot;  /*!< The channel snapshot */
706         char userfield[AST_MAX_USER_FIELD];     /*!< Userfield for the channel */
707         unsigned int flags;                     /*!< Specific flags for this party */
708         struct varshead variables;              /*!< CDR variables for the channel */
709 };
710
711 /*! \brief An in-memory representation of an active CDR */
712 struct cdr_object {
713         struct cdr_object_snapshot party_a;     /*!< The Party A information */
714         struct cdr_object_snapshot party_b;     /*!< The Party B information */
715         struct cdr_object_fn_table *fn_table;   /*!< The current virtual table */
716
717         enum ast_cdr_disposition disposition;   /*!< The disposition of the CDR */
718         struct timeval start;                   /*!< When this CDR was created */
719         struct timeval answer;                  /*!< Either when the channel was answered, or when the path between channels was established */
720         struct timeval end;                     /*!< When this CDR was finalized */
721         struct timeval lastevent;               /*!< The time at which the last event was created regarding this CDR */
722         unsigned int sequence;                  /*!< A monotonically increasing number for each CDR */
723         struct ast_flags flags;                 /*!< Flags on the CDR */
724         AST_DECLARE_STRING_FIELDS(
725                 AST_STRING_FIELD(linkedid);         /*!< Linked ID. Cached here as it may change out from party A, which must be immutable */
726                 AST_STRING_FIELD(uniqueid);                     /*!< Unique id of party A. Cached here as it is the master CDR container key */
727                 AST_STRING_FIELD(name);             /*!< Channel name of party A. Cached here as the party A address may change */
728                 AST_STRING_FIELD(bridge);           /*!< The bridge the party A happens to be in. */
729                 AST_STRING_FIELD(appl);             /*!< The last accepted application party A was in */
730                 AST_STRING_FIELD(data);             /*!< The data for the last accepted application party A was in */
731                 AST_STRING_FIELD(context);          /*!< The accepted context for Party A */
732                 AST_STRING_FIELD(exten);            /*!< The accepted extension for Party A */
733                 AST_STRING_FIELD(party_b_name);     /*!< Party B channel name. Cached here as it is the all CDRs container key */
734         );
735         struct cdr_object *next;                /*!< The next CDR object in the chain */
736         struct cdr_object *last;                /*!< The last CDR object in the chain */
737         int is_root;                            /*!< True if this is the first CDR in the chain */
738 };
739
740 /*!
741  * \brief Copy variables from one list to another
742  * \param to_list destination
743  * \param from_list source
744  * \retval The number of copied variables
745  */
746 static int copy_variables(struct varshead *to_list, struct varshead *from_list)
747 {
748         struct ast_var_t *variables;
749         struct ast_var_t *newvariable;
750         const char *var;
751         const char *val;
752         int x = 0;
753
754         AST_LIST_TRAVERSE(from_list, variables, entries) {
755                 var = ast_var_name(variables);
756                 if (ast_strlen_zero(var)) {
757                         continue;
758                 }
759                 val = ast_var_value(variables);
760                 if (ast_strlen_zero(val)) {
761                         continue;
762                 }
763                 newvariable = ast_var_assign(var, val);
764                 if (newvariable) {
765                         AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
766                         ++x;
767                 }
768         }
769
770         return x;
771 }
772
773 /*!
774  * \brief Delete all variables from a variable list
775  * \param headp The head pointer to the variable list to delete
776  */
777 static void free_variables(struct varshead *headp)
778 {
779         struct ast_var_t *vardata;
780
781         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
782                 ast_var_delete(vardata);
783         }
784 }
785
786 /*!
787  * \brief Copy a snapshot and its details
788  * \param dst The destination
789  * \param src The source
790  */
791 static void cdr_object_snapshot_copy(struct cdr_object_snapshot *dst, struct cdr_object_snapshot *src)
792 {
793         ao2_t_replace(dst->snapshot, src->snapshot, "CDR snapshot copy");
794         strcpy(dst->userfield, src->userfield);
795         dst->flags = src->flags;
796         copy_variables(&dst->variables, &src->variables);
797 }
798
799 /*!
800  * \brief Transition a \ref cdr_object to a new state with initiation flag
801  * \param cdr The \ref cdr_object to transition
802  * \param fn_table The \ref cdr_object_fn_table state to go to
803  */
804 static void cdr_object_transition_state_init(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table, int do_init)
805 {
806         CDR_DEBUG("%p - Transitioning CDR for %s from state %s to %s\n",
807                 cdr, cdr->party_a.snapshot->base->name,
808                 cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
809         cdr->fn_table = fn_table;
810
811         if (cdr->fn_table->init_function && do_init) {
812                 cdr->fn_table->init_function(cdr);
813         }
814 }
815
816 /*!
817  * \brief Transition a \ref cdr_object to a new state
818  * \param cdr The \ref cdr_object to transition
819  * \param fn_table The \ref cdr_object_fn_table state to go to
820  */
821 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
822 {
823         cdr_object_transition_state_init(cdr, fn_table, 1);
824 }
825
826 /*!
827  * \internal
828  * \brief Hash function for master CDR container indexed by Party A uniqueid.
829  */
830 static int cdr_master_hash_fn(const void *obj, const int flags)
831 {
832         const struct cdr_object *cdr;
833         const char *key;
834
835         switch (flags & OBJ_SEARCH_MASK) {
836         case OBJ_SEARCH_KEY:
837                 key = obj;
838                 break;
839         case OBJ_SEARCH_OBJECT:
840                 cdr = obj;
841                 key = cdr->uniqueid;
842                 break;
843         default:
844                 ast_assert(0);
845                 return 0;
846         }
847         return ast_str_case_hash(key);
848 }
849
850 /*!
851  * \internal
852  * \brief Comparison function for master CDR container indexed by Party A uniqueid.
853  */
854 static int cdr_master_cmp_fn(void *obj, void *arg, int flags)
855 {
856     struct cdr_object *left = obj;
857     struct cdr_object *right = arg;
858     const char *right_key = arg;
859     int cmp;
860
861     switch (flags & OBJ_SEARCH_MASK) {
862     case OBJ_SEARCH_OBJECT:
863         right_key = right->uniqueid;
864         /* Fall through */
865     case OBJ_SEARCH_KEY:
866         cmp = strcmp(left->uniqueid, right_key);
867         break;
868     case OBJ_SEARCH_PARTIAL_KEY:
869         /*
870          * We could also use a partial key struct containing a length
871          * so strlen() does not get called for every comparison instead.
872          */
873         cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
874         break;
875     default:
876         /* Sort can only work on something with a full or partial key. */
877         ast_assert(0);
878         cmp = 0;
879         break;
880     }
881     return cmp ? 0 : CMP_MATCH;
882 }
883
884 /*!
885  * \internal
886  * \brief Hash function for all CDR container indexed by Party B channel name.
887  */
888 static int cdr_all_hash_fn(const void *obj, const int flags)
889 {
890         const struct cdr_object *cdr;
891         const char *key;
892
893         switch (flags & OBJ_SEARCH_MASK) {
894         case OBJ_SEARCH_KEY:
895                 key = obj;
896                 break;
897         case OBJ_SEARCH_OBJECT:
898                 cdr = obj;
899                 key = cdr->party_b_name;
900                 break;
901         default:
902                 ast_assert(0);
903                 return 0;
904         }
905         return ast_str_case_hash(key);
906 }
907
908 /*!
909  * \internal
910  * \brief Comparison function for all CDR container indexed by Party B channel name.
911  */
912 static int cdr_all_cmp_fn(void *obj, void *arg, int flags)
913 {
914     struct cdr_object *left = obj;
915     struct cdr_object *right = arg;
916     const char *right_key = arg;
917     int cmp;
918
919     switch (flags & OBJ_SEARCH_MASK) {
920     case OBJ_SEARCH_OBJECT:
921         right_key = right->party_b_name;
922         /* Fall through */
923     case OBJ_SEARCH_KEY:
924         cmp = strcasecmp(left->party_b_name, right_key);
925         break;
926     case OBJ_SEARCH_PARTIAL_KEY:
927         /*
928          * We could also use a partial key struct containing a length
929          * so strlen() does not get called for every comparison instead.
930          */
931         cmp = strncasecmp(left->party_b_name, right_key, strlen(right_key));
932         break;
933     default:
934         /* Sort can only work on something with a full or partial key. */
935         ast_assert(0);
936         cmp = 0;
937         break;
938     }
939     return cmp ? 0 : CMP_MATCH;
940 }
941
942 /*!
943  * \internal
944  * \brief Relink the CDR because Party B's snapshot changed.
945  * \since 13.19.0
946  *
947  * \return Nothing
948  */
949 static void cdr_all_relink(struct cdr_object *cdr)
950 {
951         ao2_lock(active_cdrs_all);
952         if (cdr->party_b.snapshot) {
953                 if (strcasecmp(cdr->party_b_name, cdr->party_b.snapshot->base->name)) {
954                         ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
955                         ast_string_field_set(cdr, party_b_name, cdr->party_b.snapshot->base->name);
956                         ao2_link_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
957                 }
958         } else {
959                 ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
960                 ast_string_field_set(cdr, party_b_name, "");
961         }
962         ao2_unlock(active_cdrs_all);
963 }
964
965 /*!
966  * \internal
967  * \brief Unlink the master CDR and chained records from the active_cdrs_all container.
968  * \since 13.19.0
969  *
970  * \return Nothing
971  */
972 static void cdr_all_unlink(struct cdr_object *cdr)
973 {
974         struct cdr_object *cur;
975         struct cdr_object *next;
976
977         ast_assert(cdr->is_root);
978
979         /* Hold a ref to the root CDR to ensure the list members don't go away on us. */
980         ao2_ref(cdr, +1);
981         ao2_lock(active_cdrs_all);
982         for (cur = cdr; cur; cur = next) {
983                 next = cur->next;
984                 ao2_unlink_flags(active_cdrs_all, cur, OBJ_NOLOCK);
985                 /*
986                  * It is safe to still use cur after unlinking because the
987                  * root CDR holds a ref to all the CDRs in the list and we
988                  * have a ref to the root CDR.
989                  */
990                 ast_string_field_set(cur, party_b_name, "");
991         }
992         ao2_unlock(active_cdrs_all);
993         ao2_ref(cdr, -1);
994 }
995
996 /*!
997  * \brief \ref cdr_object Destructor
998  */
999 static void cdr_object_dtor(void *obj)
1000 {
1001         struct cdr_object *cdr = obj;
1002         struct ast_var_t *it_var;
1003
1004         ao2_cleanup(cdr->party_a.snapshot);
1005         ao2_cleanup(cdr->party_b.snapshot);
1006         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
1007                 ast_var_delete(it_var);
1008         }
1009         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
1010                 ast_var_delete(it_var);
1011         }
1012         ast_string_field_free_memory(cdr);
1013
1014         /* CDR destruction used to work by calling ao2_cleanup(next) and
1015          * allowing the chain to destroy itself neatly. Unfortunately, for
1016          * really long chains, this can result in a stack overflow. So now
1017          * when the root CDR is destroyed, it is responsible for unreffing
1018          * all CDRs in the chain
1019          */
1020         if (cdr->is_root) {
1021                 struct cdr_object *curr = cdr->next;
1022                 struct cdr_object *next;
1023
1024                 while (curr) {
1025                         next = curr->next;
1026                         ao2_cleanup(curr);
1027                         curr = next;
1028                 }
1029         }
1030 }
1031
1032 /*!
1033  * \brief \ref cdr_object constructor
1034  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
1035  *
1036  * This implicitly sets the state of the newly created CDR to the Single state
1037  * (\ref single_state_fn_table)
1038  */
1039 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan, const struct timeval *event_time)
1040 {
1041         struct cdr_object *cdr;
1042
1043         ast_assert(chan != NULL);
1044
1045         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1046         if (!cdr) {
1047                 return NULL;
1048         }
1049         cdr->last = cdr;
1050         if (ast_string_field_init(cdr, 64)) {
1051                 ao2_cleanup(cdr);
1052                 return NULL;
1053         }
1054         ast_string_field_set(cdr, uniqueid, chan->base->uniqueid);
1055         ast_string_field_set(cdr, name, chan->base->name);
1056         ast_string_field_set(cdr, linkedid, chan->peer->linkedid);
1057         cdr->disposition = AST_CDR_NULL;
1058         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
1059         cdr->lastevent = *event_time;
1060
1061         cdr->party_a.snapshot = chan;
1062         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1063
1064         CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->base->name);
1065
1066         cdr_object_transition_state(cdr, &single_state_fn_table);
1067
1068         return cdr;
1069 }
1070
1071 /*!
1072  * \brief Create a new \ref cdr_object and append it to an existing chain
1073  * \param cdr The \ref cdr_object to append to
1074  */
1075 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr, const struct timeval *event_time)
1076 {
1077         struct cdr_object *new_cdr;
1078         struct cdr_object *it_cdr;
1079         struct cdr_object *cdr_last;
1080
1081         cdr_last = cdr->last;
1082         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot, event_time);
1083         if (!new_cdr) {
1084                 return NULL;
1085         }
1086         new_cdr->disposition = AST_CDR_NULL;
1087
1088         /* Copy over the linkedid, as it may have changed */
1089         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1090         ast_string_field_set(new_cdr, appl, cdr_last->appl);
1091         ast_string_field_set(new_cdr, data, cdr_last->data);
1092         ast_string_field_set(new_cdr, context, cdr_last->context);
1093         ast_string_field_set(new_cdr, exten, cdr_last->exten);
1094
1095         /*
1096          * If the current CDR says to disable all future ones,
1097          * keep the disable chain going
1098          */
1099         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1100                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
1101         }
1102
1103         /* Copy over other Party A information */
1104         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1105
1106         /* Append the CDR to the end of the list */
1107         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1108                 it_cdr->last = new_cdr;
1109         }
1110         it_cdr->last = new_cdr;
1111         it_cdr->next = new_cdr;
1112
1113         return new_cdr;
1114 }
1115
1116 /*!
1117  * \internal
1118  * \brief Determine if CDR flag is configured.
1119  *
1120  * \param cdr_flag The configured CDR flag to check.
1121  *
1122  * \retval 0 if the CDR flag is not configured.
1123  * \retval non-zero if the CDR flag is configured.
1124  *
1125  * \return Nothing
1126  */
1127 static int is_cdr_flag_set(unsigned int cdr_flag)
1128 {
1129         struct module_config *mod_cfg;
1130         int flag_set;
1131
1132         mod_cfg = ao2_global_obj_ref(module_configs);
1133         flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1134         ao2_cleanup(mod_cfg);
1135         return flag_set;
1136 }
1137
1138 /*!
1139  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1140  * to endbeforehexten logic
1141  *
1142  * \param old_snapshot The previous state
1143  * \param new_snapshot The new state
1144  *
1145  * \retval 0 if the state has not changed
1146  * \retval 1 if the state changed
1147  */
1148 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1149         struct ast_channel_snapshot *new_snapshot)
1150 {
1151         /* If we ignore hangup logic, don't indicate that we're executing anything new */
1152         if (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1153                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1154                 return 0;
1155         }
1156
1157         /* When Party A is originated to an application and the application exits, the stack
1158          * will attempt to clear the application and restore the dummy originate application
1159          * of "AppDialX". Ignore application changes to AppDialX as a result.
1160          */
1161         if (strcmp(new_snapshot->dialplan->appl, old_snapshot->dialplan->appl)
1162                 && strncasecmp(new_snapshot->dialplan->appl, "appdial", 7)
1163                 && (strcmp(new_snapshot->dialplan->context, old_snapshot->dialplan->context)
1164                         || strcmp(new_snapshot->dialplan->exten, old_snapshot->dialplan->exten)
1165                         || new_snapshot->dialplan->priority != old_snapshot->dialplan->priority)) {
1166                 return 1;
1167         }
1168
1169         return 0;
1170 }
1171
1172 /*!
1173  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1174  * that was created as the result of a dial operation
1175  *
1176  * \retval 0 the channel was not created as the result of a dial
1177  * \retval 1 the channel was created as the result of a dial
1178  */
1179 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1180 {
1181         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1182                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1183 }
1184
1185 /*!
1186  * \brief Given two CDR snapshots, figure out who should be Party A for the
1187  * resulting CDR
1188  * \param left One of the snapshots
1189  * \param right The other snapshot
1190  * \retval The snapshot that won
1191  */
1192 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
1193 {
1194         /* Check whether or not the party is dialed. A dialed party is never the
1195          * Party A with a party that was not dialed.
1196          */
1197         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1198                 return left;
1199         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1200                 return right;
1201         }
1202
1203         /* Try the Party A flag */
1204         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1205                 return left;
1206         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1207                 return right;
1208         }
1209
1210         /* Neither party is dialed and neither has the Party A flag - defer to
1211          * creation time */
1212         if (left->snapshot->base->creationtime.tv_sec < right->snapshot->base->creationtime.tv_sec) {
1213                 return left;
1214         } else if (left->snapshot->base->creationtime.tv_sec > right->snapshot->base->creationtime.tv_sec) {
1215                 return right;
1216         } else if (left->snapshot->base->creationtime.tv_usec > right->snapshot->base->creationtime.tv_usec) {
1217                 return right;
1218         } else {
1219                 /* Okay, fine, take the left one */
1220                 return left;
1221         }
1222 }
1223
1224 /*!
1225  * Compute the duration for a \ref cdr_object
1226  */
1227 static long cdr_object_get_duration(struct cdr_object *cdr)
1228 {
1229         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1230 }
1231
1232 /*!
1233  * \brief Compute the billsec for a \ref cdr_object
1234  */
1235 static long cdr_object_get_billsec(struct cdr_object *cdr)
1236 {
1237         long int ms;
1238
1239         if (ast_tvzero(cdr->answer)) {
1240                 return 0;
1241         }
1242
1243         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1244         if (ms % 1000 >= 500
1245                 && is_cdr_flag_set(CDR_INITIATED_SECONDS)) {
1246                 ms = (ms / 1000) + 1;
1247         } else {
1248                 ms = ms / 1000;
1249         }
1250
1251         return ms;
1252 }
1253
1254 /*!
1255  * \internal
1256  * \brief Set a variable on a CDR object
1257  *
1258  * \param headp The header pointer to the variable to set
1259  * \param name The name of the variable
1260  * \param value The value of the variable
1261  */
1262 static void set_variable(struct varshead *headp, const char *name, const char *value)
1263 {
1264         struct ast_var_t *newvariable;
1265
1266         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1267                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1268                         AST_LIST_REMOVE_CURRENT(entries);
1269                         ast_var_delete(newvariable);
1270                         break;
1271                 }
1272         }
1273         AST_LIST_TRAVERSE_SAFE_END;
1274
1275         if (value && (newvariable = ast_var_assign(name, value))) {
1276                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1277         }
1278 }
1279
1280 /*!
1281  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1282  * suitable for consumption by the registered CDR backends
1283  * \param cdr The \ref cdr_object to convert to a public record
1284  * \retval A chain of \ref ast_cdr objects on success
1285  * \retval NULL on failure
1286  */
1287 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1288 {
1289         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1290         struct cdr_object *it_cdr;
1291         struct ast_var_t *it_var, *it_copy_var;
1292         struct ast_channel_snapshot *party_a;
1293         struct ast_channel_snapshot *party_b;
1294
1295         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1296                 struct ast_cdr *cdr_copy;
1297
1298                 /* Don't create records for CDRs where the party A was a dialed channel */
1299                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1300                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1301                                 it_cdr->party_a.snapshot->base->name);
1302                         continue;
1303                 }
1304
1305                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1306                 if (!cdr_copy) {
1307                         ast_free(pub_cdr);
1308                         return NULL;
1309                 }
1310
1311                 party_a = it_cdr->party_a.snapshot;
1312                 party_b = it_cdr->party_b.snapshot;
1313
1314                 /* Party A */
1315                 ast_assert(party_a != NULL);
1316                 ast_copy_string(cdr_copy->accountcode, party_a->base->accountcode, sizeof(cdr_copy->accountcode));
1317                 cdr_copy->amaflags = party_a->amaflags;
1318                 ast_copy_string(cdr_copy->channel, party_a->base->name, sizeof(cdr_copy->channel));
1319                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller->name, party_a->caller->number, "");
1320                 ast_copy_string(cdr_copy->src, party_a->caller->number, sizeof(cdr_copy->src));
1321                 ast_copy_string(cdr_copy->uniqueid, party_a->base->uniqueid, sizeof(cdr_copy->uniqueid));
1322                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1323                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1324                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1325                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1326
1327                 /* Party B */
1328                 if (party_b) {
1329                         ast_copy_string(cdr_copy->dstchannel, party_b->base->name, sizeof(cdr_copy->dstchannel));
1330                         ast_copy_string(cdr_copy->peeraccount, party_b->base->accountcode, sizeof(cdr_copy->peeraccount));
1331                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1332                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1333                         }
1334                 }
1335                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1336                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1337                 }
1338
1339                 /* Timestamps/durations */
1340                 cdr_copy->start = it_cdr->start;
1341                 cdr_copy->answer = it_cdr->answer;
1342                 cdr_copy->end = it_cdr->end;
1343                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1344                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1345
1346                 /* Flags and IDs */
1347                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1348                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1349                 cdr_copy->disposition = it_cdr->disposition;
1350                 cdr_copy->sequence = it_cdr->sequence;
1351
1352                 /* Variables */
1353                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1354                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1355                         int found = 0;
1356                         struct ast_var_t *newvariable;
1357                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1358                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1359                                         found = 1;
1360                                         break;
1361                                 }
1362                         }
1363                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1364                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1365                         }
1366                 }
1367
1368                 if (!pub_cdr) {
1369                         pub_cdr = cdr_copy;
1370                         cdr_prev = pub_cdr;
1371                 } else {
1372                         cdr_prev->next = cdr_copy;
1373                         cdr_prev = cdr_copy;
1374                 }
1375         }
1376
1377         return pub_cdr;
1378 }
1379
1380 /*!
1381  * \brief Dispatch a CDR.
1382  * \param cdr The \ref cdr_object to dispatch
1383  *
1384  * This will create a \ref ast_cdr object and publish it to the various backends
1385  */
1386 static void cdr_object_dispatch(struct cdr_object *cdr)
1387 {
1388         struct ast_cdr *pub_cdr;
1389
1390         CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1391                 cdr->party_a.snapshot->base->name,
1392                 cdr->party_b.snapshot ? cdr->party_b.snapshot->base->name : "<none>");
1393         pub_cdr = cdr_object_create_public_records(cdr);
1394         cdr_detach(pub_cdr);
1395 }
1396
1397 /*!
1398  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1399  * \param cdr The \ref cdr_object
1400  * \param hangupcause The Asterisk hangup cause code
1401  */
1402 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1403 {
1404         /* Change the disposition based on the hang up cause */
1405         switch (hangupcause) {
1406         case AST_CAUSE_BUSY:
1407                 cdr->disposition = AST_CDR_BUSY;
1408                 break;
1409         case AST_CAUSE_CONGESTION:
1410                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1411                         cdr->disposition = AST_CDR_FAILED;
1412                 } else {
1413                         cdr->disposition = AST_CDR_CONGESTION;
1414                 }
1415                 break;
1416         case AST_CAUSE_NO_ROUTE_DESTINATION:
1417         case AST_CAUSE_UNREGISTERED:
1418                 cdr->disposition = AST_CDR_FAILED;
1419                 break;
1420         case AST_CAUSE_NORMAL_CLEARING:
1421         case AST_CAUSE_NO_ANSWER:
1422                 cdr->disposition = AST_CDR_NOANSWER;
1423                 break;
1424         default:
1425                 break;
1426         }
1427 }
1428
1429 /*!
1430  * \brief Finalize a CDR.
1431  *
1432  * This function is safe to call multiple times. Note that you can call this
1433  * explicitly before going to the finalized state if there's a chance the CDR
1434  * will be re-activated, in which case the \ref cdr_object's end time should be
1435  * cleared. This function is implicitly called when a CDR transitions to the
1436  * finalized state and right before it is dispatched
1437  *
1438  * \param cdr_object The CDR to finalize
1439  */
1440 static void cdr_object_finalize(struct cdr_object *cdr)
1441 {
1442         if (!ast_tvzero(cdr->end)) {
1443                 return;
1444         }
1445         cdr->end = cdr->lastevent;
1446
1447         if (cdr->disposition == AST_CDR_NULL) {
1448                 if (!ast_tvzero(cdr->answer)) {
1449                         cdr->disposition = AST_CDR_ANSWERED;
1450                 } else if (cdr->party_a.snapshot->hangup->cause) {
1451                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangup->cause);
1452                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangup->cause) {
1453                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangup->cause);
1454                 } else {
1455                         cdr->disposition = AST_CDR_FAILED;
1456                 }
1457         }
1458
1459         /* tv_usec is suseconds_t, which could be int or long */
1460         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1461                         cdr->party_a.snapshot->base->name,
1462                         (long)cdr->start.tv_sec,
1463                         (long)cdr->start.tv_usec,
1464                         (long)cdr->answer.tv_sec,
1465                         (long)cdr->answer.tv_usec,
1466                         (long)cdr->end.tv_sec,
1467                         (long)cdr->end.tv_usec,
1468                         ast_cdr_disp2str(cdr->disposition));
1469 }
1470
1471 /*!
1472  * \brief Check to see if a CDR needs to move to the finalized state because
1473  * its Party A hungup.
1474  */
1475 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1476 {
1477         if (ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1478                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1479                 cdr_object_finalize(cdr);
1480         }
1481
1482         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1483                 && cdr->fn_table != &finalized_state_fn_table) {
1484                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1485         }
1486 }
1487
1488 /*!
1489  * \brief Check to see if a CDR needs to be answered based on its Party A.
1490  * Note that this is safe to call as much as you want - we won't answer twice
1491  */
1492 static void cdr_object_check_party_a_answer(struct cdr_object *cdr)
1493 {
1494         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1495                 cdr->answer = cdr->lastevent;
1496                 /* tv_usec is suseconds_t, which could be int or long */
1497                 CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1498                         (long)cdr->answer.tv_sec,
1499                         (long)cdr->answer.tv_usec);
1500         }
1501 }
1502
1503 /* \brief Set Caller ID information on a CDR */
1504 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1505 {
1506         if (!old_snapshot->snapshot) {
1507                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller->dnid);
1508                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller->subaddr);
1509                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->caller->dialed_subaddr);
1510                 return;
1511         }
1512         if (strcmp(old_snapshot->snapshot->caller->dnid, new_snapshot->caller->dnid)) {
1513                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller->dnid);
1514         }
1515         if (strcmp(old_snapshot->snapshot->caller->subaddr, new_snapshot->caller->subaddr)) {
1516                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller->subaddr);
1517         }
1518         if (strcmp(old_snapshot->snapshot->caller->dialed_subaddr, new_snapshot->caller->dialed_subaddr)) {
1519                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->caller->dialed_subaddr);
1520         }
1521 }
1522
1523 /*!
1524  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1525  * a new \ref ast_channel_snapshot
1526  * \param old_snapshot The old \ref cdr_object_snapshot
1527  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1528  */
1529 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1530                 struct ast_channel_snapshot *new_snapshot)
1531 {
1532         cdr_object_update_cid(old_snapshot, new_snapshot);
1533         ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1534 }
1535
1536 /* BASE METHOD IMPLEMENTATIONS */
1537
1538 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1539 {
1540         ast_assert(strcasecmp(snapshot->base->name, cdr->party_a.snapshot->base->name) == 0);
1541
1542         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1543         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1544                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1545                 cdr_object_finalize(cdr);
1546                 return 0;
1547         }
1548
1549         /*
1550          * Only record the context and extension if we aren't in a subroutine, or if
1551          * we are executing hangup logic.
1552          */
1553         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1554                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1555                 if (strcmp(cdr->context, snapshot->dialplan->context)) {
1556                         ast_string_field_set(cdr, context, snapshot->dialplan->context);
1557                 }
1558                 if (strcmp(cdr->exten, snapshot->dialplan->exten)) {
1559                         ast_string_field_set(cdr, exten, snapshot->dialplan->exten);
1560                 }
1561         }
1562
1563         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1564
1565         /* When Party A is originated to an application and the application exits, the stack
1566          * will attempt to clear the application and restore the dummy originate application
1567          * of "AppDialX". Prevent that, and any other application changes we might not want
1568          * here.
1569          */
1570         if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1571                 && !ast_strlen_zero(snapshot->dialplan->appl)
1572                 && (strncasecmp(snapshot->dialplan->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1573                 if (strcmp(cdr->appl, snapshot->dialplan->appl)) {
1574                         ast_string_field_set(cdr, appl, snapshot->dialplan->appl);
1575                 }
1576                 if (strcmp(cdr->data, snapshot->dialplan->data)) {
1577                         ast_string_field_set(cdr, data, snapshot->dialplan->data);
1578                 }
1579
1580                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1581                  * execute before the dial begins, will alter the application/data to
1582                  * something people typically don't want to see, if we see a channel enter
1583                  * into Dial here, we set the appl/data accordingly and lock it.
1584                  */
1585                 if (!strcmp(snapshot->dialplan->appl, "Dial")) {
1586                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1587                 }
1588         }
1589
1590         if (strcmp(cdr->linkedid, snapshot->peer->linkedid)) {
1591                 ast_string_field_set(cdr, linkedid, snapshot->peer->linkedid);
1592         }
1593         cdr_object_check_party_a_answer(cdr);
1594         cdr_object_check_party_a_hangup(cdr);
1595
1596         return 0;
1597 }
1598
1599 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1600 {
1601         return 0;
1602 }
1603
1604 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1605 {
1606         return 0;
1607 }
1608
1609 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1610 {
1611         /* Base process bridge enter simply indicates that we can't handle it */
1612         return BRIDGE_ENTER_NEED_CDR;
1613 }
1614
1615 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1616 {
1617         char park_info[128];
1618
1619         ast_assert(!strcasecmp(parking_info->parkee->base->name, cdr->party_a.snapshot->base->name));
1620
1621         /* Update Party A information regardless */
1622         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1623
1624         /* Fake out where we're parked */
1625         ast_string_field_set(cdr, appl, "Park");
1626         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1627         ast_string_field_set(cdr, data, park_info);
1628
1629         /* Prevent any further changes to the App/Data fields for this record */
1630         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1631
1632         return 0;
1633 }
1634
1635 /* SINGLE STATE */
1636
1637 static void single_state_init_function(struct cdr_object *cdr)
1638 {
1639         cdr->start = cdr->lastevent;
1640         cdr_object_check_party_a_answer(cdr);
1641 }
1642
1643 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1644 {
1645         /* This should never happen! */
1646         ast_assert(cdr->party_b.snapshot == NULL);
1647         ast_assert(0);
1648         return;
1649 }
1650
1651 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1652 {
1653         if (caller && !strcasecmp(cdr->party_a.snapshot->base->name, caller->base->name)) {
1654                 base_process_party_a(cdr, caller);
1655                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1656                         cdr->party_a.snapshot->base->name);
1657                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1658                 cdr_all_relink(cdr);
1659                 CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1660                         cdr->party_b.snapshot->base->name);
1661
1662                 /* If we have two parties, lock the application that caused the
1663                  * two parties to be associated. This prevents mid-call event
1664                  * macros/gosubs from perturbing the CDR application/data
1665                  */
1666                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1667         } else if (!strcasecmp(cdr->party_a.snapshot->base->name, peer->base->name)) {
1668                 /* We're the entity being dialed, i.e., outbound origination */
1669                 base_process_party_a(cdr, peer);
1670                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1671                         cdr->party_a.snapshot->base->name);
1672         }
1673
1674         cdr_object_transition_state(cdr, &dial_state_fn_table);
1675         return 0;
1676 }
1677
1678 /*!
1679  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1680  * already in the bridge while in the Single state. The goal of this is to find
1681  * a Party B for our CDR.
1682  *
1683  * \param cdr Our \ref cdr_object in the Single state
1684  * \param cand_cdr The \ref cdr_object already in the Bridge state
1685  *
1686  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1687  * Party B
1688  * \retval 1 No party in the cand_cdr could be used as our Party B
1689  */
1690 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1691                 struct cdr_object *cand_cdr)
1692 {
1693         struct cdr_object_snapshot *party_a;
1694
1695         /* Don't match on ourselves */
1696         if (!strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)) {
1697                 return 1;
1698         }
1699
1700         /* Try the candidate CDR's Party A first */
1701         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1702         if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
1703                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1704                         cdr, cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name);
1705                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1706                 cdr_all_relink(cdr);
1707                 if (!cand_cdr->party_b.snapshot) {
1708                         /* We just stole them - finalize their CDR. Note that this won't
1709                          * transition their state, it just sets the end time and the
1710                          * disposition - if we need to re-activate them later, we can.
1711                          */
1712                         cdr_object_finalize(cand_cdr);
1713                 }
1714                 return 0;
1715         }
1716
1717         /* Try their Party B, unless it's us */
1718         if (!cand_cdr->party_b.snapshot
1719                 || !strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_b.snapshot->base->name)) {
1720                 return 1;
1721         }
1722         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1723         if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
1724                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1725                         cdr, cdr->party_a.snapshot->base->name, cand_cdr->party_b.snapshot->base->name);
1726                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1727                 cdr_all_relink(cdr);
1728                 return 0;
1729         }
1730
1731         return 1;
1732 }
1733
1734 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)
1735 {
1736         struct ao2_iterator it_cdrs;
1737         char *channel_id;
1738         int success = 0;
1739
1740         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1741
1742         if (ao2_container_count(bridge->channels) == 1) {
1743                 /* No one in the bridge yet but us! */
1744                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1745                 return BRIDGE_ENTER_ONLY_PARTY;
1746         }
1747
1748         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1749                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1750                 ao2_ref(channel_id, -1)) {
1751                 struct cdr_object *cand_cdr_master;
1752                 struct cdr_object *cand_cdr;
1753
1754                 cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1755                 if (!cand_cdr_master) {
1756                         continue;
1757                 }
1758
1759                 ao2_lock(cand_cdr_master);
1760                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1761                         /* Skip any records that are not in a bridge or in this bridge.
1762                          * I'm not sure how that would happen, but it pays to be careful. */
1763                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1764                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1765                                 continue;
1766                         }
1767
1768                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1769                                 continue;
1770                         }
1771                         /* We successfully got a party B - break out */
1772                         success = 1;
1773                         break;
1774                 }
1775                 ao2_unlock(cand_cdr_master);
1776                 ao2_cleanup(cand_cdr_master);
1777         }
1778         ao2_iterator_destroy(&it_cdrs);
1779
1780         /* We always transition state, even if we didn't get a peer */
1781         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1782
1783         /* Success implies that we have a Party B */
1784         if (success) {
1785                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1786         }
1787
1788         return BRIDGE_ENTER_NO_PARTY_B;
1789 }
1790
1791 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1792 {
1793         cdr_object_transition_state(cdr, &parked_state_fn_table);
1794         return 0;
1795 }
1796
1797
1798 /* DIAL STATE */
1799
1800 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1801 {
1802         ast_assert(snapshot != NULL);
1803         ast_assert(cdr->party_b.snapshot
1804                 && !strcasecmp(cdr->party_b.snapshot->base->name, snapshot->base->name));
1805
1806         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1807
1808         /* If party B hangs up, finalize this CDR */
1809         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1810                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1811         }
1812 }
1813
1814 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1815 {
1816         /* Don't process a begin dial here. A party A already in the dial state will
1817          * who receives a dial begin for something else will be handled by the
1818          * message router callback and will add a new CDR for the party A */
1819         return 1;
1820 }
1821
1822 /*!
1823  * \internal
1824  * \brief Convert a dial status to a CDR disposition
1825  */
1826 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1827 {
1828         if (!strcmp(dial_status, "ANSWER")) {
1829                 return AST_CDR_ANSWERED;
1830         } else if (!strcmp(dial_status, "BUSY")) {
1831                 return AST_CDR_BUSY;
1832         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1833                 return AST_CDR_NOANSWER;
1834         } else if (!strcmp(dial_status, "CONGESTION")) {
1835                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1836                         return AST_CDR_FAILED;
1837                 } else {
1838                         return AST_CDR_CONGESTION;
1839                 }
1840         } else if (!strcmp(dial_status, "FAILED")) {
1841                 return AST_CDR_FAILED;
1842         }
1843         return AST_CDR_FAILED;
1844 }
1845
1846 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)
1847 {
1848         struct ast_channel_snapshot *party_a;
1849
1850         if (caller) {
1851                 party_a = caller;
1852         } else {
1853                 party_a = peer;
1854         }
1855         ast_assert(!strcasecmp(cdr->party_a.snapshot->base->name, party_a->base->name));
1856         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1857
1858         if (cdr->party_b.snapshot) {
1859                 if (strcasecmp(cdr->party_b.snapshot->base->name, peer->base->name)) {
1860                         /* Not the status for this CDR - defer back to the message router */
1861                         return 1;
1862                 }
1863                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1864         }
1865
1866         /* Set the disposition based on the dial string. */
1867         cdr->disposition = dial_status_to_disposition(dial_status);
1868         if (cdr->disposition == AST_CDR_ANSWERED) {
1869                 /* Switch to dial pending to wait and see what the caller does */
1870                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1871         } else {
1872                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1873         }
1874
1875         return 0;
1876 }
1877
1878 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)
1879 {
1880         int success = 0;
1881
1882         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1883
1884         /* Get parties in the bridge */
1885         if (ao2_container_count(bridge->channels) == 1) {
1886                 /* No one in the bridge yet but us! */
1887                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1888                 return BRIDGE_ENTER_ONLY_PARTY;
1889         }
1890
1891         /* If we don't have a Party B (originated channel), skip it */
1892         if (cdr->party_b.snapshot) {
1893                 struct ao2_iterator it_cdrs;
1894                 char *channel_id;
1895
1896                 for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1897                         !success && (channel_id = ao2_iterator_next(&it_cdrs));
1898                         ao2_ref(channel_id, -1)) {
1899                         struct cdr_object *cand_cdr_master;
1900                         struct cdr_object *cand_cdr;
1901
1902                         cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1903                         if (!cand_cdr_master) {
1904                                 continue;
1905                         }
1906
1907                         ao2_lock(cand_cdr_master);
1908                         for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1909                                 /* Skip any records that are not in a bridge or in this bridge.
1910                                  * I'm not sure how that would happen, but it pays to be careful. */
1911                                 if (cand_cdr->fn_table != &bridge_state_fn_table
1912                                         || strcmp(cdr->bridge, cand_cdr->bridge)) {
1913                                         continue;
1914                                 }
1915
1916                                 /* Skip any records that aren't our Party B */
1917                                 if (strcasecmp(cdr->party_b.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)) {
1918                                         continue;
1919                                 }
1920                                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1921                                 /* If they have a Party B, they joined up with someone else as their
1922                                  * Party A. Don't finalize them as they're active. Otherwise, we
1923                                  * have stolen them so they need to be finalized.
1924                                  */
1925                                 if (!cand_cdr->party_b.snapshot) {
1926                                         cdr_object_finalize(cand_cdr);
1927                                 }
1928                                 success = 1;
1929                                 break;
1930                         }
1931                         ao2_unlock(cand_cdr_master);
1932                         ao2_cleanup(cand_cdr_master);
1933                 }
1934                 ao2_iterator_destroy(&it_cdrs);
1935         }
1936
1937         /* We always transition state, even if we didn't get a peer */
1938         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1939
1940         /* Success implies that we have a Party B */
1941         if (success) {
1942                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1943         }
1944         return BRIDGE_ENTER_NO_PARTY_B;
1945 }
1946
1947 /* DIALED PENDING STATE */
1948
1949 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1950 {
1951         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1952          * that means we need a new CDR; otherwise, switch us over to single.
1953          */
1954         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1955                 if (cdr->party_b.snapshot) {
1956                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1957                         cdr->fn_table->process_party_a(cdr, snapshot);
1958                         return 1;
1959                 } else {
1960                         /* The CDR does not need to be reinitialized when transitioning
1961                          * to its single state as this would overwrite the start time,
1962                          * causing potentially both the answer and the start time to be
1963                          * the same which is incorrect.
1964                          */
1965                         cdr_object_transition_state_init(cdr, &single_state_fn_table, 0);
1966                         cdr->fn_table->process_party_a(cdr, snapshot);
1967                         return 0;
1968                 }
1969         }
1970         base_process_party_a(cdr, snapshot);
1971         return 0;
1972 }
1973
1974 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)
1975 {
1976         cdr_object_transition_state(cdr, &dial_state_fn_table);
1977         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1978 }
1979
1980 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1981 {
1982         if (cdr->party_b.snapshot) {
1983                 /* We can't handle this as we have a Party B - ask for a new one */
1984                 return 1;
1985         }
1986         cdr_object_transition_state(cdr, &parked_state_fn_table);
1987         return 0;
1988 }
1989
1990 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1991 {
1992         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1993
1994         /* Ask for a new CDR */
1995         return 1;
1996 }
1997
1998 /* BRIDGE STATE */
1999
2000 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2001 {
2002         ast_assert(cdr->party_b.snapshot
2003                 && !strcasecmp(cdr->party_b.snapshot->base->name, snapshot->base->name));
2004
2005         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
2006
2007         /* If party B hangs up, finalize this CDR */
2008         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
2009                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
2010         }
2011 }
2012
2013 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2014 {
2015         if (strcmp(cdr->bridge, bridge->uniqueid)) {
2016                 return 1;
2017         }
2018         if (strcasecmp(cdr->party_a.snapshot->base->name, channel->base->name)
2019                 && cdr->party_b.snapshot
2020                 && strcasecmp(cdr->party_b.snapshot->base->name, channel->base->name)) {
2021                 return 1;
2022         }
2023         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2024
2025         return 0;
2026 }
2027
2028 /* PARKED STATE */
2029
2030 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2031 {
2032         if (strcasecmp(cdr->party_a.snapshot->base->name, channel->base->name)) {
2033                 return 1;
2034         }
2035         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2036
2037         return 0;
2038 }
2039
2040 /* FINALIZED STATE */
2041
2042 static void finalized_state_init_function(struct cdr_object *cdr)
2043 {
2044         cdr_object_finalize(cdr);
2045 }
2046
2047 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2048 {
2049         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2050                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
2051                 return 0;
2052         }
2053
2054         /* Indicate that, if possible, we should get a new CDR */
2055         return 1;
2056 }
2057
2058 /*!
2059  * \internal
2060  * \brief Filter channel snapshots by technology
2061  */
2062 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2063 {
2064         return snapshot->base->tech_properties & AST_CHAN_TP_INTERNAL;
2065 }
2066
2067 /*!
2068  * \internal
2069  * \brief Filter a channel snapshot update
2070  */
2071 static int filter_channel_snapshot_message(struct ast_channel_snapshot *old_snapshot,
2072                 struct ast_channel_snapshot *new_snapshot)
2073 {
2074         int ret = 0;
2075
2076         /* Drop cache updates from certain channel technologies */
2077         if (old_snapshot) {
2078                 ret |= filter_channel_snapshot(old_snapshot);
2079         }
2080         if (new_snapshot) {
2081                 ret |= filter_channel_snapshot(new_snapshot);
2082         }
2083
2084         return ret;
2085 }
2086
2087 static int dial_status_end(const char *dialstatus)
2088 {
2089         return (strcmp(dialstatus, "RINGING") &&
2090                         strcmp(dialstatus, "PROCEEDING") &&
2091                         strcmp(dialstatus, "PROGRESS"));
2092 }
2093
2094 /* TOPIC ROUTER CALLBACKS */
2095
2096 /*!
2097  * \brief Handler for Stasis-Core dial messages
2098  * \param data Passed on
2099  * \param sub The stasis subscription for this message callback
2100  * \param topic The topic this message was published for
2101  * \param message The message
2102  */
2103 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2104 {
2105         struct cdr_object *cdr;
2106         struct ast_multi_channel_blob *payload = stasis_message_data(message);
2107         struct ast_channel_snapshot *caller;
2108         struct ast_channel_snapshot *peer;
2109         struct cdr_object *it_cdr;
2110         struct ast_json *dial_status_blob;
2111         const char *dial_status = NULL;
2112         int res = 1;
2113
2114         caller = ast_multi_channel_blob_get_channel(payload, "caller");
2115         peer = ast_multi_channel_blob_get_channel(payload, "peer");
2116         if (!peer && !caller) {
2117                 return;
2118         }
2119
2120         if (peer && filter_channel_snapshot(peer)) {
2121                 return;
2122         }
2123
2124         if (caller && filter_channel_snapshot(caller)) {
2125                 return;
2126         }
2127
2128         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2129         if (dial_status_blob) {
2130                 dial_status = ast_json_string_get(dial_status_blob);
2131         }
2132
2133         CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2134                 ast_strlen_zero(dial_status) ? "Begin" : "End",
2135                 caller ? caller->base->name : "(none)",
2136                 peer ? peer->base->name : "(none)",
2137                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2138                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2139
2140         /* Figure out who is running this show */
2141         if (caller) {
2142                 cdr = ao2_find(active_cdrs_master, caller->base->uniqueid, OBJ_SEARCH_KEY);
2143         } else {
2144                 cdr = ao2_find(active_cdrs_master, peer->base->uniqueid, OBJ_SEARCH_KEY);
2145         }
2146         if (!cdr) {
2147                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->base->name : peer->base->name);
2148                 ast_assert(0);
2149                 return;
2150         }
2151
2152         ao2_lock(cdr);
2153         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2154                 it_cdr->lastevent = *stasis_message_timestamp(message);
2155                 if (ast_strlen_zero(dial_status)) {
2156                         if (!it_cdr->fn_table->process_dial_begin) {
2157                                 continue;
2158                         }
2159                         CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2160                                 it_cdr,
2161                                 caller ? caller->base->name : "(none)",
2162                                 peer ? peer->base->name : "(none)");
2163                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2164                                         caller,
2165                                         peer);
2166                 } else if (dial_status_end(dial_status)) {
2167                         if (!it_cdr->fn_table->process_dial_end) {
2168                                 continue;
2169                         }
2170                         CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2171                                 it_cdr,
2172                                 caller ? caller->base->name : "(none)",
2173                                 peer ? peer->base->name : "(none)");
2174                         it_cdr->fn_table->process_dial_end(it_cdr,
2175                                         caller,
2176                                         peer,
2177                                         dial_status);
2178                 }
2179         }
2180
2181         /* If no CDR handled a dial begin message, make a new one */
2182         if (res && ast_strlen_zero(dial_status)) {
2183                 struct cdr_object *new_cdr;
2184
2185                 new_cdr = cdr_object_create_and_append(cdr, stasis_message_timestamp(message));
2186                 if (new_cdr) {
2187                         new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2188                 }
2189         }
2190         ao2_unlock(cdr);
2191         ao2_cleanup(cdr);
2192 }
2193
2194 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2195 {
2196         struct cdr_object *cdr = obj;
2197
2198         if (!strcasecmp(cdr->party_b_name, arg)) {
2199 #ifdef AST_DEVMODE
2200                 struct ast_channel_snapshot *party_b = data;
2201
2202                 /*
2203                  * For sanity's sake we also assert the party_b snapshot
2204                  * is consistent with the key.
2205                  */
2206                 ast_assert(cdr->party_b.snapshot
2207                         && !strcasecmp(cdr->party_b.snapshot->base->name, party_b->base->name));
2208 #endif
2209
2210                 /* Don't transition to the finalized state - let the Party A do
2211                  * that when its ready
2212                  */
2213                 cdr_object_finalize(cdr);
2214         }
2215         return 0;
2216 }
2217
2218 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2219 {
2220         struct cdr_object *cdr = obj;
2221
2222         if (cdr->fn_table->process_party_b
2223                 && !strcasecmp(cdr->party_b_name, arg)) {
2224                 struct ast_channel_snapshot *party_b = data;
2225
2226                 /*
2227                  * For sanity's sake we also check the party_b snapshot
2228                  * for consistency with the key.  The callback needs and
2229                  * asserts the snapshot to be this way.
2230                  */
2231                 if (!cdr->party_b.snapshot
2232                         || strcasecmp(cdr->party_b.snapshot->base->name, party_b->base->name)) {
2233                         ast_log(LOG_NOTICE,
2234                                 "CDR for Party A %s(%s) has inconsistent Party B %s name.  Message can be ignored but this shouldn't happen.\n",
2235                                 cdr->linkedid,
2236                                 cdr->party_a.snapshot->base->name,
2237                                 cdr->party_b_name);
2238                         return 0;
2239                 }
2240
2241                 cdr->fn_table->process_party_b(cdr, party_b);
2242         }
2243         return 0;
2244 }
2245
2246 /*! \brief Determine if we need to add a new CDR based on snapshots */
2247 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2248                 struct ast_channel_snapshot *new_snapshot)
2249 {
2250         /* If we're dead, we don't need a new CDR */
2251         if (!new_snapshot
2252                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2253                         && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN))) {
2254                 return 0;
2255         }
2256
2257         /* Auto-fall through will increment the priority but have no application */
2258         if (ast_strlen_zero(new_snapshot->dialplan->appl)) {
2259                 return 0;
2260         }
2261
2262         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2263                 return 0;
2264         }
2265
2266         return 1;
2267 }
2268
2269 /*!
2270  * \brief Handler for channel snapshot update messages
2271  * \param data Passed on
2272  * \param sub The stasis subscription for this message callback
2273  * \param topic The topic this message was published for
2274  * \param message The message
2275  */
2276 static void handle_channel_snapshot_update_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2277 {
2278         struct cdr_object *cdr;
2279         struct ast_channel_snapshot_update *update = stasis_message_data(message);
2280         struct cdr_object *it_cdr;
2281
2282         if (filter_channel_snapshot_message(update->old_snapshot, update->new_snapshot)) {
2283                 return;
2284         }
2285
2286         if (update->new_snapshot && !update->old_snapshot) {
2287                 cdr = cdr_object_alloc(update->new_snapshot, stasis_message_timestamp(message));
2288                 if (!cdr) {
2289                         return;
2290                 }
2291                 cdr->is_root = 1;
2292                 ao2_link(active_cdrs_master, cdr);
2293         } else {
2294                 cdr = ao2_find(active_cdrs_master, update->new_snapshot->base->uniqueid, OBJ_SEARCH_KEY);
2295         }
2296
2297         /* Handle Party A */
2298         if (!cdr) {
2299                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", update->new_snapshot->base->name);
2300                 ast_assert(0);
2301         } else {
2302                 int all_reject = 1;
2303
2304                 ao2_lock(cdr);
2305                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2306                         it_cdr->lastevent = *stasis_message_timestamp(message);
2307                         if (!it_cdr->fn_table->process_party_a) {
2308                                 continue;
2309                         }
2310                         all_reject &= it_cdr->fn_table->process_party_a(it_cdr, update->new_snapshot);
2311                 }
2312                 if (all_reject && check_new_cdr_needed(update->old_snapshot, update->new_snapshot)) {
2313                         /* We're not hung up and we have a new snapshot - we need a new CDR */
2314                         struct cdr_object *new_cdr;
2315
2316                         new_cdr = cdr_object_create_and_append(cdr, stasis_message_timestamp(message));
2317                         if (new_cdr) {
2318                                 new_cdr->fn_table->process_party_a(new_cdr, update->new_snapshot);
2319                         }
2320                 }
2321                 ao2_unlock(cdr);
2322         }
2323
2324         if (ast_test_flag(&update->new_snapshot->flags, AST_FLAG_DEAD)) {
2325                 ao2_lock(cdr);
2326                 CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, update->old_snapshot->base->name);
2327                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2328                         it_cdr->lastevent = *stasis_message_timestamp(message);
2329                         cdr_object_finalize(it_cdr);
2330                 }
2331                 cdr_object_dispatch(cdr);
2332                 ao2_unlock(cdr);
2333
2334                 cdr_all_unlink(cdr);
2335                 ao2_unlink(active_cdrs_master, cdr);
2336         }
2337
2338         /* Handle Party B */
2339         if (update->new_snapshot) {
2340                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2341                         cdr_object_update_party_b, (char *) update->new_snapshot->base->name, update->new_snapshot);
2342         }
2343
2344         if (ast_test_flag(&update->new_snapshot->flags, AST_FLAG_DEAD)) {
2345                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2346                         cdr_object_finalize_party_b, (char *) update->new_snapshot->base->name, update->new_snapshot);
2347         }
2348
2349         ao2_cleanup(cdr);
2350 }
2351
2352 struct bridge_leave_data {
2353         struct ast_bridge_snapshot *bridge;
2354         struct ast_channel_snapshot *channel;
2355 };
2356
2357 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2358 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2359 {
2360         struct cdr_object *cdr = obj;
2361         struct bridge_leave_data *leave_data = data;
2362
2363         if (cdr->fn_table == &bridge_state_fn_table
2364                 && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2365                 && !strcasecmp(cdr->party_b_name, arg)) {
2366                 /*
2367                  * For sanity's sake we also assert the party_b snapshot
2368                  * is consistent with the key.
2369                  */
2370                 ast_assert(cdr->party_b.snapshot
2371                         && !strcasecmp(cdr->party_b.snapshot->base->name, leave_data->channel->base->name));
2372
2373                 /* It is our Party B, in our bridge. Set the end time and let the handler
2374                  * transition our CDR appropriately when we leave the bridge.
2375                  */
2376                 cdr_object_finalize(cdr);
2377         }
2378         return 0;
2379 }
2380
2381 /*! \brief Filter bridge messages based on bridge technology */
2382 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2383 {
2384         /* Ignore holding bridge technology messages. We treat this simply as an application
2385          * that a channel enters into.
2386          */
2387         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2388                 return 1;
2389         }
2390         return 0;
2391 }
2392
2393 /*!
2394  * \brief Handler for when a channel leaves a bridge
2395  * \param data Passed on
2396  * \param sub The stasis subscription for this message callback
2397  * \param topic The topic this message was published for
2398  * \param message The message - hopefully a bridge one!
2399  */
2400 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2401                 struct stasis_message *message)
2402 {
2403         struct ast_bridge_blob *update = stasis_message_data(message);
2404         struct ast_bridge_snapshot *bridge = update->bridge;
2405         struct ast_channel_snapshot *channel = update->channel;
2406         struct cdr_object *cdr;
2407         struct cdr_object *it_cdr;
2408         struct bridge_leave_data leave_data = {
2409                 .bridge = bridge,
2410                 .channel = channel,
2411         };
2412         int left_bridge = 0;
2413
2414         if (filter_bridge_messages(bridge)) {
2415                 return;
2416         }
2417
2418         if (filter_channel_snapshot(channel)) {
2419                 return;
2420         }
2421
2422         CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2423                 channel->base->name,
2424                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2425                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2426
2427         cdr = ao2_find(active_cdrs_master, channel->base->uniqueid, OBJ_SEARCH_KEY);
2428         if (!cdr) {
2429                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2430                 ast_assert(0);
2431                 return;
2432         }
2433
2434         /* Party A */
2435         ao2_lock(cdr);
2436         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2437                 it_cdr->lastevent = *stasis_message_timestamp(message);
2438                 if (!it_cdr->fn_table->process_bridge_leave) {
2439                         continue;
2440                 }
2441                 CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2442                         it_cdr, channel->base->name);
2443                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2444                         ast_string_field_set(it_cdr, bridge, "");
2445                         left_bridge = 1;
2446                 }
2447         }
2448         ao2_unlock(cdr);
2449
2450         /* Party B */
2451         if (left_bridge
2452                 && strcmp(bridge->subclass, "parking")) {
2453                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2454                         cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->base->name,
2455                         &leave_data);
2456         }
2457
2458         ao2_cleanup(cdr);
2459 }
2460
2461 /*!
2462  * \internal
2463  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2464  *
2465  * \note The new CDR will be automatically transitioned to the bridge state
2466  */
2467 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2468                 struct cdr_object_snapshot *party_b)
2469 {
2470         struct cdr_object *new_cdr;
2471
2472         new_cdr = cdr_object_create_and_append(cdr, &cdr->lastevent);
2473         if (!new_cdr) {
2474                 return;
2475         }
2476         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2477         cdr_all_relink(new_cdr);
2478         cdr_object_check_party_a_answer(new_cdr);
2479         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2480         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2481         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2482                 new_cdr, new_cdr->party_a.snapshot->base->name,
2483                 party_b->snapshot->base->name);
2484 }
2485
2486 /*!
2487  * \brief Process a single \ref bridge_candidate
2488  *
2489  * When a CDR enters a bridge, it needs to make pairings with everyone else
2490  * that it is not currently paired with. This function determines, for the
2491  * CDR for the channel that entered the bridge and the CDR for every other
2492  * channel currently in the bridge, who is Party A and makes new CDRs.
2493  *
2494  * \param cdr The \ref cdr_obj being processed
2495  * \param cand_cdr The \ref cdr_object that is a candidate
2496  *
2497  */
2498 static void bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2499 {
2500         struct cdr_object_snapshot *party_a;
2501         struct cdr_object *cand_cdr;
2502
2503         ao2_lock(base_cand_cdr);
2504
2505         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2506                 /* Skip any records that are not in this bridge */
2507                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2508                         continue;
2509                 }
2510
2511                 /* If the candidate is us or someone we've taken on, pass on by */
2512                 if (!strcasecmp(cdr->party_a.snapshot->base->name, cand_cdr->party_a.snapshot->base->name)
2513                         || (cdr->party_b.snapshot
2514                                 && !strcasecmp(cdr->party_b.snapshot->base->name, cand_cdr->party_a.snapshot->base->name))) {
2515                         break;
2516                 }
2517
2518                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2519                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2520                  * Party B */
2521                 if (!strcasecmp(party_a->snapshot->base->name, cdr->party_a.snapshot->base->name)) {
2522                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2523                         break;
2524                 }
2525
2526                 /* We're Party B. Check if we can add ourselves immediately or if we need
2527                  * a new CDR for them (they already have a Party B) */
2528                 if (cand_cdr->party_b.snapshot
2529                         && strcasecmp(cand_cdr->party_b.snapshot->base->name, cdr->party_a.snapshot->base->name)) {
2530                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2531                 } else {
2532                         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2533                                 cand_cdr, cand_cdr->party_a.snapshot->base->name,
2534                                 cdr->party_a.snapshot->base->name);
2535                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2536                         cdr_all_relink(cand_cdr);
2537                         /* It's possible that this joined at one point and was never chosen
2538                          * as party A. Clear their end time, as it would be set in such a
2539                          * case.
2540                          */
2541                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2542                 }
2543
2544                 break;
2545         }
2546
2547         ao2_unlock(base_cand_cdr);
2548 }
2549
2550 /*!
2551  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2552  * entered a bridge
2553  * \param cdr The \ref cdr_object that just entered the bridge
2554  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2555  */
2556 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2557 {
2558         struct ao2_iterator it_channels;
2559         char *channel_id;
2560
2561         it_channels = ao2_iterator_init(bridge->channels, 0);
2562         while ((channel_id = ao2_iterator_next(&it_channels))) {
2563                 struct cdr_object *cand_cdr;
2564
2565                 cand_cdr = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
2566                 if (cand_cdr) {
2567                         bridge_candidate_process(cdr, cand_cdr);
2568                         ao2_ref(cand_cdr, -1);
2569                 }
2570
2571                 ao2_ref(channel_id, -1);
2572         }
2573         ao2_iterator_destroy(&it_channels);
2574 }
2575
2576 /*! \brief Handle entering into a parking bridge
2577  * \param cdr The CDR to operate on
2578  * \param bridge The bridge the channel just entered
2579  * \param channel The channel snapshot
2580  */
2581 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2582                 struct ast_bridge_snapshot *bridge,
2583                 struct ast_channel_snapshot *channel,
2584                 const struct timeval *event_time)
2585 {
2586         int res = 1;
2587         struct cdr_object *it_cdr;
2588         struct cdr_object *new_cdr;
2589
2590         ao2_lock(cdr);
2591
2592         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2593                 it_cdr->lastevent = *event_time;
2594
2595                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2596                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2597                 }
2598                 if (it_cdr->fn_table->process_party_a) {
2599                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2600                                 channel->base->name);
2601                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2602                 }
2603         }
2604
2605         if (res) {
2606                 /* No one handled it - we need a new one! */
2607                 new_cdr = cdr_object_create_and_append(cdr, event_time);
2608                 if (new_cdr) {
2609                         /* Let the single state transition us to Parked */
2610                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2611                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2612                 }
2613         }
2614         ao2_unlock(cdr);
2615 }
2616
2617 /*! \brief Handle a bridge enter message for a 'normal' bridge
2618  * \param cdr The CDR to operate on
2619  * \param bridge The bridge the channel just entered
2620  * \param channel The channel snapshot
2621  */
2622 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2623                 struct ast_bridge_snapshot *bridge,
2624                 struct ast_channel_snapshot *channel,
2625                 const struct timeval *event_time)
2626 {
2627         enum process_bridge_enter_results result;
2628         struct cdr_object *it_cdr;
2629         struct cdr_object *new_cdr;
2630         struct cdr_object *handled_cdr = NULL;
2631
2632         ao2_lock(cdr);
2633
2634 try_again:
2635         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2636                 it_cdr->lastevent = *event_time;
2637
2638                 if (it_cdr->fn_table->process_party_a) {
2639                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2640                                 channel->base->name);
2641                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2642                 }
2643
2644                 /* Notify all states that they have entered a bridge */
2645                 if (it_cdr->fn_table->process_bridge_enter) {
2646                         CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2647                                 channel->base->name);
2648                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2649                         switch (result) {
2650                         case BRIDGE_ENTER_ONLY_PARTY:
2651                                 /* Fall through */
2652                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2653                                 if (!handled_cdr) {
2654                                         handled_cdr = it_cdr;
2655                                 }
2656                                 break;
2657                         case BRIDGE_ENTER_NEED_CDR:
2658                                 /* Pass */
2659                                 break;
2660                         case BRIDGE_ENTER_NO_PARTY_B:
2661                                 /* We didn't win on any - end this CDR. If someone else comes in later
2662                                  * that is Party B to this CDR, it can re-activate this CDR.
2663                                  */
2664                                 if (!handled_cdr) {
2665                                         handled_cdr = it_cdr;
2666                                 }
2667                                 cdr_object_finalize(cdr);
2668                                 break;
2669                         }
2670                 }
2671         }
2672
2673         /* Create the new matchings, but only for either:
2674          *  * The first CDR in the chain that handled it. This avoids issues with
2675          *    forked CDRs.
2676          *  * If no one handled it, the last CDR in the chain. This would occur if
2677          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2678          *    to make pairings with everyone in the bridge.
2679          */
2680         if (handled_cdr) {
2681                 handle_bridge_pairings(handled_cdr, bridge);
2682         } else {
2683                 /* Nothing handled it - we need a new one! */
2684                 new_cdr = cdr_object_create_and_append(cdr, event_time);
2685                 if (new_cdr) {
2686                         /* This is guaranteed to succeed: the new CDR is created in the single state
2687                          * and will be able to handle the bridge enter message
2688                          */
2689                         goto try_again;
2690                 }
2691         }
2692         ao2_unlock(cdr);
2693 }
2694
2695 /*!
2696  * \internal
2697  * \brief Handler for Stasis-Core bridge enter messages
2698  * \param data Passed on
2699  * \param sub The stasis subscription for this message callback
2700  * \param topic The topic this message was published for
2701  * \param message The message - hopefully a bridge one!
2702  */
2703 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2704                 struct stasis_message *message)
2705 {
2706         struct ast_bridge_blob *update = stasis_message_data(message);
2707         struct ast_bridge_snapshot *bridge = update->bridge;
2708         struct ast_channel_snapshot *channel = update->channel;
2709         struct cdr_object *cdr;
2710
2711         if (filter_bridge_messages(bridge)) {
2712                 return;
2713         }
2714
2715         if (filter_channel_snapshot(channel)) {
2716                 return;
2717         }
2718
2719         CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2720                 channel->base->name,
2721                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2722                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2723
2724         cdr = ao2_find(active_cdrs_master, channel->base->uniqueid, OBJ_SEARCH_KEY);
2725         if (!cdr) {
2726                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2727                 ast_assert(0);
2728                 return;
2729         }
2730
2731         if (!strcmp(bridge->subclass, "parking")) {
2732                 handle_parking_bridge_enter_message(cdr, bridge, channel, stasis_message_timestamp(message));
2733         } else {
2734                 handle_standard_bridge_enter_message(cdr, bridge, channel, stasis_message_timestamp(message));
2735         }
2736         ao2_cleanup(cdr);
2737 }
2738
2739 /*!
2740  * \brief Handler for when a channel is parked
2741  * \param data Passed on
2742  * \param sub The stasis subscription for this message callback
2743  * \param topic The topic this message was published for
2744  * \param message The message about who got parked
2745  * */
2746 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2747                 struct stasis_message *message)
2748 {
2749         struct ast_parked_call_payload *payload = stasis_message_data(message);
2750         struct ast_channel_snapshot *channel = payload->parkee;
2751         struct cdr_object *cdr;
2752         int unhandled = 1;
2753         struct cdr_object *it_cdr;
2754
2755         /* Anything other than getting parked will be handled by other updates */
2756         if (payload->event_type != PARKED_CALL) {
2757                 return;
2758         }
2759
2760         /* No one got parked? */
2761         if (!channel) {
2762                 return;
2763         }
2764
2765         if (filter_channel_snapshot(channel)) {
2766                 return;
2767         }
2768
2769         CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2770                 channel->base->name,
2771                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2772                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2773
2774         cdr = ao2_find(active_cdrs_master, channel->base->uniqueid, OBJ_SEARCH_KEY);
2775         if (!cdr) {
2776                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->base->name);
2777                 ast_assert(0);
2778                 return;
2779         }
2780
2781         ao2_lock(cdr);
2782
2783         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2784                 it_cdr->lastevent = *stasis_message_timestamp(message);
2785                 if (it_cdr->fn_table->process_parked_channel) {
2786                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2787                 }
2788         }
2789
2790         if (unhandled) {
2791                 /* Nothing handled the messgae - we need a new one! */
2792                 struct cdr_object *new_cdr;
2793
2794                 new_cdr = cdr_object_create_and_append(cdr, stasis_message_timestamp(message));
2795                 if (new_cdr) {
2796                         /* As the new CDR is created in the single state, it is guaranteed
2797                          * to have a function for the parked call message and will handle
2798                          * the message */
2799                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2800                 }
2801         }
2802
2803         ao2_unlock(cdr);
2804
2805         ao2_cleanup(cdr);
2806 }
2807
2808 /*!
2809  * \brief Handler for a synchronization message
2810  * \param data Passed on
2811  * \param sub The stasis subscription for this message callback
2812  * \param topic The topic this message was published for
2813  * \param message A blank ao2 object
2814  * */
2815 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2816                 struct stasis_message *message)
2817 {
2818         return;
2819 }
2820
2821 struct ast_cdr_config *ast_cdr_get_config(void)
2822 {
2823         struct ast_cdr_config *general;
2824         struct module_config *mod_cfg;
2825
2826         mod_cfg = ao2_global_obj_ref(module_configs);
2827         if (!mod_cfg) {
2828                 return NULL;
2829         }
2830         general = ao2_bump(mod_cfg->general);
2831         ao2_cleanup(mod_cfg);
2832         return general;
2833 }
2834
2835 void ast_cdr_set_config(struct ast_cdr_config *config)
2836 {
2837         struct module_config *mod_cfg;
2838
2839         if (!config) {
2840                 return;
2841         }
2842
2843         mod_cfg = ao2_global_obj_ref(module_configs);
2844         if (!mod_cfg) {
2845                 return;
2846         }
2847
2848         ao2_replace(mod_cfg->general, config);
2849
2850         cdr_set_debug_mode(mod_cfg);
2851         cdr_toggle_runtime_options();
2852
2853         ao2_cleanup(mod_cfg);
2854 }
2855
2856 int ast_cdr_is_enabled(void)
2857 {
2858         return is_cdr_flag_set(CDR_ENABLED);
2859 }
2860
2861 int ast_cdr_backend_suspend(const char *name)
2862 {
2863         int success = -1;
2864         struct cdr_beitem *i = NULL;
2865
2866         AST_RWLIST_WRLOCK(&be_list);
2867         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2868                 if (!strcasecmp(name, i->name)) {
2869                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2870                         i->suspended = 1;
2871                         success = 0;
2872                 }
2873         }
2874         AST_RWLIST_UNLOCK(&be_list);
2875
2876         return success;
2877 }
2878
2879 int ast_cdr_backend_unsuspend(const char *name)
2880 {
2881         int success = -1;
2882         struct cdr_beitem *i = NULL;
2883
2884         AST_RWLIST_WRLOCK(&be_list);
2885         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2886                 if (!strcasecmp(name, i->name)) {
2887                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2888                         i->suspended = 0;
2889                         success = 0;
2890                 }
2891         }
2892         AST_RWLIST_UNLOCK(&be_list);
2893
2894         return success;
2895 }
2896
2897 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2898 {
2899         struct cdr_beitem *i;
2900         struct cdr_beitem *cur;
2901
2902         if (!name) {
2903                 return -1;
2904         }
2905
2906         if (!be) {
2907                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2908
2909                 return -1;
2910         }
2911
2912         i = ast_calloc(1, sizeof(*i));
2913         if (!i) {
2914                 return -1;
2915         }
2916
2917         i->be = be;
2918         ast_copy_string(i->name, name, sizeof(i->name));
2919         ast_copy_string(i->desc, desc, sizeof(i->desc));
2920
2921         AST_RWLIST_WRLOCK(generic_list);
2922         AST_RWLIST_TRAVERSE(generic_list, cur, list) {
2923                 if (!strcasecmp(name, cur->name)) {
2924                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2925                         AST_RWLIST_UNLOCK(generic_list);
2926                         ast_free(i);
2927
2928                         return -1;
2929                 }
2930         }
2931
2932         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2933         AST_RWLIST_UNLOCK(generic_list);
2934
2935         return 0;
2936 }
2937
2938 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2939 {
2940         return cdr_generic_register(&be_list, name, desc, be);
2941 }
2942
2943 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2944 {
2945         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2946 }
2947
2948 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2949 {
2950         struct cdr_beitem *match = NULL;
2951         int active_count;
2952
2953         AST_RWLIST_WRLOCK(generic_list);
2954         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2955                 if (!strcasecmp(name, match->name)) {
2956                         break;
2957                 }
2958         }
2959
2960         if (!match) {
2961                 AST_RWLIST_UNLOCK(generic_list);
2962                 return 0;
2963         }
2964
2965         active_count = ao2_container_count(active_cdrs_master);
2966
2967         if (!match->suspended && active_count != 0) {
2968                 AST_RWLIST_UNLOCK(generic_list);
2969                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2970                         name, active_count);
2971                 return -1;
2972         }
2973
2974         AST_RWLIST_REMOVE(generic_list, match, list);
2975         AST_RWLIST_UNLOCK(generic_list);
2976
2977         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2978         ast_free(match);
2979
2980         return 0;
2981 }
2982
2983 int ast_cdr_unregister(const char *name)
2984 {
2985         return ast_cdr_generic_unregister(&be_list, name);
2986 }
2987
2988 int ast_cdr_modifier_unregister(const char *name)
2989 {
2990         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2991 }
2992
2993 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2994 {
2995         struct ast_cdr *newcdr;
2996
2997         if (!cdr) {
2998                 return NULL;
2999         }
3000         newcdr = ast_cdr_alloc();
3001         if (!newcdr) {
3002                 return NULL;
3003         }
3004
3005         *newcdr = *cdr;
3006         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
3007         copy_variables(&newcdr->varshead, &cdr->varshead);
3008         newcdr->next = NULL;
3009
3010         return newcdr;
3011 }
3012
3013 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
3014 {
3015         struct ast_var_t *variables;
3016
3017         if (ast_strlen_zero(name)) {
3018                 return NULL;
3019         }
3020
3021         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
3022                 if (!strcasecmp(name, ast_var_name(variables))) {
3023                         return ast_var_value(variables);
3024                 }
3025         }
3026
3027         return NULL;
3028 }
3029
3030 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
3031 {
3032         if (fmt == NULL) {      /* raw mode */
3033                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
3034         } else {
3035                 buf[0] = '\0';/* Ensure the buffer is initialized. */
3036                 if (when.tv_sec) {
3037                         struct ast_tm tm;
3038
3039                         ast_localtime(&when, &tm, NULL);
3040                         ast_strftime(buf, bufsize, fmt, &tm);
3041                 }
3042         }
3043 }
3044
3045 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
3046 {
3047         const char *fmt = "%Y-%m-%d %T";
3048         const char *varbuf;
3049
3050         if (!cdr) {
3051                 return;
3052         }
3053
3054         *ret = NULL;
3055
3056         if (!strcasecmp(name, "clid")) {
3057                 ast_copy_string(workspace, cdr->clid, workspacelen);
3058         } else if (!strcasecmp(name, "src")) {
3059                 ast_copy_string(workspace, cdr->src, workspacelen);
3060         } else if (!strcasecmp(name, "dst")) {
3061                 ast_copy_string(workspace, cdr->dst, workspacelen);
3062         } else if (!strcasecmp(name, "dcontext")) {
3063                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
3064         } else if (!strcasecmp(name, "channel")) {
3065                 ast_copy_string(workspace, cdr->channel, workspacelen);
3066         } else if (!strcasecmp(name, "dstchannel")) {
3067                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3068         } else if (!strcasecmp(name, "lastapp")) {
3069                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
3070         } else if (!strcasecmp(name, "lastdata")) {
3071                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
3072         } else if (!strcasecmp(name, "start")) {
3073                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3074         } else if (!strcasecmp(name, "answer")) {
3075                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3076         } else if (!strcasecmp(name, "end")) {
3077                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3078         } else if (!strcasecmp(name, "duration")) {
3079                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3080         } else if (!strcasecmp(name, "billsec")) {
3081                 snprintf(workspace, workspacelen, "%ld", (cdr->billsec || !ast_tvzero(cdr->end) || ast_tvzero(cdr->answer)) ? cdr->billsec : (long)ast_tvdiff_ms(ast_tvnow(), cdr->answer) / 1000);
3082         } else if (!strcasecmp(name, "disposition")) {
3083                 if (raw) {
3084                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3085                 } else {
3086                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3087                 }
3088         } else if (!strcasecmp(name, "amaflags")) {
3089                 if (raw) {
3090                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3091                 } else {
3092                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3093                 }
3094         } else if (!strcasecmp(name, "accountcode")) {
3095                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
3096         } else if (!strcasecmp(name, "peeraccount")) {
3097                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3098         } else if (!strcasecmp(name, "uniqueid")) {
3099                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3100         } else if (!strcasecmp(name, "linkedid")) {
3101                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
3102         } else if (!strcasecmp(name, "userfield")) {
3103                 ast_copy_string(workspace, cdr->userfield, workspacelen);
3104         } else if (!strcasecmp(name, "sequence")) {
3105                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
3106         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3107                 ast_copy_string(workspace, varbuf, workspacelen);
3108         } else {
3109                 workspace[0] = '\0';
3110         }
3111
3112         if (!ast_strlen_zero(workspace)) {
3113                 *ret = workspace;
3114         }
3115 }
3116
3117 /*!
3118  * \internal
3119  * \brief Callback that finds all CDRs that reference a particular channel by name
3120  */
3121 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
3122 {
3123         struct cdr_object *cdr = obj;
3124         const char *name = arg;
3125
3126         if (!strcasecmp(cdr->party_a.snapshot->base->name, name) ||
3127                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->base->name, name))) {
3128                 return CMP_MATCH;
3129         }
3130         return 0;
3131 }
3132
3133 /*!
3134  * \internal
3135  * \brief Callback that finds a CDR by channel name
3136  */
3137 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3138 {
3139         struct cdr_object *cdr = obj;
3140         const char *name = arg;
3141
3142         if (!strcasecmp(cdr->party_a.snapshot->base->name, name)) {
3143                 return CMP_MATCH;
3144         }
3145         return 0;
3146 }
3147
3148 /* Read Only CDR variables */
3149 static const char * const cdr_readonly_vars[] = {
3150         "clid",
3151         "src",
3152         "dst",
3153         "dcontext",
3154         "channel",
3155         "dstchannel",
3156         "lastapp",
3157         "lastdata",
3158         "start",
3159         "answer",
3160         "end",
3161         "duration",
3162         "billsec",
3163         "disposition",
3164         "amaflags",
3165         "accountcode",
3166         "uniqueid",
3167         "linkedid",
3168         "userfield",
3169         "sequence",
3170         NULL
3171 };
3172
3173 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3174 {
3175         struct cdr_object *cdr;
3176         struct cdr_object *it_cdr;
3177         struct ao2_iterator *it_cdrs;
3178         char *arg = ast_strdupa(channel_name);
3179         int x;
3180
3181         for (x = 0; cdr_readonly_vars[x]; x++) {
3182                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
3183                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3184                         return -1;
3185                 }
3186         }
3187
3188         it_cdrs = ao2_callback(active_cdrs_master, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
3189         if (!it_cdrs) {
3190                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3191                 return -1;
3192         }
3193
3194         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3195                 ao2_lock(cdr);
3196                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3197                         struct varshead *headp = NULL;
3198
3199                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3200                                 continue;
3201                         }
3202                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->base->name)) {
3203                                 headp = &it_cdr->party_a.variables;
3204                         } else if (it_cdr->party_b.snapshot
3205                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->base->name)) {
3206                                 headp = &it_cdr->party_b.variables;
3207                         }
3208                         if (headp) {
3209                                 set_variable(headp, name, value);
3210                         }
3211                 }
3212         }
3213         ao2_iterator_destroy(it_cdrs);
3214
3215         return 0;
3216 }
3217
3218 /*!
3219  * \brief Format a variable on a \ref cdr_object
3220  */
3221 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3222 {
3223         struct ast_var_t *variable;
3224
3225         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3226                 if (!strcasecmp(name, ast_var_name(variable))) {
3227                         ast_copy_string(value, ast_var_value(variable), length);
3228                         return;
3229                 }
3230         }
3231
3232         *value = '\0';
3233 }
3234
3235 /*!
3236  * \brief Format one of the standard properties on a \ref cdr_object
3237  */
3238 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3239 {
3240         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3241         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3242
3243         if (!strcasecmp(name, "clid")) {
3244                 ast_callerid_merge(value, length, party_a->caller->name, party_a->caller->number, "");
3245         } else if (!strcasecmp(name, "src")) {
3246                 ast_copy_string(value, party_a->caller->number, length);
3247         } else if (!strcasecmp(name, "dst")) {
3248                 ast_copy_string(value, party_a->dialplan->exten, length);
3249         } else if (!strcasecmp(name, "dcontext")) {
3250                 ast_copy_string(value, party_a->dialplan->context, length);
3251         } else if (!strcasecmp(name, "channel")) {
3252                 ast_copy_string(value, party_a->base->name, length);
3253         } else if (!strcasecmp(name, "dstchannel")) {
3254                 if (party_b) {
3255                         ast_copy_string(value, party_b->base->name, length);
3256                 } else {
3257                         ast_copy_string(value, "", length);
3258                 }
3259         } else if (!strcasecmp(name, "lastapp")) {
3260                 ast_copy_string(value, party_a->dialplan->appl, length);
3261         } else if (!strcasecmp(name, "lastdata")) {
3262                 ast_copy_string(value, party_a->dialplan->data, length);
3263         } else if (!strcasecmp(name, "start")) {
3264                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3265         } else if (!strcasecmp(name, "answer")) {
3266                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3267         } else if (!strcasecmp(name, "end")) {
3268                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3269         } else if (!strcasecmp(name, "duration")) {
3270                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3271         } else if (!strcasecmp(name, "billsec")) {
3272                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3273         } else if (!strcasecmp(name, "disposition")) {
3274                 snprintf(value, length, "%u", cdr_obj->disposition);
3275         } else if (!strcasecmp(name, "amaflags")) {
3276                 snprintf(value, length, "%d", party_a->amaflags);
3277         } else if (!strcasecmp(name, "accountcode")) {
3278                 ast_copy_string(value, party_a->base->accountcode, length);
3279         } else if (!strcasecmp(name, "peeraccount")) {
3280                 if (party_b) {
3281                         ast_copy_string(value, party_b->base->accountcode, length);
3282                 } else {
3283                         ast_copy_string(value, "", length);
3284                 }
3285         } else if (!strcasecmp(name, "uniqueid")) {
3286                 ast_copy_string(value, party_a->base->uniqueid, length);
3287         } else if (!strcasecmp(name, "linkedid")) {
3288                 ast_copy_string(value, cdr_obj->linkedid, length);
3289         } else if (!strcasecmp(name, "userfield")) {
3290                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3291         } else if (!strcasecmp(name, "sequence")) {
3292                 snprintf(value, length, "%u", cdr_obj->sequence);
3293         } else {
3294                 return 1;
3295         }
3296
3297         return 0;
3298 }
3299
3300 /*! \internal
3301  * \brief Look up and retrieve a CDR object by channel name
3302  * \param name The name of the channel
3303  * \retval NULL on error
3304  * \retval The \ref cdr_object for the channel on success, with the reference
3305  *      count bumped by one.
3306  */
3307 static struct cdr_object *cdr_object_get_by_name(const char *name)
3308 {
3309         char *param;
3310
3311         if (ast_strlen_zero(name)) {
3312                 return NULL;
3313         }
3314
3315         param = ast_strdupa(name);
3316         return ao2_callback(active_cdrs_master, 0, cdr_object_get_by_name_cb, param);
3317 }
3318
3319 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3320 {
3321         struct cdr_object *cdr;
3322         struct cdr_object *cdr_obj;
3323
3324         if (ast_strlen_zero(name)) {
3325                 return 1;
3326         }
3327
3328         cdr = cdr_object_get_by_name(channel_name);
3329         if (!cdr) {
3330                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3331                 return 1;
3332         }
3333
3334         ao2_lock(cdr);
3335
3336         cdr_obj = cdr->last;
3337         if (cdr_object_format_property(cdr_obj, name, value, length)) {
3338                 /* Property failed; attempt variable */
3339                 cdr_object_format_var_internal(cdr_obj, name, value, length);
3340         }
3341
3342         ao2_unlock(cdr);
3343
3344         ao2_cleanup(cdr);
3345         return 0;
3346 }
3347
3348 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
3349 {
3350         struct cdr_object *cdr;
3351         struct cdr_object *it_cdr;
3352         struct ast_var_t *variable;
3353         const char *var;
3354         char workspace[256];
3355         int total = 0, x = 0, i;
3356
3357         cdr = cdr_object_get_by_name(channel_name);
3358         if (!cdr) {
3359                 if (is_cdr_flag_set(CDR_ENABLED)) {
3360                         ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3361                 }
3362                 return 0;
3363         }
3364
3365         ast_str_reset(*buf);
3366
3367         ao2_lock(cdr);
3368         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3369                 if (++x > 1) {
3370                         ast_str_append(buf, 0, "\n");
3371                 }
3372
3373                 AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
3374                         if (!(var = ast_var_name(variable))) {
3375                                 continue;
3376                         }
3377
3378                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variable), ""), sep) < 0) {
3379                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3380                                 break;
3381                         }
3382
3383                         total++;
3384                 }
3385
3386                 for (i = 0; cdr_readonly_vars[i]; i++) {
3387                         if (cdr_object_format_property(it_cdr, cdr_readonly_vars[i], workspace, sizeof(workspace))) {
3388                                 /* Unhandled read-only CDR variable. */
3389                                 ast_assert(0);
3390                                 continue;
3391                         }
3392
3393                         if (!ast_strlen_zero(workspace)
3394                                 && ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, workspace, sep) < 0) {
3395                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3396                                 break;
3397                         }
3398                         total++;
3399                 }
3400         }
3401         ao2_unlock(cdr);
3402         ao2_cleanup(cdr);
3403         return total;
3404 }
3405
3406 void ast_cdr_free(struct ast_cdr *cdr)
3407 {
3408         while (cdr) {
3409                 struct ast_cdr *next = cdr->next;
3410
3411                 free_variables(&cdr->varshead);
3412                 ast_free(cdr);
3413                 cdr = next;
3414         }
3415 }
3416
3417 struct ast_cdr *ast_cdr_alloc(void)
3418 {
3419         struct ast_cdr *x;
3420
3421         x = ast_calloc(1, sizeof(*x));
3422         return x;
3423 }
3424
3425 const char *ast_cdr_disp2str(int disposition)
3426 {
3427         switch (disposition) {
3428         case AST_CDR_NULL:
3429                 return "NO ANSWER"; /* by default, for backward compatibility */
3430         case AST_CDR_NOANSWER:
3431                 return "NO ANSWER";
3432         case AST_CDR_FAILED:
3433                 return "FAILED";
3434         case AST_CDR_BUSY:
3435                 return "BUSY";
3436         case AST_CDR_ANSWERED:
3437                 return "ANSWERED";
3438         case AST_CDR_CONGESTION:
3439                 return "CONGESTION";
3440         }
3441         return "UNKNOWN";
3442 }
3443
3444 struct party_b_userfield_update {
3445         const char *channel_name;
3446         const char *userfield;
3447 };
3448
3449 /*! \brief Callback used to update the userfield on Party B on all CDRs */
3450 static int cdr_object_update_party_b_userfield_cb(void *obj, void *arg, void *data, int flags)
3451 {
3452         struct cdr_object *cdr = obj;
3453
3454         if ((cdr->fn_table != &finalized_state_fn_table || !cdr->next)
3455                 && !strcasecmp(cdr->party_b_name, arg)) {
3456                 struct party_b_userfield_update *info = data;
3457
3458                 /*
3459                  * For sanity's sake we also assert the party_b snapshot
3460                  * is consistent with the key.
3461                  */
3462                 ast_assert(cdr->party_b.snapshot
3463                         && !strcasecmp(cdr->party_b.snapshot->base->name, info->channel_name));
3464
3465                 ast_copy_string(cdr->party_b.userfield, info->userfield,
3466                         sizeof(cdr->party_b.userfield));
3467         }
3468
3469         return 0;
3470 }
3471
3472 void ast_cdr_setuserfield(const char *channel_name, const char *userfield)
3473 {
3474         struct cdr_object *cdr;
3475         struct party_b_userfield_update party_b_info = {
3476                 .channel_name = channel_name,
3477                 .userfield = userfield,
3478         };
3479         struct cdr_object *it_cdr;
3480
3481         /* Handle Party A */
3482         cdr = cdr_object_get_by_name(channel_name);
3483         if (cdr) {
3484                 ao2_lock(cdr);
3485                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3486                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3487                                 continue;
3488                         }
3489                         ast_copy_string(it_cdr->party_a.userfield, userfield,
3490                                 sizeof(it_cdr->party_a.userfield));
3491                 }
3492                 ao2_unlock(cdr);
3493         }
3494
3495         /* Handle Party B */
3496         ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
3497                 cdr_object_update_party_b_userfield_cb, (char *) party_b_info.channel_name,
3498                 &party_b_info);
3499
3500         ao2_cleanup(cdr);
3501 }
3502
3503 static void post_cdr(struct ast_cdr *cdr)
3504 {
3505         struct module_config *mod_cfg;
3506         struct cdr_beitem *i;
3507
3508         mod_cfg = ao2_global_obj_ref(module_configs);
3509         if (!mod_cfg) {
3510                 return;
3511         }
3512
3513         for (; cdr ; cdr = cdr->next) {
3514                 /* For people, who don't want to see unanswered single-channel events */
3515                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) &&
3516                                 cdr->disposition < AST_CDR_ANSWERED &&
3517                                 (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
3518                         ast_debug(1, "Skipping CDR for %s since we weren't answered\n", cdr->channel);
3519                         continue;
3520                 }
3521
3522                 /* Modify CDR's */
3523                 AST_RWLIST_RDLOCK(&mo_list);
3524                 AST_RWLIST_TRAVERSE(&mo_list, i, list) {
3525                         i->be(cdr);
3526                 }
3527                 AST_RWLIST_UNLOCK(&mo_list);
3528
3529                 if (ast_test_flag(cdr, AST_CDR_FLAG_DISABLE)) {
3530                         continue;
3531                 }
3532                 AST_RWLIST_RDLOCK(&be_list);
3533                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
3534                         if (!i->suspended) {
3535                                 i->be(cdr);
3536                         }
3537                 }
3538                 AST_RWLIST_UNLOCK(&be_list);
3539         }
3540         ao2_cleanup(mod_cfg);
3541 }
3542
3543 int ast_cdr_set_property(const char *channel_name, enum ast_cdr_options option)
3544 {
3545         struct cdr_object *cdr;
3546         struct cdr_object *it_cdr;
3547
3548         cdr = cdr_object_get_by_name(channel_name);
3549         if (!cdr) {
3550                 return -1;
3551         }
3552
3553         ao2_lock(cdr);
3554         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3555                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3556                         continue;
3557                 }
3558                 /* Note: in general, set the flags on both the CDR record as well as the
3559                  * Party A. Sometimes all we have is the Party A to look at.
3560                  */
3561                 ast_set_flag(&it_cdr->flags, option);
3562                 ast_set_flag(&it_cdr->party_a, option);
3563         }
3564         ao2_unlock(cdr);
3565
3566         ao2_cleanup(cdr);
3567         return 0;
3568 }
3569
3570 int ast_cdr_clear_property(const char *channel_name, enum ast_cdr_options option)
3571 {
3572         struct cdr_object *cdr;
3573         struct cdr_object *it_cdr;
3574
3575         cdr = cdr_object_get_by_name(channel_name);
3576         if (!cdr) {
3577                 return -1;
3578         }
3579
3580         ao2_lock(cdr);
3581         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3582                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3583                         continue;
3584                 }
3585                 ast_clear_flag(&it_cdr->flags, option);
3586         }
3587         ao2_unlock(cdr);
3588
3589         ao2_cleanup(cdr);
3590         return 0;
3591 }
3592
3593 int ast_cdr_reset(const char *channel_name, int keep_variables)
3594 {
3595         struct cdr_object *cdr;
3596         struct ast_var_t *vardata;
3597         struct cdr_object *it_cdr;
3598
3599         cdr = cdr_object_get_by_name(channel_name);
3600         if (!cdr) {
3601                 return -1;
3602         }
3603
3604         ao2_lock(cdr);
3605         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3606                 /* clear variables */
3607                 if (!keep_variables) {
3608                         while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_a.variables, entries))) {
3609                                 ast_var_delete(vardata);
3610                         }
3611                         if (cdr->party_b.snapshot) {
3612                                 while ((vardata = AST_LIST_REMOVE_HEAD(&it_cdr->party_b.variables, entries))) {
3613                                         ast_var_delete(vardata);
3614                                 }
3615                         }
3616                 }
3617
3618                 /* Reset to initial state */
3619                 memset(&it_cdr->start, 0, sizeof(it_cdr->start));
3620                 memset(&it_cdr->end, 0, sizeof(it_cdr->end));
3621                 memset(&it_cdr->answer, 0, sizeof(it_cdr->answer));
3622                 it_cdr->start = ast_tvnow();
3623                 it_cdr->lastevent = it_cdr->start;
3624                 cdr_object_check_party_a_answer(it_cdr);
3625         }
3626         ao2_unlock(cdr);
3627
3628         ao2_cleanup(cdr);
3629         return 0;
3630 }
3631
3632 int ast_cdr_fork(const char *channel_name, struct ast_flags *options)
3633 {
3634         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3635         struct cdr_object *new_cdr;
3636         struct cdr_object *it_cdr;
3637         struct cdr_object *cdr_obj;
3638
3639         if (!cdr) {
3640                 return -1;
3641         }
3642
3643         {
3644                 SCOPED_AO2LOCK(lock, cdr);
3645                 struct timeval now = ast_tvnow();
3646
3647                 cdr_obj = cdr->last;
3648                 if (cdr_obj->fn_table == &finalized_state_fn_table) {
3649                         /* If the last CDR in the chain is finalized, don't allow a fork -
3650                          * things are already dying at this point
3651                          */
3652                         return -1;
3653                 }
3654
3655                 /* Copy over the basic CDR information. The Party A information is
3656                  * copied over automatically as part of the append
3657                  */
3658                 ast_debug(1, "Forking CDR for channel %s\n", cdr->party_a.snapshot->base->name);
3659                 new_cdr = cdr_object_create_and_append(cdr, &now);
3660                 if (!new_cdr) {
3661                         return -1;
3662                 }
3663                 new_cdr->fn_table = cdr_obj->fn_table;
3664                 ast_string_field_set(new_cdr, bridge, cdr->bridge);
3665                 ast_string_field_set(new_cdr, appl, cdr->appl);
3666                 ast_string_field_set(new_cdr, data, cdr->data);
3667                 ast_string_field_set(new_cdr, context, cdr->context);
3668                 ast_string_field_set(new_cdr, exten, cdr->exten);
3669                 new_cdr->flags = cdr->flags;
3670                 /* Explicitly clear the AST_CDR_LOCK_APP flag - we want
3671                  * the application to be changed on the new CDR if the
3672                  * dialplan demands it
3673                  */
3674                 ast_clear_flag(&new_cdr->flags, AST_CDR_LOCK_APP);
3675
3676                 /* If there's a Party B, copy it over as well */
3677                 if (cdr_obj->party_b.snapshot) {
3678                         new_cdr->party_b.snapshot = cdr_obj->party_b.snapshot;
3679                         ao2_ref(new_cdr->party_b.snapshot, +1);
3680                         cdr_all_relink(new_cdr);
3681                         strcpy(new_cdr->party_b.userfield, cdr_obj->party_b.userfield);
3682                         new_cdr->party_b.flags = cdr_obj->party_b.flags;
3683                         if (ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3684                                 copy_variables(&new_cdr->party_b.variables, &cdr_obj->party_b.variables);
3685                         }
3686                 }
3687                 new_cdr->start = cdr_obj->start;
3688                 new_cdr->answer = cdr_obj->answer;
3689                 new_cdr->lastevent = ast_tvnow();
3690
3691                 /* Modify the times based on the flags passed in */
3692                 if (ast_test_flag(options, AST_CDR_FLAG_SET_ANSWER)
3693                                 && new_cdr->party_a.snapshot->state == AST_STATE_UP) {
3694                         new_cdr->answer = ast_tvnow();
3695                 }
3696                 if (ast_test_flag(options, AST_CDR_FLAG_RESET)) {
3697                         new_cdr->answer = ast_tvnow();
3698                         new_cdr->start = ast_tvnow();
3699                 }
3700
3701                 /* Create and append, by default, copies over the variables */
3702                 if (!ast_test_flag(options, AST_CDR_FLAG_KEEP_VARS)) {
3703                         free_variables(&new_cdr->party_a.variables);
3704                 }
3705
3706                 /* Finalize any current CDRs */
3707                 if (ast_test_flag(options, AST_CDR_FLAG_FINALIZE)) {
3708                         for (it_cdr = cdr; it_cdr != new_cdr; it_cdr = it_cdr->next) {
3709                                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3710                                         continue;
3711                                 }
3712                                 /* Force finalization on the CDR. This will bypass any checks for
3713                                  * end before 'h' extension.
3714                                  */
3715                                 cdr_object_finalize(it_cdr);
3716                                 cdr_object_transition_state(it_cdr, &finalized_state_fn_table);
3717                         }
3718                 }
3719         }
3720
3721         return 0;
3722 }
3723
3724 /*! \note Don't call without cdr_batch_lock */
3725 static void reset_batch(void)
3726 {
3727         batch->size = 0;
3728         batch->head = NULL;
3729         batch->tail = NULL;
3730 }
3731
3732 /*! \note Don't call without cdr_batch_lock */
3733 static int init_batch(void)
3734 {
3735         /* This is the single meta-batch used to keep track of all CDRs during the entire life of the program */
3736         if (!(batch = ast_malloc(sizeof(*batch))))
3737                 return -1;
3738
3739         reset_batch();
3740
3741         return 0;
3742 }
3743
3744 static void *do_batch_backend_process(void *data)
3745 {
3746         struct cdr_batch_item *processeditem;
3747         struct cdr_batch_item *batchitem = data;
3748
3749         /* Push each CDR into storage mechanism(s) and free all the memory */
3750         while (batchitem) {
3751                 post_cdr(batchitem->cdr);
3752                 ast_cdr_free(batchitem->cdr);
3753                 processeditem = batchitem;
3754                 batchitem = batchitem->next;
3755                 ast_free(processeditem);
3756         }
3757
3758         return NULL;
3759 }
3760
3761 static void cdr_submit_batch(int do_shutdown)
3762 {
3763         struct module_config *mod_cfg;
3764         struct cdr_batch_item *oldbatchitems = NULL;
3765         pthread_t batch_post_thread = AST_PTHREADT_NULL;
3766
3767         /* if there's no batch, or no CDRs in the batch, then there's nothing to do */
3768         if (!batch || !batch->head) {
3769                 return;
3770         }
3771
3772         /* move the old CDRs aside, and prepare a new CDR batch */
3773         ast_mutex_lock(&cdr_batch_lock);
3774         oldbatchitems = batch->head;
3775         reset_batch();
3776         ast_mutex_unlock(&cdr_batch_lock);
3777
3778         mod_cfg = ao2_global_obj_ref(module_configs);
3779
3780         /* if configured, spawn a new thread to post these CDRs,
3781            also try to save as much as possible if we are shutting down safely */
3782         if (!mod_cfg
3783                 || ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY)
3784                 || do_shutdown) {
3785                 ast_debug(1, "CDR single-threaded batch processing begins now\n");
3786                 do_batch_backend_process(oldbatchitems);
3787         } else {
3788                 if (ast_pthread_create_detached_background(&batch_post_thread, NULL, do_batch_backend_process, oldbatchitems)) {
3789                         ast_log(LOG_WARNING, "CDR processing thread could not detach, now trying in this thread\n");
3790                         do_batch_backend_process(oldbatchitems);
3791                 } else {
3792                         ast_debug(1, "CDR multi-threaded batch processing begins now\n");
3793                 }
3794         }
3795
3796         ao2_cleanup(mod_cfg);
3797 }
3798
3799 static int submit_scheduled_batch(const void *data)
3800 {
3801         struct module_config *mod_cfg;
3802         int nextms;
3803
3804         cdr_submit_batch(0);
3805
3806         mod_cfg = ao2_global_obj_ref(module_configs);
3807         if (!mod_cfg) {
3808                 return 0;
3809         }
3810
3811         /* Calculate the next scheduled interval */
3812         nextms = mod_cfg->general->batch_settings.time * 1000;
3813
3814         ao2_cleanup(mod_cfg);
3815
3816         return nextms;
3817 }
3818
3819 /*! Do not hold the batch lock while calling this function */
3820 static void start_batch_mode(void)
3821 {
3822         /* Prevent two deletes from happening at the same time */
3823         ast_mutex_lock(&cdr_sched_lock);
3824         /* this is okay since we are not being called from within the scheduler */
3825         AST_SCHED_DEL(sched, cdr_sched);
3826         /* schedule the submission to occur ASAP (1 ms) */
3827         cdr_sched = ast_sched_add_variable(sched, 1, submit_scheduled_batch, NULL, 1);
3828         ast_mutex_unlock(&cdr_sched_lock);
3829
3830         /* signal the do_cdr thread to wakeup early and do some work (that lazy thread ;) */
3831         ast_mutex_lock(&cdr_pending_lock);
3832         ast_cond_signal(&cdr_pending_cond);
3833         ast_mutex_unlock(&cdr_pending_lock);
3834 }
3835
3836 static void cdr_detach(struct ast_cdr *cdr)
3837 {
3838         struct cdr_batch_item *newtail;
3839         int curr;
3840         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3841         int submit_batch = 0;
3842
3843         if (!cdr) {
3844                 return;
3845         }
3846
3847         /* maybe they disabled CDR stuff completely, so just drop it */
3848         if (!mod_cfg || !ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3849                 ast_debug(1, "Dropping CDR !\n");
3850                 ast_cdr_free(cdr);
3851                 return;
3852         }
3853
3854         /* post stuff immediately if we are not in batch mode, this is legacy behaviour */
3855         if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
3856                 post_cdr(cdr);
3857                 ast_cdr_free(cdr);
3858                 return;
3859         }
3860
3861         /* otherwise, each CDR gets put into a batch list (at the end) */
3862         ast_debug(1, "CDR detaching from this thread\n");
3863
3864         /* we'll need a new tail for every CDR */
3865         if (!(newtail = ast_calloc(1, sizeof(*newtail)))) {
3866                 post_cdr(cdr);
3867                 ast_cdr_free(cdr);
3868                 return;
3869         }
3870
3871         /* don't traverse a whole list (just keep track of the tail) */
3872         ast_mutex_lock(&cdr_batch_lock);
3873         if (!batch)
3874                 init_batch();
3875         if (!batch->head) {
3876                 /* new batch is empty, so point the head at the new tail */
3877                 batch->head = newtail;
3878         } else {
3879                 /* already got a batch with something in it, so just append a new tail */
3880                 batch->tail->next = newtail;
3881         }
3882         newtail->cdr = cdr;
3883         batch->tail = newtail;
3884         curr = batch->size++;
3885
3886         /* if we have enough stuff to post, then do it */
3887         if (curr >= (mod_cfg->general->batch_settings.size - 1)) {
3888                 submit_batch = 1;
3889         }
3890         ast_mutex_unlock(&cdr_batch_lock);
3891
3892         /* Don't submit a batch with cdr_batch_lock held */
3893         if (submit_batch) {
3894                 start_batch_mode();
3895         }
3896 }
3897
3898 static void *do_cdr(void *data)
3899 {
3900         struct timespec timeout;
3901         int schedms;
3902         int numevents = 0;
3903
3904         for (;;) {
3905                 struct timeval now;
3906                 schedms = ast_sched_wait(sched);
3907                 /* this shouldn't happen, but provide a 1 second default just in case */
3908                 if (schedms < 0)
3909                         schedms = 1000;
3910                 now = ast_tvadd(ast_tvnow(), ast_samp2tv(schedms, 1000));
3911                 timeout.tv_sec = now.tv_sec;
3912                 timeout.tv_nsec = now.tv_usec * 1000;
3913                 /* prevent stuff from clobbering cdr_pending_cond, then wait on signals sent to it until the timeout expires */
3914                 ast_mutex_lock(&cdr_pending_lock);
3915                 ast_cond_timedwait(&cdr_pending_cond, &cdr_pending_lock, &timeout);
3916                 numevents = ast_sched_runq(sched);
3917                 ast_mutex_unlock(&cdr_pending_lock);
3918                 ast_debug(2, "Processed %d CDR batches from the run queue\n", numevents);
3919         }
3920
3921         return NULL;
3922 }
3923
3924 static char *handle_cli_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3925 {
3926         struct module_config *mod_cfg;
3927
3928         switch (cmd) {
3929         case CLI_INIT:
3930                 e->command = "cdr set debug [on|off]";
3931                 e->usage = "Enable or disable extra debugging in the CDR Engine. Note\n"
3932                                 "that this will dump debug information to the VERBOSE setting\n"
3933                                 "and should only be used when debugging information from the\n"
3934                                 "CDR engine is needed.\n";
3935                 return NULL;
3936         case CLI_GENERATE:
3937                 return NULL;
3938         }
3939
3940         if (a->argc != 4) {
3941                 return CLI_SHOWUSAGE;
3942         }
3943
3944         mod_cfg = ao2_global_obj_ref(module_configs);
3945         if (!mod_cfg) {
3946                 ast_cli(a->fd, "Could not set CDR debugging mode\n");
3947                 return CLI_SUCCESS;
3948         }
3949         if (!strcasecmp(a->argv[3], "on")
3950                 && !ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3951                 ast_set_flag(&mod_cfg->general->settings, CDR_DEBUG);
3952                 ast_cli(a->fd, "CDR debugging enabled\n");
3953         } else if (!strcasecmp(a->argv[3], "off")
3954                 && ast_test_flag(&mod_cfg->general->settings, CDR_DEBUG)) {
3955                 ast_clear_flag(&mod_cfg->general->settings, CDR_DEBUG);
3956                 ast_cli(a->fd, "CDR debugging disabled\n");
3957         }
3958         cdr_set_debug_mode(mod_cfg);
3959         ao2_cleanup(mod_cfg);
3960
3961         return CLI_SUCCESS;
3962 }
3963
3964 /*! \brief Complete user input for 'cdr show' */
3965 static char *cli_complete_show(struct ast_cli_args *a)
3966 {
3967         int wordlen = strlen(a->word);
3968         struct ao2_iterator it_cdrs;
3969         struct cdr_object *cdr;
3970
3971         it_cdrs = ao2_iterator_init(active_cdrs_master, 0);
3972         while ((cdr = ao2_iterator_next(&it_cdrs))) {
3973                 if (!strncasecmp(a->word, cdr->party_a.snapshot->base->name, wordlen)) {
3974                         if (ast_cli_completion_add(ast_strdup(cdr->party_a.snapshot->base->name))) {
3975                                 ao2_ref(cdr, -1);
3976                                 break;
3977                         }
3978                 }
3979                 ao2_ref(cdr, -1);
3980         }
3981         ao2_iterator_destroy(&it_cdrs);
3982
3983         return NULL;
3984 }
3985
3986 static void cli_show_channels(struct ast_cli_args *a)
3987 {
3988         struct ao2_iterator it_cdrs;
3989         struct cdr_object *cdr;
3990         char start_time_buffer[64];
3991         char answer_time_buffer[64];
3992         char end_time_buffer[64];
3993
3994 #define TITLE_STRING "%-25.25s %-25.25s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8s %-8.8s\n"
3995 #define FORMAT_STRING "%-25.25s %-25.25s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8ld %-8.8ld\n"
3996
3997         ast_cli(a->fd, "\n");
3998         ast_cli(a->fd, "Channels with Call Detail Record (CDR) Information\n");
3999         ast_cli(a->fd, "--------------------------------------------------\n");
4000         ast_cli(a->fd, TITLE_STRING, "Channel", "Dst. Channel", "LastApp", "Start", "Answer", "End", "Billsec", "Duration");
4001
4002         it_cdrs = ao2_iterator_init(active_cdrs_master, 0);
4003         for (; (cdr = ao2_iterator_next(&it_cdrs)); ao2_cleanup(cdr)) {
4004                 struct cdr_object *it_cdr;
4005                 struct timeval start_time = { 0, };
4006                 struct timeval answer_time = { 0, };
4007                 struct timeval end_time = { 0, };
4008
4009                 SCOPED_AO2LOCK(lock, cdr);
4010
4011                 /* Calculate the start, end, answer, billsec, and duration over the
4012                  * life of all of the CDR entries
4013                  */
4014                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4015                         if (snapshot_is_dialed(it_cdr->party_a.snapshot)) {
4016                                 continue;
4017                         }
4018                         if (ast_tvzero(start_time)) {
4019                                 start_time = it_cdr->start;
4020                         }
4021                         if (!ast_tvzero(it_cdr->answer) && ast_tvzero(answer_time)) {
4022                                 answer_time = it_cdr->answer;
4023                         }
4024                 }
4025
4026                 /* If there was no start time, then all CDRs were for a dialed channel; skip */
4027                 if (ast_tvzero(start_time)) {
4028                         continue;
4029                 }
4030                 it_cdr = cdr->last;
4031
4032                 end_time = ast_tvzero(it_cdr->end) ? ast_tvnow() : it_cdr->end;
4033                 cdr_get_tv(start_time, "%T", start_time_buffer, sizeof(start_time_buffer));
4034                 cdr_get_tv(answer_time, "%T", answer_time_buffer, sizeof(answer_time_buffer));
4035                 cdr_get_tv(end_time, "%T", end_time_buffer, sizeof(end_time_buffer));
4036                 ast_cli(a->fd, FORMAT_STRING, it_cdr->party_a.snapshot->base->name,
4037                                 it_cdr->party_b.snapshot ? it_cdr->party_b.snapshot->base->name : "<none>",
4038                                 it_cdr->appl,
4039                                 start_time_buffer,
4040                                 answer_time_buffer,
4041                                 end_time_buffer,
4042                                 ast_tvzero(answer_time) ? 0 : (long)ast_tvdiff_ms(end_time, answer_time) / 1000,
4043                                 (long)ast_tvdiff_ms(end_time, start_time) / 1000);
4044         }
4045         ao2_iterator_destroy(&it_cdrs);
4046 #undef FORMAT_STRING
4047 #undef TITLE_STRING
4048 }
4049
4050 static void cli_show_channel(struct ast_cli_args *a)
4051 {
4052         struct cdr_object *it_cdr;
4053         char clid[64];
4054         char start_time_buffer[64];
4055         char answer_time_buffer[64];
4056         char end_time_buffer[64];
4057         const char *channel_name = a->argv[3];
4058         struct cdr_object *cdr;
4059
4060 #define TITLE_STRING "%-10.10s %-20.20s %-25.25s %-15.15s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8s %-8.8s\n"
4061 #define FORMAT_STRING "%-10.10s %-20.20s %-25.25s %-15.15s %-15.15s %-8.8s %-8.8s %-8.8s %-8.8ld %-8.8ld\n"
4062
4063         cdr = cdr_object_get_by_name(channel_name);
4064         if (!cdr) {
4065                 ast_cli(a->fd, "Unknown channel: %s\n", channel_name);
4066                 return;
4067         }
4068
4069         ast_cli(a->fd, "\n");
4070         ast_cli(a->fd, "Call Detail Record (CDR) Information for %s\n", channel_name);
4071         ast_cli(a->fd, "--------------------------------------------------\n");
4072         ast_cli(a->fd, TITLE_STRING, "AccountCode", "CallerID", "Dst. Channel", "LastApp", "Data", "Start", "Answer", "End", "Billsec", "Duration");
4073
4074         ao2_lock(cdr);
4075         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4076                 struct timeval end;
4077
4078                 if (snapshot_is_dialed(it_cdr->party_a.snapshot)) {
4079                         continue;
4080                 }
4081                 ast_callerid_merge(clid, sizeof(clid), it_cdr->party_a.snapshot->caller->name, it_cdr->party_a.snapshot->caller->number, "");
4082                 if (ast_tvzero(it_cdr->end)) {
4083                         end = ast_tvnow();
4084                 } else {
4085                         end = it_cdr->end;
4086                 }
4087                 cdr_get_tv(it_cdr->start, "%T", start_time_buffer, sizeof(start_time_buffer));
4088                 cdr_get_tv(it_cdr->answer, "%T", answer_time_buffer, sizeof(answer_time_buffer));
4089                 cdr_get_tv(end, "%T", end_time_buffer, sizeof(end_time_buffer));
4090                 ast_cli(a->fd, FORMAT_STRING,
4091                                 it_cdr->party_a.snapshot->base->accountcode,
4092                                 clid,
4093                                 it_cdr->party_b.snapshot ? it_cdr->party_b.snapshot->base->name : "<none>",
4094                                 it_cdr->appl,
4095                                 it_cdr->data,
4096                                 start_time_buffer,
4097                                 answer_time_buffer,
4098                                 end_time_buffer,
4099                                 (long)ast_tvdiff_ms(end, it_cdr->answer) / 1000,
4100                                 (long)ast_tvdiff_ms(end, it_cdr->start) / 1000);
4101         }
4102         ao2_unlock(cdr);
4103
4104         ao2_cleanup(cdr);
4105
4106 #undef FORMAT_STRING
4107 #undef TITLE_STRING
4108 }
4109
4110 static char *handle_cli_show(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4111 {
4112         switch (cmd) {
4113         case CLI_INIT:
4114                         e->command = "cdr show active";
4115                         e->usage =
4116                                 "Usage: cdr show active [channel]\n"
4117                                 "       Displays a summary of all Call Detail Records when [channel]\n"
4118                                 "       is omitted; displays all of the Call Detail Records\n"
4119                                 "       currently in flight for a given [channel] when [channel] is\n"
4120                                 "       specified.\n\n"
4121                                 "       Note that this will not display Call Detail Records that\n"
4122                                 "       have already been dispatched to a backend storage, nor for\n"
4123                                 "       channels that are no longer active.\n";
4124                         return NULL;
4125         case CLI_GENERATE:
4126                 return cli_complete_show(a);
4127         }
4128
4129         if (a->argc > 4) {
4130                 return CLI_SHOWUSAGE;
4131         } else if (a->argc < 4) {
4132                 cli_show_channels(a);
4133         } else {
4134                 cli_show_channel(a);
4135         }
4136
4137         return CLI_SUCCESS;
4138 }
4139
4140 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4141 {
4142         struct cdr_beitem *beitem = NULL;
4143         struct module_config *mod_cfg;
4144         int cnt = 0;
4145         long nextbatchtime = 0;
4146
4147         switch (cmd) {
4148         case CLI_INIT:
4149                 e->command = "cdr show status";
4150                 e->usage =
4151                         "Usage: cdr show status\n"
4152                         "       Displays the Call Detail Record engine system status.\n";
4153                 return NULL;
4154         case CLI_GENERATE:
4155                 return NULL;
4156         }
4157
4158         if (a->argc > 3) {
4159                 return CLI_SHOWUSAGE;
4160         }
4161
4162         mod_cfg = ao2_global_obj_ref(module_configs);
4163         if (!mod_cfg) {
4164                 return CLI_FAILURE;
4165         }
4166
4167         ast_cli(a->fd, "\n");
4168         ast_cli(a->fd, "Call Detail Record (CDR) settings\n");
4169         ast_cli(a->fd, "----------------------------------\n");
4170         ast_cli(a->fd, "  Logging:                    %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED) ? "Enabled" : "Disabled");
4171         ast_cli(a->fd, "  Mode:                       %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE) ? "Batch" : "Simple");
4172         if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
4173                 ast_cli(a->fd, "  Log unanswered calls:       %s\n", ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) ? "Yes" : "No");
4174                 ast_cli(a->fd, "  Log congestion:             %s\n\n", ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION) ? "Yes" : "No");
4175                 if (ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
4176                         ast_cli(a->fd, "* Batch Mode Settings\n");
4177                         ast_cli(a->fd, "  -------------------\n");
4178                         if (batch)
4179                                 cnt = batch->size;
4180                         if (cdr_sched > -1)
4181                                 nextbatchtime = ast_sched_when(sched, cdr_sched);
4182                         ast_cli(a->fd, "  Safe shutdown:              %s\n", ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SAFE_SHUTDOWN) ? "Enabled" : "Disabled");
4183                         ast_cli(a->fd, "  Threading model:            %s\n", ast_test_flag(&mod_cfg->general->batch_settings.settings, BATCH_MODE_SCHEDULER_ONLY) ? "Scheduler only" : "Scheduler plus separate threads");
4184                         ast_cli(a->fd, "  Current batch size:         %d record%s\n", cnt, ESS(cnt));
4185                         ast_cli(a->fd, "  Maximum batch size:         %u record%s\n", mod_cfg->general->batch_settings.size, ESS(mod_cfg->general->batch_settings.size));
4186                         ast_cli(a->fd, "  Maximum batch time:         %u second%s\n", mod_cfg->general->batch_settings.time, ESS(mod_cfg->general->batch_settings.time));
4187                         ast_cli(a->fd, "  Next batch processing time: %ld second%s\n\n", nextbatchtime, ESS(nextbatchtime));
4188                 }
4189                 ast_cli(a->fd, "* Registered Backends\n");
4190                 ast_cli(a->fd, "  -------------------\n");
4191                 AST_RWLIST_RDLOCK(&be_list);
4192                 if (AST_RWLIST_EMPTY(&be_list)) {
4193                         ast_cli(a->fd, "    (none)\n");
4194                 } else {
4195                         AST_RWLIST_TRAVERSE(&be_list, beitem, list) {
4196                                 ast_cli(a->fd, "    %s%s\n", beitem->name, beitem->suspended ? " (suspended) " : "");
4197                         }
4198                 }
4199                 AST_RWLIST_UNLOCK(&be_list);
4200                 ast_cli(a->fd, "\n");
4201         }
4202
4203         ao2_cleanup(mod_cfg);
4204         return CLI_SUCCESS;
4205 }
4206
4207 static char *handle_cli_submit(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4208 {
4209         struct module_config *mod_cfg;
4210
4211         switch (cmd) {
4212         case CLI_INIT:
4213                 e->command = "cdr submit";
4214                 e->usage =
4215                         "Usage: cdr submit\n"
4216                         "Posts all pending batched CDR data to the configured CDR\n"
4217                         "backend engine modules.\n";
4218                 return NULL;
4219         case CLI_GENERATE:
4220                 return NULL;
4221         }
4222         if (a->argc > 2) {
4223                 return CLI_SHOWUSAGE;
4224         }
4225
4226         mod_cfg = ao2_global_obj_ref(module_configs);
4227         if (!mod_cfg) {
4228                 return CLI_FAILURE;
4229         }
4230
4231         if (!ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
4232                 ast_cli(a->fd, "Cannot submit CDR batch: CDR engine disabled.\n");
4233         } else if (!ast_test_flag(&mod_cfg->general->settings, CDR_BATCHMODE)) {
4234                 ast_cli(a->fd, "Cannot submit CDR batch: batch mode not enabled.\n");
4235         } else {
4236                 start_batch_mode();
4237                 ast_cli(a->fd, "Submitted CDRs to backend engines for processing.  This may take a while.\n");
4238         }
4239         ao2_cleanup(mod_cfg);
4240
4241         return CLI_SUCCESS;
4242 }
4243
4244 static struct ast_cli_entry cli_commands[] = {
4245         AST_CLI_DEFINE(handle_cli_submit, "Posts all pending batched CDR data"),
4246         AST_CLI_DEFINE(handle_cli_status, "Display the CDR status"),
4247         AST_CLI_DEFINE(handle_cli_show, "Display active CDRs for channels"),
4248         AST_CLI_DEFINE(handle_cli_debug, "Enable debugging in the CDR engine"),
4249 };
4250
4251 /*!
4252  * \brief This dispatches *all* \ref cdr_objects. It should only be used during
4253  * shutdown, so that we get billing records for everything that we can.
4254  */
4255 static int cdr_object_dispatch_all_cb(void *obj, void *arg, int flags)
4256 {
4257         struct cdr_object *cdr = obj;
4258         struct cdr_object *it_cdr;
4259
4260         ao2_lock(cdr);
4261         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
4262                 cdr_object_transition_state(it_cdr, &finalized_state_fn_table);
4263         }
4264         cdr_object_dispatch(cdr);
4265         ao2_unlock(cdr);
4266
4267         cdr_all_unlink(cdr);
4268
4269         return CMP_MATCH;
4270 }
4271
4272 static void finalize_batch_mode(void)
4273 {
4274         if (cdr_thread == AST_PTHREADT_NULL) {
4275                 return;
4276         }
4277         /* wake up the thread so it will exit */
4278         pthread_cancel(cdr_thread);
4279         pthread_kill(cdr_thread, SIGURG);
4280         pthread_join(cdr_thread, NULL);
4281         cdr_thread = AST_PTHREADT_NULL;
4282         ast_cond_destroy(&cdr_pending_cond);
4283         ast_cdr_engine_term();
4284 }
4285
4286 struct stasis_message_router *ast_cdr_message_router(void)
4287 {
4288         if (!stasis_router) {
4289                 return NULL;
4290         }
4291
4292         ao2_bump(stasis_router);
4293         return stasis_router;
4294 }
4295
4296 /*!
4297  * \brief Destroy the active Stasis subscriptions
4298  */
4299 static void destroy_subscriptions(void)
4300 {
4301         channel_subscription = stasis_forward_cancel(channel_subscription);
4302         bridge_subscription = stasis_forward_cancel(bridge_subscription);
4303         parking_subscription = stasis_forward_cancel(parking_subscription);
4304 }
4305
4306 /*!
4307  * \brief Create the Stasis subcriptions for CDRs
4308  */
4309 static int create_subscriptions(void)
4310 {
4311         if (!cdr_topic) {
4312                 return -1;
4313         }
4314
4315         if (channel_subscription || bridge_subscription || parking_subscription) {
4316                 return 0;
4317         }
4318
4319         channel_subscription = stasis_forward_all(ast_channel_topic_all(), cdr_topic);
4320         if (!channel_subscription) {
4321                 return -1;
4322         }
4323         bridge_subscription = stasis_forward_all(ast_bridge_topic_all(), cdr_topic);
4324         if (!bridge_subscription) {
4325                 return -1;
4326         }
4327         parking_subscription = stasis_forward_all(ast_parking_topic(), cdr_topic);
4328         if (!parking_subscription) {
4329                 return -1;
4330         }
4331
4332         return 0;
4333 }
4334
4335 static int process_config(int reload)
4336 {
4337         if (!reload) {
4338                 if (aco_info_init(&cfg_info)) {
4339                         return 1;
4340                 }
4341
4342                 aco_option_register(&cfg_info, "enable", ACO_EXACT, general_options, DEFAULT_ENABLED, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_ENABLED);
4343                 aco_option_register(&cfg_info, "debug", ACO_EXACT, general_options, 0, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_DEBUG);
4344                 aco_option_register(&cfg_info, "unanswered", ACO_EXACT, general_options, DEFAULT_UNANSWERED, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_UNANSWERED);
4345                 aco_option_register(&cfg_info, "congestion", ACO_EXACT, general_options, 0, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_CONGESTION);
4346                 aco_option_register(&cfg_info, "batch", ACO_EXACT, general_options, DEFAULT_BATCHMODE, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_BATCHMODE);
4347                 aco_option_register(&cfg_info, "endbeforehexten", ACO_EXACT, general_options, DEFAULT_END_BEFORE_H_EXTEN, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_END_BEFORE_H_EXTEN);
4348                 aco_option_register(&cfg_info, "initiatedseconds", ACO_EXACT, general_options, DEFAULT_INITIATED_SECONDS, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, settings), CDR_INITIATED_SECONDS);
4349                 aco_option_register(&cfg_info, "scheduleronly", ACO_EXACT, general_options, DEFAULT_BATCH_SCHEDULER_ONLY, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, batch_settings.settings), BATCH_MODE_SCHEDULER_ONLY);
4350                 aco_option_register(&cfg_info, "safeshutdown", ACO_EXACT, general_options, DEFAULT_BATCH_SAFE_SHUTDOWN, OPT_BOOLFLAG_T, 1, FLDSET(struct ast_cdr_config, batch_settings.settings), BATCH_MODE_SAFE_SHUTDOWN);
4351                 aco_option_register(&cfg_info, "size", ACO_EXACT, general_options, DEFAULT_BATCH_SIZE, OPT_UINT_T, PARSE_IN_RANGE, FLDSET(struct ast_cdr_config, batch_settings.size), 0, MAX_BATCH_SIZE);
4352                 aco_option_register(&cfg_info, "time", ACO_EXACT, general_options, DEFAULT_BATCH_TIME, OPT_UINT_T, PARSE_IN_RANGE, FLDSET(struct ast_cdr_config, batch_settings.time), 1, MAX_BATCH_TIME);
4353         }
4354
4355         if (aco_process_config(&cfg_info, reload) == ACO_PROCESS_ERROR) {
4356                 struct module_config *mod_cfg;
4357
4358                 if (reload) {
4359                         return 1;
4360                 }
4361
4362                 /* If we couldn't process the configuration and this wasn't a reload,
4363                  * create a default config
4364                  */
4365                 mod_cfg = module_config_alloc();
4366                 if (!mod_cfg
4367                         || aco_set_defaults(&general_option, "general", mod_cfg->general)) {
4368                         ao2_cleanup(mod_cfg);
4369                         return 1;
4370                 }
4371                 ast_log(LOG_NOTICE, "Failed to process CDR configuration; using defaults\n");
4372                 ao2_global_obj_replace_unref(module_configs, mod_cfg);
4373                 cdr_set_debug_mode(mod_cfg);
4374                 ao2_cleanup(mod_cfg);
4375         }
4376
4377         return 0;
4378 }
4379
4380 static void cdr_engine_shutdown(void)
4381 {
4382         stasis_message_router_unsubscribe_and_join(stasis_router);
4383         stasis_router = NULL;