Merge "res_calendar: Specialized calendars depend on symbols of general calendar."
[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/causes.h"
57 #include "asterisk/linkedlists.h"
58 #include "asterisk/utils.h"
59 #include "asterisk/sched.h"
60 #include "asterisk/config.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/config_options.h"
64 #include "asterisk/json.h"
65 #include "asterisk/parking.h"
66 #include "asterisk/stasis.h"
67 #include "asterisk/stasis_channels.h"
68 #include "asterisk/stasis_bridges.h"
69 #include "asterisk/stasis_message_router.h"
70 #include "asterisk/astobj2.h"
71 #include "asterisk/taskprocessor.h"
72
73 /*** DOCUMENTATION
74         <configInfo name="cdr" language="en_US">
75                 <synopsis>Call Detail Record configuration</synopsis>
76                 <description>
77                         <para>CDR is Call Detail Record, which provides logging services via a variety of
78                         pluggable backend modules. Detailed call information can be recorded to
79                         databases, files, etc. Useful for billing, fraud prevention, compliance with
80                         Sarbanes-Oxley aka The Enron Act, QOS evaluations, and more.</para>
81                 </description>
82                 <configFile name="cdr.conf">
83                         <configObject name="general">
84                                 <synopsis>Global settings applied to the CDR engine.</synopsis>
85                                 <configOption name="debug">
86                                         <synopsis>Enable/disable verbose CDR debugging.</synopsis>
87                                         <description><para>When set to <literal>True</literal>, verbose updates
88                                         of changes in CDR information will be logged. Note that this is only
89                                         of use when debugging CDR behavior.</para>
90                                         </description>
91                                 </configOption>
92                                 <configOption name="enable">
93                                         <synopsis>Enable/disable CDR logging.</synopsis>
94                                         <description><para>Define whether or not to use CDR logging. Setting this to "no" will override
95                                         any loading of backend CDR modules.  Default is "yes".</para>
96                                         </description>
97                                 </configOption>
98                                 <configOption name="unanswered">
99                                         <synopsis>Log calls that are never answered and don't set an outgoing party.</synopsis>
100                                         <description><para>
101                                         Define whether or not to log unanswered calls that don't involve an outgoing party. Setting
102                                         this to "yes" will make calls to extensions that don't answer and don't set a side B channel
103                                         (such as by using the Dial application) receive CDR log entries. If this option is set to
104                                         "no", then those log entries will not be created. Unanswered calls which get offered to an
105                                         outgoing line will always receive log entries regardless of this option, and that is the
106                                         intended behavior.
107                                         </para>
108                                         </description>
109                                 </configOption>
110                                 <configOption name="congestion">
111                                         <synopsis>Log congested calls.</synopsis>
112                                         <description><para>Define whether or not to log congested calls. Setting this to "yes" will
113                                         report each call that fails to complete due to congestion conditions.</para>
114                                         </description>
115                                 </configOption>
116                                 <configOption name="endbeforehexten">
117                                         <synopsis>Don't produce CDRs while executing hangup logic</synopsis>
118                                         <description>
119                                                 <para>As each CDR for a channel is finished, its end time is updated
120                                                 and the CDR is finalized. When a channel is hung up and hangup
121                                                 logic is present (in the form of a hangup handler or the
122                                                 <literal>h</literal> extension), a new CDR is generated for the
123                                                 channel. Any statistics are gathered from this new CDR. By enabling
124                                                 this option, no new CDR is created for the dialplan logic that is
125                                                 executed in <literal>h</literal> extensions or attached hangup handler
126                                                 subroutines. The default value is <literal>yes</literal>, indicating
127                                                 that a CDR will be generated during hangup logic.</para>
128                                         </description>
129                                 </configOption>
130                                 <configOption name="initiatedseconds">
131                                         <synopsis>Count microseconds for billsec purposes</synopsis>
132                                         <description><para>Normally, the <literal>billsec</literal> field logged to the CDR backends
133                                         is simply the end time (hangup time) minus the answer time in seconds. Internally,
134                                         asterisk stores the time in terms of microseconds and seconds. By setting
135                                         initiatedseconds to <literal>yes</literal>, you can force asterisk to report any seconds
136                                         that were initiated (a sort of round up method). Technically, this is
137                                         when the microsecond part of the end time is greater than the microsecond
138                                         part of the answer time, then the billsec time is incremented one second.</para>
139                                         </description>
140                                 </configOption>
141                                 <configOption name="batch">
142                                         <synopsis>Submit CDRs to the backends for processing in batches</synopsis>
143                                         <description><para>Define the CDR batch mode, where instead of posting the CDR at the end of
144                                         every call, the data will be stored in a buffer to help alleviate load on the
145                                         asterisk server.</para>
146                                         <warning><para>Use of batch mode may result in data loss after unsafe asterisk termination,
147                                         i.e., software crash, power failure, kill -9, etc.</para>
148                                         </warning>
149                                         </description>
150                                 </configOption>
151                                 <configOption name="size">
152                                         <synopsis>The maximum number of CDRs to accumulate before triggering a batch</synopsis>
153                                         <description><para>Define the maximum number of CDRs to accumulate in the buffer before posting
154                                         them to the backend engines. batch must be set to <literal>yes</literal>.</para>
155                                         </description>
156                                 </configOption>
157                                 <configOption name="time">
158                                         <synopsis>The maximum time to accumulate CDRs before triggering a batch</synopsis>
159                                         <description><para>Define the maximum time to accumulate CDRs before posting them in a batch to the
160                                         backend engines. If this time limit is reached, then it will post the records, regardless of the value
161                                         defined for size. batch must be set to <literal>yes</literal>.</para>
162                                         <note><para>Time is expressed in seconds.</para></note>
163                                         </description>
164                                 </configOption>
165                                 <configOption name="scheduleronly">
166                                         <synopsis>Post batched CDRs on their own thread instead of the scheduler</synopsis>
167                                         <description><para>The CDR engine uses the internal asterisk scheduler to determine when to post
168                                         records.  Posting can either occur inside the scheduler thread, or a new
169                                         thread can be spawned for the submission of every batch.  For small batches,
170                                         it might be acceptable to just use the scheduler thread, so set this to <literal>yes</literal>.
171                                         For large batches, say anything over size=10, a new thread is recommended, so
172                                         set this to <literal>no</literal>.</para>
173                                         </description>
174                                 </configOption>
175                                 <configOption name="safeshutdown">
176                                         <synopsis>Block shutdown of Asterisk until CDRs are submitted</synopsis>
177                                         <description><para>When shutting down asterisk, you can block until the CDRs are submitted.  If
178                                         you don't, then data will likely be lost.  You can always check the size of
179                                         the CDR batch buffer with the CLI <astcli>cdr status</astcli> command.  To enable blocking on
180                                         submission of CDR data during asterisk shutdown, set this to <literal>yes</literal>.</para>
181                                         </description>
182                                 </configOption>
183                         </configObject>
184                 </configFile>
185         </configInfo>
186  ***/
187
188
189 /* The prime here should be similar in size to the channel container. */
190 #ifdef LOW_MEMORY
191 #define NUM_CDR_BUCKETS 61
192 #else
193 #define NUM_CDR_BUCKETS 769
194 #endif
195
196 #define DEFAULT_ENABLED "1"
197 #define DEFAULT_BATCHMODE "0"
198 #define DEFAULT_UNANSWERED "0"
199 #define DEFAULT_CONGESTION "0"
200 #define DEFAULT_END_BEFORE_H_EXTEN "1"
201 #define DEFAULT_INITIATED_SECONDS "0"
202
203 #define DEFAULT_BATCH_SIZE "100"
204 #define MAX_BATCH_SIZE 1000
205 #define DEFAULT_BATCH_TIME "300"
206 #define MAX_BATCH_TIME 86400
207 #define DEFAULT_BATCH_SCHEDULER_ONLY "0"
208 #define DEFAULT_BATCH_SAFE_SHUTDOWN "1"
209
210 #define cdr_set_debug_mode(mod_cfg) \
211         do { \
212                 cdr_debug_enabled = ast_test_flag(&(mod_cfg)->general->settings, CDR_DEBUG); \
213         } while (0)
214
215 static int cdr_debug_enabled;
216
217 #define CDR_DEBUG(fmt, ...) \
218         do { \
219                 if (cdr_debug_enabled) { \
220                         ast_verbose((fmt), ##__VA_ARGS__); \
221                 } \
222         } while (0)
223
224 static void cdr_detach(struct ast_cdr *cdr);
225 static void cdr_submit_batch(int shutdown);
226 static int cdr_toggle_runtime_options(void);
227
228 /*! \brief The configuration settings for this module */
229 struct module_config {
230         struct ast_cdr_config *general;         /*!< CDR global settings */
231 };
232
233 /*! \brief The container for the module configuration */
234 static AO2_GLOBAL_OBJ_STATIC(module_configs);
235
236 /*! \brief The type definition for general options */
237 static struct aco_type general_option = {
238         .type = ACO_GLOBAL,
239         .name = "general",
240         .item_offset = offsetof(struct module_config, general),
241         .category = "general",
242         .category_match = ACO_WHITELIST_EXACT,
243 };
244
245 /*! Config sections used by existing modules. Do not add to this list. */
246 static const char *ignore_categories[] = {
247         "csv",
248         "custom",
249         "manager",
250         "odbc",
251         "pgsql",
252         "radius",
253         "sqlite",
254         "tds",
255         "mysql",
256         NULL,
257 };
258
259 static struct aco_type ignore_option = {
260         .type = ACO_IGNORE,
261         .name = "modules",
262         .category = (const char*)ignore_categories,
263         .category_match = ACO_WHITELIST_ARRAY,
264 };
265
266 static void *module_config_alloc(void);
267 static void module_config_destructor(void *obj);
268 static void module_config_post_apply(void);
269
270 /*! \brief The file definition */
271 static struct aco_file module_file_conf = {
272         .filename = "cdr.conf",
273         .types = ACO_TYPES(&general_option, &ignore_option),
274 };
275
276 CONFIG_INFO_CORE("cdr", cfg_info, module_configs, module_config_alloc,
277         .files = ACO_FILES(&module_file_conf),
278         .post_apply_config = module_config_post_apply,
279 );
280
281 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
282
283 static void module_config_post_apply(void)
284 {
285         struct module_config *mod_cfg;
286
287         mod_cfg = ao2_global_obj_ref(module_configs);
288         if (!mod_cfg) {
289                 return;
290         }
291         cdr_set_debug_mode(mod_cfg);
292         ao2_cleanup(mod_cfg);
293 }
294
295 /*! \brief Dispose of a module config object */
296 static void module_config_destructor(void *obj)
297 {
298         struct module_config *cfg = obj;
299
300         if (!cfg) {
301                 return;
302         }
303         ao2_ref(cfg->general, -1);
304 }
305
306 /*! \brief Create a new module config object */
307 static void *module_config_alloc(void)
308 {
309         struct module_config *mod_cfg;
310         struct ast_cdr_config *cdr_config;
311
312         mod_cfg = ao2_alloc(sizeof(*mod_cfg), module_config_destructor);
313         if (!mod_cfg) {
314                 return NULL;
315         }
316
317         cdr_config = ao2_alloc(sizeof(*cdr_config), NULL);
318         if (!cdr_config) {
319                 ao2_ref(cdr_config, -1);
320                 return NULL;
321         }
322         mod_cfg->general = cdr_config;
323
324         return mod_cfg;
325 }
326
327 /*! \brief Registration object for CDR backends */
328 struct cdr_beitem {
329         char name[20];
330         char desc[80];
331         ast_cdrbe be;
332         AST_RWLIST_ENTRY(cdr_beitem) list;
333         int suspended:1;
334 };
335
336 /*! \brief List of registered backends */
337 static AST_RWLIST_HEAD_STATIC(be_list, cdr_beitem);
338
339 /*! \brief List of registered modifiers */
340 static AST_RWLIST_HEAD_STATIC(mo_list, cdr_beitem);
341
342 /*! \brief Queued CDR waiting to be batched */
343 struct cdr_batch_item {
344         struct ast_cdr *cdr;
345         struct cdr_batch_item *next;
346 };
347
348 /*! \brief The actual batch queue */
349 static struct cdr_batch {
350         int size;
351         struct cdr_batch_item *head;
352         struct cdr_batch_item *tail;
353 } *batch = NULL;
354
355 /*! \brief The global sequence counter used for CDRs */
356 static int global_cdr_sequence =  0;
357
358 /*! \brief Scheduler items */
359 static struct ast_sched_context *sched;
360 static int cdr_sched = -1;
361 AST_MUTEX_DEFINE_STATIC(cdr_sched_lock);
362 static pthread_t cdr_thread = AST_PTHREADT_NULL;
363
364 /*! \brief Lock protecting modifications to the batch queue */
365 AST_MUTEX_DEFINE_STATIC(cdr_batch_lock);
366
367 /*! \brief These are used to wake up the CDR thread when there's work to do */
368 AST_MUTEX_DEFINE_STATIC(cdr_pending_lock);
369 static ast_cond_t cdr_pending_cond;
370
371 /*! \brief A container of the active master CDRs indexed by Party A channel uniqueid */
372 static struct ao2_container *active_cdrs_master;
373
374 /*! \brief A container of all active CDRs with a Party B indexed by Party B channel name */
375 static struct ao2_container *active_cdrs_all;
376
377 /*! \brief Message router for stasis messages regarding channel state */
378 static struct stasis_message_router *stasis_router;
379
380 /*! \brief Our subscription for bridges */
381 static struct stasis_forward *bridge_subscription;
382
383 /*! \brief Our subscription for channels */
384 static struct stasis_forward *channel_subscription;
385
386 /*! \brief Our subscription for parking */
387 static struct stasis_forward *parking_subscription;
388
389 /*! \brief The parent topic for all topics we want to aggregate for CDRs */
390 static struct stasis_topic *cdr_topic;
391
392 /*! \brief A message type used to synchronize with the CDR topic */
393 STASIS_MESSAGE_TYPE_DEFN_LOCAL(cdr_sync_message_type);
394
395 struct cdr_object;
396
397 /*! \brief Return types for \ref process_bridge_enter functions */
398 enum process_bridge_enter_results {
399         /*!
400          * The CDR was the only party in the bridge.
401          */
402         BRIDGE_ENTER_ONLY_PARTY,
403         /*!
404          * The CDR was able to obtain a Party B from some other party already in the bridge
405          */
406         BRIDGE_ENTER_OBTAINED_PARTY_B,
407         /*!
408          * The CDR was not able to obtain a Party B
409          */
410         BRIDGE_ENTER_NO_PARTY_B,
411         /*!
412          * This CDR can't handle a bridge enter message and a new CDR needs to be created
413          */
414         BRIDGE_ENTER_NEED_CDR,
415 };
416
417 /*!
418  * \brief A virtual table used for \ref cdr_object.
419  *
420  * Note that all functions are optional - if a subclass does not need an
421  * implementation, it is safe to leave it NULL.
422  */
423 struct cdr_object_fn_table {
424         /*! \brief Name of the subclass */
425         const char *name;
426
427         /*!
428          * \brief An initialization function. This will be called automatically
429          * when a \ref cdr_object is switched to this type in
430          * \ref cdr_object_transition_state
431          *
432          * \param cdr The \ref cdr_object that was just transitioned
433          */
434         void (* const init_function)(struct cdr_object *cdr);
435
436         /*!
437          * \brief Process a Party A update for the \ref cdr_object
438          *
439          * \param cdr The \ref cdr_object to process the update
440          * \param snapshot The snapshot for the CDR's Party A
441          * \retval 0 the CDR handled the update or ignored it
442          * \retval 1 the CDR is finalized and a new one should be made to handle it
443          */
444         int (* const process_party_a)(struct cdr_object *cdr,
445                         struct ast_channel_snapshot *snapshot);
446
447         /*!
448          * \brief Process a Party B update for the \ref cdr_object
449          *
450          * \param cdr The \ref cdr_object to process the update
451          * \param snapshot The snapshot for the CDR's Party B
452          */
453         void (* const process_party_b)(struct cdr_object *cdr,
454                         struct ast_channel_snapshot *snapshot);
455
456         /*!
457          * \brief Process the beginning of a dial. A dial message implies one of two
458          * things:
459          * The \ref cdr_object's Party A has been originated
460          * The \ref cdr_object's Party A is dialing its Party B
461          *
462          * \param cdr The \ref cdr_object
463          * \param caller The originator of the dial attempt
464          * \param peer The destination of the dial attempt
465          *
466          * \retval 0 if the parties in the dial were handled by this CDR
467          * \retval 1 if the parties could not be handled by this CDR
468          */
469         int (* const process_dial_begin)(struct cdr_object *cdr,
470                         struct ast_channel_snapshot *caller,
471                         struct ast_channel_snapshot *peer);
472
473         /*!
474          * \brief Process the end of a dial. At the end of a dial, a CDR can be
475          * transitioned into one of two states - DialedPending
476          * (\ref dialed_pending_state_fn_table) or Finalized
477          * (\ref finalized_state_fn_table).
478          *
479          * \param cdr The \ref cdr_object
480          * \param caller The originator of the dial attempt
481          * \param peer the Destination of the dial attempt
482          * \param dial_status What happened
483          *
484          * \retval 0 if the parties in the dial were handled by this CDR
485          * \retval 1 if the parties could not be handled by this CDR
486          */
487         int (* const process_dial_end)(struct cdr_object *cdr,
488                         struct ast_channel_snapshot *caller,
489                         struct ast_channel_snapshot *peer,
490                         const char *dial_status);
491
492         /*!
493          * \brief Process the entering of a bridge by this CDR. The purpose of this
494          * callback is to have the CDR prepare itself for the bridge and attempt to
495          * find a valid Party B. The act of creating new CDRs based on the entering
496          * of this channel into the bridge is handled by the higher level message
497          * handler.
498          *
499          * Note that this handler is for when a channel enters into a "normal"
500          * bridge, where people actually talk to each other. Parking is its own
501          * thing.
502          *
503          * \param cdr The \ref cdr_object
504          * \param bridge The bridge that the Party A just entered into
505          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
506          *
507          * \retval process_bridge_enter_results Defines whether or not this CDR was able
508          * to fully handle the bridge enter message.
509          */
510         enum process_bridge_enter_results (* const process_bridge_enter)(
511                         struct cdr_object *cdr,
512                         struct ast_bridge_snapshot *bridge,
513                         struct ast_channel_snapshot *channel);
514
515         /*!
516          * \brief Process entering into a parking bridge.
517          *
518          * \param cdr The \ref cdr_object
519          * \param bridge The parking bridge that Party A just entered into
520          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
521          *
522          * \retval 0 This CDR successfully transitioned itself into the parked state
523          * \retval 1 This CDR couldn't handle the parking transition and we need a
524          *  new CDR.
525          */
526         int (* const process_parking_bridge_enter)(struct cdr_object *cdr,
527                         struct ast_bridge_snapshot *bridge,
528                         struct ast_channel_snapshot *channel);
529
530         /*!
531          * \brief Process the leaving of a bridge by this CDR.
532          *
533          * \param cdr The \ref cdr_object
534          * \param bridge The bridge that the Party A just left
535          * \param channel The \ref ast_channel_snapshot for this CDR's Party A
536          *
537          * \retval 0 This CDR left successfully
538          * \retval 1 Error
539          */
540         int (* const process_bridge_leave)(struct cdr_object *cdr,
541                         struct ast_bridge_snapshot *bridge,
542                         struct ast_channel_snapshot *channel);
543
544         /*!
545          * \brief Process an update informing us that the channel got itself parked
546          *
547          * \param cdr The \ref cdr_object
548          * \param channel The parking information for this CDR's party A
549          *
550          * \retval 0 This CDR successfully parked itself
551          * \retval 1 This CDR couldn't handle the park
552          */
553         int (* const process_parked_channel)(struct cdr_object *cdr,
554                         struct ast_parked_call_payload *parking_info);
555 };
556
557 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
558 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
559 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
560 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status);
561 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info);
562
563 static void single_state_init_function(struct cdr_object *cdr);
564 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
565 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
566 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);
567 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
568
569 /*!
570  * \brief The virtual table for the Single state.
571  *
572  * A \ref cdr_object starts off in this state. This represents a channel that
573  * has no Party B information itself.
574  *
575  * A \ref cdr_object from this state can go into any of the following states:
576  * * \ref dial_state_fn_table
577  * * \ref bridge_state_fn_table
578  * * \ref finalized_state_fn_table
579  */
580 struct cdr_object_fn_table single_state_fn_table = {
581         .name = "Single",
582         .init_function = single_state_init_function,
583         .process_party_a = base_process_party_a,
584         .process_party_b = single_state_process_party_b,
585         .process_dial_begin = single_state_process_dial_begin,
586         .process_dial_end = base_process_dial_end,
587         .process_bridge_enter = single_state_process_bridge_enter,
588         .process_parking_bridge_enter = single_state_process_parking_bridge_enter,
589         .process_bridge_leave = base_process_bridge_leave,
590         .process_parked_channel = base_process_parked_channel,
591 };
592
593 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
594 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
595 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);
596 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);
597
598 /*!
599  * \brief The virtual table for the Dial state.
600  *
601  * A \ref cdr_object that has begun a dial operation. This state is entered when
602  * the Party A for a CDR is determined to be dialing out to a Party B or when
603  * a CDR is for an originated channel (in which case the Party A information is
604  * the originated channel, and there is no Party B).
605  *
606  * A \ref cdr_object from this state can go in any of the following states:
607  * * \ref dialed_pending_state_fn_table
608  * * \ref bridge_state_fn_table
609  * * \ref finalized_state_fn_table
610  */
611 struct cdr_object_fn_table dial_state_fn_table = {
612         .name = "Dial",
613         .process_party_a = base_process_party_a,
614         .process_party_b = dial_state_process_party_b,
615         .process_dial_begin = dial_state_process_dial_begin,
616         .process_dial_end = dial_state_process_dial_end,
617         .process_bridge_enter = dial_state_process_bridge_enter,
618         .process_bridge_leave = base_process_bridge_leave,
619 };
620
621 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
622 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer);
623 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);
624 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
625
626 /*!
627  * \brief The virtual table for the Dialed Pending state.
628  *
629  * A \ref cdr_object that has successfully finished a dial operation, but we
630  * don't know what they're going to do yet. It's theoretically possible to dial
631  * a party and then have that party not be bridged with the caller; likewise,
632  * an origination can complete and the channel go off and execute dialplan. The
633  * pending state acts as a bridge between either:
634  * * Entering a bridge
635  * * Getting a new CDR for new dialplan execution
636  * * Switching from being originated to executing dialplan
637  *
638  * A \ref cdr_object from this state can go in any of the following states:
639  * * \ref single_state_fn_table
640  * * \ref dialed_pending_state_fn_table
641  * * \ref bridge_state_fn_table
642  * * \ref finalized_state_fn_table
643  */
644 struct cdr_object_fn_table dialed_pending_state_fn_table = {
645         .name = "DialedPending",
646         .process_party_a = dialed_pending_state_process_party_a,
647         .process_dial_begin = dialed_pending_state_process_dial_begin,
648         .process_bridge_enter = dialed_pending_state_process_bridge_enter,
649         .process_parking_bridge_enter = dialed_pending_state_process_parking_bridge_enter,
650         .process_bridge_leave = base_process_bridge_leave,
651         .process_parked_channel = base_process_parked_channel,
652 };
653
654 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
655 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
656
657 /*!
658  * \brief The virtual table for the Bridged state
659  *
660  * A \ref cdr_object enters this state when it receives notification that the
661  * channel has entered a bridge.
662  *
663  * A \ref cdr_object from this state can go to:
664  * * \ref finalized_state_fn_table
665  */
666 struct cdr_object_fn_table bridge_state_fn_table = {
667         .name = "Bridged",
668         .process_party_a = base_process_party_a,
669         .process_party_b = bridge_state_process_party_b,
670         .process_bridge_leave = bridge_state_process_bridge_leave,
671         .process_parked_channel = base_process_parked_channel,
672 };
673
674 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel);
675
676 /*!
677  * \brief The virtual table for the Parked state
678  *
679  * Parking is weird. Unlike typical bridges, it has to be treated somewhat
680  * uniquely - a channel in a parking bridge (which is a subclass of a holding
681  * bridge) has to be handled as if the channel went into an application.
682  * However, when the channel comes out, we need a new CDR - unlike the Single
683  * state.
684  */
685 struct cdr_object_fn_table parked_state_fn_table = {
686         .name = "Parked",
687         .process_party_a = base_process_party_a,
688         .process_bridge_leave = parked_state_process_bridge_leave,
689         .process_parked_channel = base_process_parked_channel,
690 };
691
692 static void finalized_state_init_function(struct cdr_object *cdr);
693 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot);
694
695 /*!
696  * \brief The virtual table for the finalized state.
697  *
698  * Once in the finalized state, the CDR is done. No modifications can be made
699  * to the CDR.
700  */
701 struct cdr_object_fn_table finalized_state_fn_table = {
702         .name = "Finalized",
703         .init_function = finalized_state_init_function,
704         .process_party_a = finalized_state_process_party_a,
705         .process_bridge_enter = base_process_bridge_enter,
706 };
707
708 /*! \brief A wrapper object around a snapshot.
709  * Fields that are mutable by the CDR engine are replicated here.
710  */
711 struct cdr_object_snapshot {
712         struct ast_channel_snapshot *snapshot;  /*!< The channel snapshot */
713         char userfield[AST_MAX_USER_FIELD];     /*!< Userfield for the channel */
714         unsigned int flags;                     /*!< Specific flags for this party */
715         struct varshead variables;              /*!< CDR variables for the channel */
716 };
717
718 /*! \brief An in-memory representation of an active CDR */
719 struct cdr_object {
720         struct cdr_object_snapshot party_a;     /*!< The Party A information */
721         struct cdr_object_snapshot party_b;     /*!< The Party B information */
722         struct cdr_object_fn_table *fn_table;   /*!< The current virtual table */
723
724         enum ast_cdr_disposition disposition;   /*!< The disposition of the CDR */
725         struct timeval start;                   /*!< When this CDR was created */
726         struct timeval answer;                  /*!< Either when the channel was answered, or when the path between channels was established */
727         struct timeval end;                     /*!< When this CDR was finalized */
728         unsigned int sequence;                  /*!< A monotonically increasing number for each CDR */
729         struct ast_flags flags;                 /*!< Flags on the CDR */
730         AST_DECLARE_STRING_FIELDS(
731                 AST_STRING_FIELD(linkedid);         /*!< Linked ID. Cached here as it may change out from party A, which must be immutable */
732                 AST_STRING_FIELD(uniqueid);                     /*!< Unique id of party A. Cached here as it is the master CDR container key */
733                 AST_STRING_FIELD(name);             /*!< Channel name of party A. Cached here as the party A address may change */
734                 AST_STRING_FIELD(bridge);           /*!< The bridge the party A happens to be in. */
735                 AST_STRING_FIELD(appl);             /*!< The last accepted application party A was in */
736                 AST_STRING_FIELD(data);             /*!< The data for the last accepted application party A was in */
737                 AST_STRING_FIELD(context);          /*!< The accepted context for Party A */
738                 AST_STRING_FIELD(exten);            /*!< The accepted extension for Party A */
739                 AST_STRING_FIELD(party_b_name);     /*!< Party B channel name. Cached here as it is the all CDRs container key */
740         );
741         struct cdr_object *next;                /*!< The next CDR object in the chain */
742         struct cdr_object *last;                /*!< The last CDR object in the chain */
743         int is_root;                            /*!< True if this is the first CDR in the chain */
744 };
745
746 /*!
747  * \brief Copy variables from one list to another
748  * \param to_list destination
749  * \param from_list source
750  * \retval The number of copied variables
751  */
752 static int copy_variables(struct varshead *to_list, struct varshead *from_list)
753 {
754         struct ast_var_t *variables;
755         struct ast_var_t *newvariable;
756         const char *var;
757         const char *val;
758         int x = 0;
759
760         AST_LIST_TRAVERSE(from_list, variables, entries) {
761                 var = ast_var_name(variables);
762                 if (ast_strlen_zero(var)) {
763                         continue;
764                 }
765                 val = ast_var_value(variables);
766                 if (ast_strlen_zero(val)) {
767                         continue;
768                 }
769                 newvariable = ast_var_assign(var, val);
770                 if (newvariable) {
771                         AST_LIST_INSERT_HEAD(to_list, newvariable, entries);
772                         ++x;
773                 }
774         }
775
776         return x;
777 }
778
779 /*!
780  * \brief Delete all variables from a variable list
781  * \param headp The head pointer to the variable list to delete
782  */
783 static void free_variables(struct varshead *headp)
784 {
785         struct ast_var_t *vardata;
786
787         while ((vardata = AST_LIST_REMOVE_HEAD(headp, entries))) {
788                 ast_var_delete(vardata);
789         }
790 }
791
792 /*!
793  * \brief Copy a snapshot and its details
794  * \param dst The destination
795  * \param src The source
796  */
797 static void cdr_object_snapshot_copy(struct cdr_object_snapshot *dst, struct cdr_object_snapshot *src)
798 {
799         ao2_t_replace(dst->snapshot, src->snapshot, "CDR snapshot copy");
800         strcpy(dst->userfield, src->userfield);
801         dst->flags = src->flags;
802         copy_variables(&dst->variables, &src->variables);
803 }
804
805 /*!
806  * \brief Transition a \ref cdr_object to a new state
807  * \param cdr The \ref cdr_object to transition
808  * \param fn_table The \ref cdr_object_fn_table state to go to
809  */
810 static void cdr_object_transition_state(struct cdr_object *cdr, struct cdr_object_fn_table *fn_table)
811 {
812         CDR_DEBUG("%p - Transitioning CDR for %s from state %s to %s\n",
813                 cdr, cdr->party_a.snapshot->name,
814                 cdr->fn_table ? cdr->fn_table->name : "NONE", fn_table->name);
815         cdr->fn_table = fn_table;
816         if (cdr->fn_table->init_function) {
817                 cdr->fn_table->init_function(cdr);
818         }
819 }
820
821 /*!
822  * \internal
823  * \brief Hash function for master CDR container indexed by Party A uniqueid.
824  */
825 static int cdr_master_hash_fn(const void *obj, const int flags)
826 {
827         const struct cdr_object *cdr;
828         const char *key;
829
830         switch (flags & OBJ_SEARCH_MASK) {
831         case OBJ_SEARCH_KEY:
832                 key = obj;
833                 break;
834         case OBJ_SEARCH_OBJECT:
835                 cdr = obj;
836                 key = cdr->uniqueid;
837                 break;
838         default:
839                 ast_assert(0);
840                 return 0;
841         }
842         return ast_str_case_hash(key);
843 }
844
845 /*!
846  * \internal
847  * \brief Comparison function for master CDR container indexed by Party A uniqueid.
848  */
849 static int cdr_master_cmp_fn(void *obj, void *arg, int flags)
850 {
851     struct cdr_object *left = obj;
852     struct cdr_object *right = arg;
853     const char *right_key = arg;
854     int cmp;
855
856     switch (flags & OBJ_SEARCH_MASK) {
857     case OBJ_SEARCH_OBJECT:
858         right_key = right->uniqueid;
859         /* Fall through */
860     case OBJ_SEARCH_KEY:
861         cmp = strcmp(left->uniqueid, right_key);
862         break;
863     case OBJ_SEARCH_PARTIAL_KEY:
864         /*
865          * We could also use a partial key struct containing a length
866          * so strlen() does not get called for every comparison instead.
867          */
868         cmp = strncmp(left->uniqueid, right_key, strlen(right_key));
869         break;
870     default:
871         /* Sort can only work on something with a full or partial key. */
872         ast_assert(0);
873         cmp = 0;
874         break;
875     }
876     return cmp ? 0 : CMP_MATCH;
877 }
878
879 /*!
880  * \internal
881  * \brief Hash function for all CDR container indexed by Party B channel name.
882  */
883 static int cdr_all_hash_fn(const void *obj, const int flags)
884 {
885         const struct cdr_object *cdr;
886         const char *key;
887
888         switch (flags & OBJ_SEARCH_MASK) {
889         case OBJ_SEARCH_KEY:
890                 key = obj;
891                 break;
892         case OBJ_SEARCH_OBJECT:
893                 cdr = obj;
894                 key = cdr->party_b_name;
895                 break;
896         default:
897                 ast_assert(0);
898                 return 0;
899         }
900         return ast_str_case_hash(key);
901 }
902
903 /*!
904  * \internal
905  * \brief Comparison function for all CDR container indexed by Party B channel name.
906  */
907 static int cdr_all_cmp_fn(void *obj, void *arg, int flags)
908 {
909     struct cdr_object *left = obj;
910     struct cdr_object *right = arg;
911     const char *right_key = arg;
912     int cmp;
913
914     switch (flags & OBJ_SEARCH_MASK) {
915     case OBJ_SEARCH_OBJECT:
916         right_key = right->party_b_name;
917         /* Fall through */
918     case OBJ_SEARCH_KEY:
919         cmp = strcasecmp(left->party_b_name, right_key);
920         break;
921     case OBJ_SEARCH_PARTIAL_KEY:
922         /*
923          * We could also use a partial key struct containing a length
924          * so strlen() does not get called for every comparison instead.
925          */
926         cmp = strncasecmp(left->party_b_name, right_key, strlen(right_key));
927         break;
928     default:
929         /* Sort can only work on something with a full or partial key. */
930         ast_assert(0);
931         cmp = 0;
932         break;
933     }
934     return cmp ? 0 : CMP_MATCH;
935 }
936
937 /*!
938  * \internal
939  * \brief Relink the CDR because Party B's snapshot changed.
940  * \since 13.19.0
941  *
942  * \return Nothing
943  */
944 static void cdr_all_relink(struct cdr_object *cdr)
945 {
946         ao2_lock(active_cdrs_all);
947         if (cdr->party_b.snapshot) {
948                 if (strcasecmp(cdr->party_b_name, cdr->party_b.snapshot->name)) {
949                         ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
950                         ast_string_field_set(cdr, party_b_name, cdr->party_b.snapshot->name);
951                         ao2_link_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
952                 }
953         } else {
954                 ao2_unlink_flags(active_cdrs_all, cdr, OBJ_NOLOCK);
955                 ast_string_field_set(cdr, party_b_name, "");
956         }
957         ao2_unlock(active_cdrs_all);
958 }
959
960 /*!
961  * \internal
962  * \brief Unlink the master CDR and chained records from the active_cdrs_all container.
963  * \since 13.19.0
964  *
965  * \return Nothing
966  */
967 static void cdr_all_unlink(struct cdr_object *cdr)
968 {
969         struct cdr_object *cur;
970         struct cdr_object *next;
971
972         ast_assert(cdr->is_root);
973
974         /* Hold a ref to the root CDR to ensure the list members don't go away on us. */
975         ao2_ref(cdr, +1);
976         ao2_lock(active_cdrs_all);
977         for (cur = cdr; cur; cur = next) {
978                 next = cur->next;
979                 ao2_unlink_flags(active_cdrs_all, cur, OBJ_NOLOCK);
980                 /*
981                  * It is safe to still use cur after unlinking because the
982                  * root CDR holds a ref to all the CDRs in the list and we
983                  * have a ref to the root CDR.
984                  */
985                 ast_string_field_set(cur, party_b_name, "");
986         }
987         ao2_unlock(active_cdrs_all);
988         ao2_ref(cdr, -1);
989 }
990
991 /*!
992  * \brief \ref cdr_object Destructor
993  */
994 static void cdr_object_dtor(void *obj)
995 {
996         struct cdr_object *cdr = obj;
997         struct ast_var_t *it_var;
998
999         ao2_cleanup(cdr->party_a.snapshot);
1000         ao2_cleanup(cdr->party_b.snapshot);
1001         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
1002                 ast_var_delete(it_var);
1003         }
1004         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
1005                 ast_var_delete(it_var);
1006         }
1007         ast_string_field_free_memory(cdr);
1008
1009         /* CDR destruction used to work by calling ao2_cleanup(next) and
1010          * allowing the chain to destroy itself neatly. Unfortunately, for
1011          * really long chains, this can result in a stack overflow. So now
1012          * when the root CDR is destroyed, it is responsible for unreffing
1013          * all CDRs in the chain
1014          */
1015         if (cdr->is_root) {
1016                 struct cdr_object *curr = cdr->next;
1017                 struct cdr_object *next;
1018
1019                 while (curr) {
1020                         next = curr->next;
1021                         ao2_cleanup(curr);
1022                         curr = next;
1023                 }
1024         }
1025 }
1026
1027 /*!
1028  * \brief \ref cdr_object constructor
1029  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
1030  *
1031  * This implicitly sets the state of the newly created CDR to the Single state
1032  * (\ref single_state_fn_table)
1033  */
1034 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
1035 {
1036         struct cdr_object *cdr;
1037
1038         ast_assert(chan != NULL);
1039
1040         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1041         if (!cdr) {
1042                 return NULL;
1043         }
1044         cdr->last = cdr;
1045         if (ast_string_field_init(cdr, 64)) {
1046                 ao2_cleanup(cdr);
1047                 return NULL;
1048         }
1049         ast_string_field_set(cdr, uniqueid, chan->uniqueid);
1050         ast_string_field_set(cdr, name, chan->name);
1051         ast_string_field_set(cdr, linkedid, chan->linkedid);
1052         cdr->disposition = AST_CDR_NULL;
1053         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
1054
1055         cdr->party_a.snapshot = chan;
1056         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1057
1058         CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->name);
1059
1060         cdr_object_transition_state(cdr, &single_state_fn_table);
1061
1062         return cdr;
1063 }
1064
1065 /*!
1066  * \brief Create a new \ref cdr_object and append it to an existing chain
1067  * \param cdr The \ref cdr_object to append to
1068  */
1069 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
1070 {
1071         struct cdr_object *new_cdr;
1072         struct cdr_object *it_cdr;
1073         struct cdr_object *cdr_last;
1074
1075         cdr_last = cdr->last;
1076         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
1077         if (!new_cdr) {
1078                 return NULL;
1079         }
1080         new_cdr->disposition = AST_CDR_NULL;
1081
1082         /* Copy over the linkedid, as it may have changed */
1083         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1084         ast_string_field_set(new_cdr, appl, cdr_last->appl);
1085         ast_string_field_set(new_cdr, data, cdr_last->data);
1086         ast_string_field_set(new_cdr, context, cdr_last->context);
1087         ast_string_field_set(new_cdr, exten, cdr_last->exten);
1088
1089         /*
1090          * If the current CDR says to disable all future ones,
1091          * keep the disable chain going
1092          */
1093         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1094                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
1095         }
1096
1097         /* Copy over other Party A information */
1098         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1099
1100         /* Append the CDR to the end of the list */
1101         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1102                 it_cdr->last = new_cdr;
1103         }
1104         it_cdr->last = new_cdr;
1105         it_cdr->next = new_cdr;
1106
1107         return new_cdr;
1108 }
1109
1110 /*!
1111  * \internal
1112  * \brief Determine if CDR flag is configured.
1113  *
1114  * \param cdr_flag The configured CDR flag to check.
1115  *
1116  * \retval 0 if the CDR flag is not configured.
1117  * \retval non-zero if the CDR flag is configured.
1118  *
1119  * \return Nothing
1120  */
1121 static int is_cdr_flag_set(unsigned int cdr_flag)
1122 {
1123         struct module_config *mod_cfg;
1124         int flag_set;
1125
1126         mod_cfg = ao2_global_obj_ref(module_configs);
1127         flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1128         ao2_cleanup(mod_cfg);
1129         return flag_set;
1130 }
1131
1132 /*!
1133  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1134  * to endbeforehexten logic
1135  *
1136  * \param old_snapshot The previous state
1137  * \param new_snapshot The new state
1138  *
1139  * \retval 0 if the state has not changed
1140  * \retval 1 if the state changed
1141  */
1142 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1143         struct ast_channel_snapshot *new_snapshot)
1144 {
1145         /* If we ignore hangup logic, don't indicate that we're executing anything new */
1146         if (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1147                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1148                 return 0;
1149         }
1150
1151         /* When Party A is originated to an application and the application exits, the stack
1152          * will attempt to clear the application and restore the dummy originate application
1153          * of "AppDialX". Ignore application changes to AppDialX as a result.
1154          */
1155         if (strcmp(new_snapshot->appl, old_snapshot->appl)
1156                 && strncasecmp(new_snapshot->appl, "appdial", 7)
1157                 && (strcmp(new_snapshot->context, old_snapshot->context)
1158                         || strcmp(new_snapshot->exten, old_snapshot->exten)
1159                         || new_snapshot->priority != old_snapshot->priority)) {
1160                 return 1;
1161         }
1162
1163         return 0;
1164 }
1165
1166 /*!
1167  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1168  * that was created as the result of a dial operation
1169  *
1170  * \retval 0 the channel was not created as the result of a dial
1171  * \retval 1 the channel was created as the result of a dial
1172  */
1173 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1174 {
1175         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1176                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1177 }
1178
1179 /*!
1180  * \brief Given two CDR snapshots, figure out who should be Party A for the
1181  * resulting CDR
1182  * \param left One of the snapshots
1183  * \param right The other snapshot
1184  * \retval The snapshot that won
1185  */
1186 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
1187 {
1188         /* Check whether or not the party is dialed. A dialed party is never the
1189          * Party A with a party that was not dialed.
1190          */
1191         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1192                 return left;
1193         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1194                 return right;
1195         }
1196
1197         /* Try the Party A flag */
1198         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1199                 return left;
1200         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1201                 return right;
1202         }
1203
1204         /* Neither party is dialed and neither has the Party A flag - defer to
1205          * creation time */
1206         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
1207                 return left;
1208         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
1209                 return right;
1210         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
1211                 return right;
1212         } else {
1213                 /* Okay, fine, take the left one */
1214                 return left;
1215         }
1216 }
1217
1218 /*!
1219  * Compute the duration for a \ref cdr_object
1220  */
1221 static long cdr_object_get_duration(struct cdr_object *cdr)
1222 {
1223         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1224 }
1225
1226 /*!
1227  * \brief Compute the billsec for a \ref cdr_object
1228  */
1229 static long cdr_object_get_billsec(struct cdr_object *cdr)
1230 {
1231         long int ms;
1232
1233         if (ast_tvzero(cdr->answer)) {
1234                 return 0;
1235         }
1236
1237         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1238         if (ms % 1000 >= 500
1239                 && is_cdr_flag_set(CDR_INITIATED_SECONDS)) {
1240                 ms = (ms / 1000) + 1;
1241         } else {
1242                 ms = ms / 1000;
1243         }
1244
1245         return ms;
1246 }
1247
1248 /*!
1249  * \internal
1250  * \brief Set a variable on a CDR object
1251  *
1252  * \param headp The header pointer to the variable to set
1253  * \param name The name of the variable
1254  * \param value The value of the variable
1255  */
1256 static void set_variable(struct varshead *headp, const char *name, const char *value)
1257 {
1258         struct ast_var_t *newvariable;
1259
1260         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1261                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1262                         AST_LIST_REMOVE_CURRENT(entries);
1263                         ast_var_delete(newvariable);
1264                         break;
1265                 }
1266         }
1267         AST_LIST_TRAVERSE_SAFE_END;
1268
1269         if (value && (newvariable = ast_var_assign(name, value))) {
1270                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1271         }
1272 }
1273
1274 /*!
1275  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1276  * suitable for consumption by the registered CDR backends
1277  * \param cdr The \ref cdr_object to convert to a public record
1278  * \retval A chain of \ref ast_cdr objects on success
1279  * \retval NULL on failure
1280  */
1281 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1282 {
1283         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1284         struct cdr_object *it_cdr;
1285         struct ast_var_t *it_var, *it_copy_var;
1286         struct ast_channel_snapshot *party_a;
1287         struct ast_channel_snapshot *party_b;
1288
1289         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1290                 struct ast_cdr *cdr_copy;
1291
1292                 /* Don't create records for CDRs where the party A was a dialed channel */
1293                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1294                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1295                                 it_cdr->party_a.snapshot->name);
1296                         continue;
1297                 }
1298
1299                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1300                 if (!cdr_copy) {
1301                         ast_free(pub_cdr);
1302                         return NULL;
1303                 }
1304
1305                 party_a = it_cdr->party_a.snapshot;
1306                 party_b = it_cdr->party_b.snapshot;
1307
1308                 /* Party A */
1309                 ast_assert(party_a != NULL);
1310                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
1311                 cdr_copy->amaflags = party_a->amaflags;
1312                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
1313                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
1314                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
1315                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
1316                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1317                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1318                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1319                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1320
1321                 /* Party B */
1322                 if (party_b) {
1323                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
1324                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
1325                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1326                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1327                         }
1328                 }
1329                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1330                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1331                 }
1332
1333                 /* Timestamps/durations */
1334                 cdr_copy->start = it_cdr->start;
1335                 cdr_copy->answer = it_cdr->answer;
1336                 cdr_copy->end = it_cdr->end;
1337                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1338                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1339
1340                 /* Flags and IDs */
1341                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1342                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1343                 cdr_copy->disposition = it_cdr->disposition;
1344                 cdr_copy->sequence = it_cdr->sequence;
1345
1346                 /* Variables */
1347                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1348                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1349                         int found = 0;
1350                         struct ast_var_t *newvariable;
1351                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1352                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1353                                         found = 1;
1354                                         break;
1355                                 }
1356                         }
1357                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1358                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1359                         }
1360                 }
1361
1362                 if (!pub_cdr) {
1363                         pub_cdr = cdr_copy;
1364                         cdr_prev = pub_cdr;
1365                 } else {
1366                         cdr_prev->next = cdr_copy;
1367                         cdr_prev = cdr_copy;
1368                 }
1369         }
1370
1371         return pub_cdr;
1372 }
1373
1374 /*!
1375  * \brief Dispatch a CDR.
1376  * \param cdr The \ref cdr_object to dispatch
1377  *
1378  * This will create a \ref ast_cdr object and publish it to the various backends
1379  */
1380 static void cdr_object_dispatch(struct cdr_object *cdr)
1381 {
1382         struct ast_cdr *pub_cdr;
1383
1384         CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1385                 cdr->party_a.snapshot->name,
1386                 cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1387         pub_cdr = cdr_object_create_public_records(cdr);
1388         cdr_detach(pub_cdr);
1389 }
1390
1391 /*!
1392  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1393  * \param cdr The \ref cdr_object
1394  * \param hangupcause The Asterisk hangup cause code
1395  */
1396 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1397 {
1398         /* Change the disposition based on the hang up cause */
1399         switch (hangupcause) {
1400         case AST_CAUSE_BUSY:
1401                 cdr->disposition = AST_CDR_BUSY;
1402                 break;
1403         case AST_CAUSE_CONGESTION:
1404                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1405                         cdr->disposition = AST_CDR_FAILED;
1406                 } else {
1407                         cdr->disposition = AST_CDR_CONGESTION;
1408                 }
1409                 break;
1410         case AST_CAUSE_NO_ROUTE_DESTINATION:
1411         case AST_CAUSE_UNREGISTERED:
1412                 cdr->disposition = AST_CDR_FAILED;
1413                 break;
1414         case AST_CAUSE_NORMAL_CLEARING:
1415         case AST_CAUSE_NO_ANSWER:
1416                 cdr->disposition = AST_CDR_NOANSWER;
1417                 break;
1418         default:
1419                 break;
1420         }
1421 }
1422
1423 /*!
1424  * \brief Finalize a CDR.
1425  *
1426  * This function is safe to call multiple times. Note that you can call this
1427  * explicitly before going to the finalized state if there's a chance the CDR
1428  * will be re-activated, in which case the \ref cdr_object's end time should be
1429  * cleared. This function is implicitly called when a CDR transitions to the
1430  * finalized state and right before it is dispatched
1431  *
1432  * \param cdr_object The CDR to finalize
1433  */
1434 static void cdr_object_finalize(struct cdr_object *cdr)
1435 {
1436         if (!ast_tvzero(cdr->end)) {
1437                 return;
1438         }
1439         cdr->end = ast_tvnow();
1440
1441         if (cdr->disposition == AST_CDR_NULL) {
1442                 if (!ast_tvzero(cdr->answer)) {
1443                         cdr->disposition = AST_CDR_ANSWERED;
1444                 } else if (cdr->party_a.snapshot->hangupcause) {
1445                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1446                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1447                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1448                 } else {
1449                         cdr->disposition = AST_CDR_FAILED;
1450                 }
1451         }
1452
1453         /* tv_usec is suseconds_t, which could be int or long */
1454         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1455                         cdr->party_a.snapshot->name,
1456                         (long)cdr->start.tv_sec,
1457                         (long)cdr->start.tv_usec,
1458                         (long)cdr->answer.tv_sec,
1459                         (long)cdr->answer.tv_usec,
1460                         (long)cdr->end.tv_sec,
1461                         (long)cdr->end.tv_usec,
1462                         ast_cdr_disp2str(cdr->disposition));
1463 }
1464
1465 /*!
1466  * \brief Check to see if a CDR needs to move to the finalized state because
1467  * its Party A hungup.
1468  */
1469 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1470 {
1471         if (ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1472                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1473                 cdr_object_finalize(cdr);
1474         }
1475
1476         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1477                 && cdr->fn_table != &finalized_state_fn_table) {
1478                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1479         }
1480 }
1481
1482 /*!
1483  * \brief Check to see if a CDR needs to be answered based on its Party A.
1484  * Note that this is safe to call as much as you want - we won't answer twice
1485  */
1486 static void cdr_object_check_party_a_answer(struct cdr_object *cdr)
1487 {
1488         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1489                 cdr->answer = ast_tvnow();
1490                 /* tv_usec is suseconds_t, which could be int or long */
1491                 CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1492                         (long)cdr->answer.tv_sec,
1493                         (long)cdr->answer.tv_usec);
1494         }
1495 }
1496
1497 /* \brief Set Caller ID information on a CDR */
1498 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1499 {
1500         if (!old_snapshot->snapshot) {
1501                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1502                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1503                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1504                 return;
1505         }
1506         if (strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1507                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1508         }
1509         if (strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1510                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1511         }
1512         if (strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1513                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1514         }
1515 }
1516
1517 /*!
1518  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1519  * a new \ref ast_channel_snapshot
1520  * \param old_snapshot The old \ref cdr_object_snapshot
1521  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1522  */
1523 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1524                 struct ast_channel_snapshot *new_snapshot)
1525 {
1526         cdr_object_update_cid(old_snapshot, new_snapshot);
1527         ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1528 }
1529
1530 /* BASE METHOD IMPLEMENTATIONS */
1531
1532 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1533 {
1534         ast_assert(strcasecmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1535
1536         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1537         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1538                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1539                 cdr_object_finalize(cdr);
1540                 return 0;
1541         }
1542
1543         /*
1544          * Only record the context and extension if we aren't in a subroutine, or if
1545          * we are executing hangup logic.
1546          */
1547         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1548                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1549                 if (strcmp(cdr->context, snapshot->context)) {
1550                         ast_string_field_set(cdr, context, snapshot->context);
1551                 }
1552                 if (strcmp(cdr->exten, snapshot->exten)) {
1553                         ast_string_field_set(cdr, exten, snapshot->exten);
1554                 }
1555         }
1556
1557         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1558
1559         /* When Party A is originated to an application and the application exits, the stack
1560          * will attempt to clear the application and restore the dummy originate application
1561          * of "AppDialX". Prevent that, and any other application changes we might not want
1562          * here.
1563          */
1564         if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1565                 && !ast_strlen_zero(snapshot->appl)
1566                 && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1567                 if (strcmp(cdr->appl, snapshot->appl)) {
1568                         ast_string_field_set(cdr, appl, snapshot->appl);
1569                 }
1570                 if (strcmp(cdr->data, snapshot->data)) {
1571                         ast_string_field_set(cdr, data, snapshot->data);
1572                 }
1573
1574                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1575                  * execute before the dial begins, will alter the application/data to
1576                  * something people typically don't want to see, if we see a channel enter
1577                  * into Dial here, we set the appl/data accordingly and lock it.
1578                  */
1579                 if (!strcmp(snapshot->appl, "Dial")) {
1580                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1581                 }
1582         }
1583
1584         if (strcmp(cdr->linkedid, snapshot->linkedid)) {
1585                 ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1586         }
1587         cdr_object_check_party_a_answer(cdr);
1588         cdr_object_check_party_a_hangup(cdr);
1589
1590         return 0;
1591 }
1592
1593 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1594 {
1595         return 0;
1596 }
1597
1598 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1599 {
1600         return 0;
1601 }
1602
1603 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1604 {
1605         /* Base process bridge enter simply indicates that we can't handle it */
1606         return BRIDGE_ENTER_NEED_CDR;
1607 }
1608
1609 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1610 {
1611         char park_info[128];
1612
1613         ast_assert(!strcasecmp(parking_info->parkee->name, cdr->party_a.snapshot->name));
1614
1615         /* Update Party A information regardless */
1616         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1617
1618         /* Fake out where we're parked */
1619         ast_string_field_set(cdr, appl, "Park");
1620         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1621         ast_string_field_set(cdr, data, park_info);
1622
1623         /* Prevent any further changes to the App/Data fields for this record */
1624         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1625
1626         return 0;
1627 }
1628
1629 /* SINGLE STATE */
1630
1631 static void single_state_init_function(struct cdr_object *cdr)
1632 {
1633         cdr->start = ast_tvnow();
1634         cdr_object_check_party_a_answer(cdr);
1635 }
1636
1637 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1638 {
1639         /* This should never happen! */
1640         ast_assert(cdr->party_b.snapshot == NULL);
1641         ast_assert(0);
1642         return;
1643 }
1644
1645 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1646 {
1647         if (caller && !strcasecmp(cdr->party_a.snapshot->name, caller->name)) {
1648                 base_process_party_a(cdr, caller);
1649                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1650                         cdr->party_a.snapshot->name);
1651                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1652                 cdr_all_relink(cdr);
1653                 CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1654                         cdr->party_b.snapshot->name);
1655
1656                 /* If we have two parties, lock the application that caused the
1657                  * two parties to be associated. This prevents mid-call event
1658                  * macros/gosubs from perturbing the CDR application/data
1659                  */
1660                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1661         } else if (!strcasecmp(cdr->party_a.snapshot->name, peer->name)) {
1662                 /* We're the entity being dialed, i.e., outbound origination */
1663                 base_process_party_a(cdr, peer);
1664                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1665                         cdr->party_a.snapshot->name);
1666         }
1667
1668         cdr_object_transition_state(cdr, &dial_state_fn_table);
1669         return 0;
1670 }
1671
1672 /*!
1673  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1674  * already in the bridge while in the Single state. The goal of this is to find
1675  * a Party B for our CDR.
1676  *
1677  * \param cdr Our \ref cdr_object in the Single state
1678  * \param cand_cdr The \ref cdr_object already in the Bridge state
1679  *
1680  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1681  * Party B
1682  * \retval 1 No party in the cand_cdr could be used as our Party B
1683  */
1684 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1685                 struct cdr_object *cand_cdr)
1686 {
1687         struct cdr_object_snapshot *party_a;
1688
1689         /* Don't match on ourselves */
1690         if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1691                 return 1;
1692         }
1693
1694         /* Try the candidate CDR's Party A first */
1695         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1696         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1697                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1698                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name);
1699                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1700                 cdr_all_relink(cdr);
1701                 if (!cand_cdr->party_b.snapshot) {
1702                         /* We just stole them - finalize their CDR. Note that this won't
1703                          * transition their state, it just sets the end time and the
1704                          * disposition - if we need to re-activate them later, we can.
1705                          */
1706                         cdr_object_finalize(cand_cdr);
1707                 }
1708                 return 0;
1709         }
1710
1711         /* Try their Party B, unless it's us */
1712         if (!cand_cdr->party_b.snapshot
1713                 || !strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name)) {
1714                 return 1;
1715         }
1716         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1717         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1718                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1719                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name);
1720                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1721                 cdr_all_relink(cdr);
1722                 return 0;
1723         }
1724
1725         return 1;
1726 }
1727
1728 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)
1729 {
1730         struct ao2_iterator it_cdrs;
1731         char *channel_id;
1732         int success = 0;
1733
1734         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1735
1736         if (ao2_container_count(bridge->channels) == 1) {
1737                 /* No one in the bridge yet but us! */
1738                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1739                 return BRIDGE_ENTER_ONLY_PARTY;
1740         }
1741
1742         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1743                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1744                 ao2_ref(channel_id, -1)) {
1745                 struct cdr_object *cand_cdr_master;
1746                 struct cdr_object *cand_cdr;
1747
1748                 cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1749                 if (!cand_cdr_master) {
1750                         continue;
1751                 }
1752
1753                 ao2_lock(cand_cdr_master);
1754                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1755                         /* Skip any records that are not in a bridge or in this bridge.
1756                          * I'm not sure how that would happen, but it pays to be careful. */
1757                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1758                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1759                                 continue;
1760                         }
1761
1762                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1763                                 continue;
1764                         }
1765                         /* We successfully got a party B - break out */
1766                         success = 1;
1767                         break;
1768                 }
1769                 ao2_unlock(cand_cdr_master);
1770                 ao2_cleanup(cand_cdr_master);
1771         }
1772         ao2_iterator_destroy(&it_cdrs);
1773
1774         /* We always transition state, even if we didn't get a peer */
1775         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1776
1777         /* Success implies that we have a Party B */
1778         if (success) {
1779                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1780         }
1781
1782         return BRIDGE_ENTER_NO_PARTY_B;
1783 }
1784
1785 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1786 {
1787         cdr_object_transition_state(cdr, &parked_state_fn_table);
1788         return 0;
1789 }
1790
1791
1792 /* DIAL STATE */
1793
1794 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1795 {
1796         ast_assert(snapshot != NULL);
1797         ast_assert(cdr->party_b.snapshot
1798                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1799
1800         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1801
1802         /* If party B hangs up, finalize this CDR */
1803         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1804                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1805         }
1806 }
1807
1808 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1809 {
1810         /* Don't process a begin dial here. A party A already in the dial state will
1811          * who receives a dial begin for something else will be handled by the
1812          * message router callback and will add a new CDR for the party A */
1813         return 1;
1814 }
1815
1816 /*!
1817  * \internal
1818  * \brief Convert a dial status to a CDR disposition
1819  */
1820 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1821 {
1822         if (!strcmp(dial_status, "ANSWER")) {
1823                 return AST_CDR_ANSWERED;
1824         } else if (!strcmp(dial_status, "BUSY")) {
1825                 return AST_CDR_BUSY;
1826         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1827                 return AST_CDR_NOANSWER;
1828         } else if (!strcmp(dial_status, "CONGESTION")) {
1829                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1830                         return AST_CDR_FAILED;
1831                 } else {
1832                         return AST_CDR_CONGESTION;
1833                 }
1834         } else if (!strcmp(dial_status, "FAILED")) {
1835                 return AST_CDR_FAILED;
1836         }
1837         return AST_CDR_FAILED;
1838 }
1839
1840 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)
1841 {
1842         struct ast_channel_snapshot *party_a;
1843
1844         if (caller) {
1845                 party_a = caller;
1846         } else {
1847                 party_a = peer;
1848         }
1849         ast_assert(!strcasecmp(cdr->party_a.snapshot->name, party_a->name));
1850         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1851
1852         if (cdr->party_b.snapshot) {
1853                 if (strcasecmp(cdr->party_b.snapshot->name, peer->name)) {
1854                         /* Not the status for this CDR - defer back to the message router */
1855                         return 1;
1856                 }
1857                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1858         }
1859
1860         /* Set the disposition based on the dial string. */
1861         cdr->disposition = dial_status_to_disposition(dial_status);
1862         if (cdr->disposition == AST_CDR_ANSWERED) {
1863                 /* Switch to dial pending to wait and see what the caller does */
1864                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1865         } else {
1866                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1867         }
1868
1869         return 0;
1870 }
1871
1872 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)
1873 {
1874         int success = 0;
1875
1876         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1877
1878         /* Get parties in the bridge */
1879         if (ao2_container_count(bridge->channels) == 1) {
1880                 /* No one in the bridge yet but us! */
1881                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1882                 return BRIDGE_ENTER_ONLY_PARTY;
1883         }
1884
1885         /* If we don't have a Party B (originated channel), skip it */
1886         if (cdr->party_b.snapshot) {
1887                 struct ao2_iterator it_cdrs;
1888                 char *channel_id;
1889
1890                 for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1891                         !success && (channel_id = ao2_iterator_next(&it_cdrs));
1892                         ao2_ref(channel_id, -1)) {
1893                         struct cdr_object *cand_cdr_master;
1894                         struct cdr_object *cand_cdr;
1895
1896                         cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1897                         if (!cand_cdr_master) {
1898                                 continue;
1899                         }
1900
1901                         ao2_lock(cand_cdr_master);
1902                         for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1903                                 /* Skip any records that are not in a bridge or in this bridge.
1904                                  * I'm not sure how that would happen, but it pays to be careful. */
1905                                 if (cand_cdr->fn_table != &bridge_state_fn_table
1906                                         || strcmp(cdr->bridge, cand_cdr->bridge)) {
1907                                         continue;
1908                                 }
1909
1910                                 /* Skip any records that aren't our Party B */
1911                                 if (strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1912                                         continue;
1913                                 }
1914                                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1915                                 /* If they have a Party B, they joined up with someone else as their
1916                                  * Party A. Don't finalize them as they're active. Otherwise, we
1917                                  * have stolen them so they need to be finalized.
1918                                  */
1919                                 if (!cand_cdr->party_b.snapshot) {
1920                                         cdr_object_finalize(cand_cdr);
1921                                 }
1922                                 success = 1;
1923                                 break;
1924                         }
1925                         ao2_unlock(cand_cdr_master);
1926                         ao2_cleanup(cand_cdr_master);
1927                 }
1928                 ao2_iterator_destroy(&it_cdrs);
1929         }
1930
1931         /* We always transition state, even if we didn't get a peer */
1932         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1933
1934         /* Success implies that we have a Party B */
1935         if (success) {
1936                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1937         }
1938         return BRIDGE_ENTER_NO_PARTY_B;
1939 }
1940
1941 /* DIALED PENDING STATE */
1942
1943 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1944 {
1945         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1946          * that means we need a new CDR; otherwise, switch us over to single.
1947          */
1948         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1949                 if (cdr->party_b.snapshot) {
1950                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1951                         cdr->fn_table->process_party_a(cdr, snapshot);
1952                         return 1;
1953                 } else {
1954                         cdr_object_transition_state(cdr, &single_state_fn_table);
1955                         cdr->fn_table->process_party_a(cdr, snapshot);
1956                         return 0;
1957                 }
1958         }
1959         base_process_party_a(cdr, snapshot);
1960         return 0;
1961 }
1962
1963 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)
1964 {
1965         cdr_object_transition_state(cdr, &dial_state_fn_table);
1966         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1967 }
1968
1969 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1970 {
1971         if (cdr->party_b.snapshot) {
1972                 /* We can't handle this as we have a Party B - ask for a new one */
1973                 return 1;
1974         }
1975         cdr_object_transition_state(cdr, &parked_state_fn_table);
1976         return 0;
1977 }
1978
1979 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1980 {
1981         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1982
1983         /* Ask for a new CDR */
1984         return 1;
1985 }
1986
1987 /* BRIDGE STATE */
1988
1989 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1990 {
1991         ast_assert(cdr->party_b.snapshot
1992                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1993
1994         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1995
1996         /* If party B hangs up, finalize this CDR */
1997         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1998                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1999         }
2000 }
2001
2002 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2003 {
2004         if (strcmp(cdr->bridge, bridge->uniqueid)) {
2005                 return 1;
2006         }
2007         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)
2008                 && cdr->party_b.snapshot
2009                 && strcasecmp(cdr->party_b.snapshot->name, channel->name)) {
2010                 return 1;
2011         }
2012         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2013
2014         return 0;
2015 }
2016
2017 /* PARKED STATE */
2018
2019 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2020 {
2021         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)) {
2022                 return 1;
2023         }
2024         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2025
2026         return 0;
2027 }
2028
2029 /* FINALIZED STATE */
2030
2031 static void finalized_state_init_function(struct cdr_object *cdr)
2032 {
2033         cdr_object_finalize(cdr);
2034 }
2035
2036 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2037 {
2038         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2039                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
2040                 return 0;
2041         }
2042
2043         /* Indicate that, if possible, we should get a new CDR */
2044         return 1;
2045 }
2046
2047 /*!
2048  * \internal
2049  * \brief Filter channel snapshots by technology
2050  */
2051 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2052 {
2053         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
2054 }
2055
2056 /*!
2057  * \internal
2058  * \brief Filter a channel cache update
2059  */
2060 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
2061                 struct ast_channel_snapshot *new_snapshot)
2062 {
2063         int ret = 0;
2064
2065         /* Drop cache updates from certain channel technologies */
2066         if (old_snapshot) {
2067                 ret |= filter_channel_snapshot(old_snapshot);
2068         }
2069         if (new_snapshot) {
2070                 ret |= filter_channel_snapshot(new_snapshot);
2071         }
2072
2073         return ret;
2074 }
2075
2076 static int dial_status_end(const char *dialstatus)
2077 {
2078         return (strcmp(dialstatus, "RINGING") &&
2079                         strcmp(dialstatus, "PROCEEDING") &&
2080                         strcmp(dialstatus, "PROGRESS"));
2081 }
2082
2083 /* TOPIC ROUTER CALLBACKS */
2084
2085 /*!
2086  * \brief Handler for Stasis-Core dial messages
2087  * \param data Passed on
2088  * \param sub The stasis subscription for this message callback
2089  * \param topic The topic this message was published for
2090  * \param message The message
2091  */
2092 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2093 {
2094         struct cdr_object *cdr;
2095         struct ast_multi_channel_blob *payload = stasis_message_data(message);
2096         struct ast_channel_snapshot *caller;
2097         struct ast_channel_snapshot *peer;
2098         struct cdr_object *it_cdr;
2099         struct ast_json *dial_status_blob;
2100         const char *dial_status = NULL;
2101         int res = 1;
2102
2103         caller = ast_multi_channel_blob_get_channel(payload, "caller");
2104         peer = ast_multi_channel_blob_get_channel(payload, "peer");
2105         if (!peer && !caller) {
2106                 return;
2107         }
2108
2109         if (peer && filter_channel_snapshot(peer)) {
2110                 return;
2111         }
2112
2113         if (caller && filter_channel_snapshot(caller)) {
2114                 return;
2115         }
2116
2117         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2118         if (dial_status_blob) {
2119                 dial_status = ast_json_string_get(dial_status_blob);
2120         }
2121
2122         CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2123                 ast_strlen_zero(dial_status) ? "Begin" : "End",
2124                 caller ? caller->name : "(none)",
2125                 peer ? peer->name : "(none)",
2126                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2127                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2128
2129         /* Figure out who is running this show */
2130         if (caller) {
2131                 cdr = ao2_find(active_cdrs_master, caller->uniqueid, OBJ_SEARCH_KEY);
2132         } else {
2133                 cdr = ao2_find(active_cdrs_master, peer->uniqueid, OBJ_SEARCH_KEY);
2134         }
2135         if (!cdr) {
2136                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->name : peer->name);
2137                 ast_assert(0);
2138                 return;
2139         }
2140
2141         ao2_lock(cdr);
2142         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2143                 if (ast_strlen_zero(dial_status)) {
2144                         if (!it_cdr->fn_table->process_dial_begin) {
2145                                 continue;
2146                         }
2147                         CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2148                                 it_cdr,
2149                                 caller ? caller->name : "(none)",
2150                                 peer ? peer->name : "(none)");
2151                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2152                                         caller,
2153                                         peer);
2154                 } else if (dial_status_end(dial_status)) {
2155                         if (!it_cdr->fn_table->process_dial_end) {
2156                                 continue;
2157                         }
2158                         CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2159                                 it_cdr,
2160                                 caller ? caller->name : "(none)",
2161                                 peer ? peer->name : "(none)");
2162                         it_cdr->fn_table->process_dial_end(it_cdr,
2163                                         caller,
2164                                         peer,
2165                                         dial_status);
2166                 }
2167         }
2168
2169         /* If no CDR handled a dial begin message, make a new one */
2170         if (res && ast_strlen_zero(dial_status)) {
2171                 struct cdr_object *new_cdr;
2172
2173                 new_cdr = cdr_object_create_and_append(cdr);
2174                 if (new_cdr) {
2175                         new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2176                 }
2177         }
2178         ao2_unlock(cdr);
2179         ao2_cleanup(cdr);
2180 }
2181
2182 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2183 {
2184         struct cdr_object *cdr = obj;
2185
2186         if (!strcasecmp(cdr->party_b_name, arg)) {
2187 #ifdef AST_DEVMODE
2188                 struct ast_channel_snapshot *party_b = data;
2189
2190                 /*
2191                  * For sanity's sake we also assert the party_b snapshot
2192                  * is consistent with the key.
2193                  */
2194                 ast_assert(cdr->party_b.snapshot
2195                         && !strcasecmp(cdr->party_b.snapshot->name, party_b->name));
2196 #endif
2197
2198                 /* Don't transition to the finalized state - let the Party A do
2199                  * that when its ready
2200                  */
2201                 cdr_object_finalize(cdr);
2202         }
2203         return 0;
2204 }
2205
2206 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2207 {
2208         struct cdr_object *cdr = obj;
2209
2210         if (cdr->fn_table->process_party_b
2211                 && !strcasecmp(cdr->party_b_name, arg)) {
2212                 struct ast_channel_snapshot *party_b = data;
2213
2214                 /*
2215                  * For sanity's sake we also check the party_b snapshot
2216                  * for consistency with the key.  The callback needs and
2217                  * asserts the snapshot to be this way.
2218                  */
2219                 if (!cdr->party_b.snapshot
2220                         || strcasecmp(cdr->party_b.snapshot->name, party_b->name)) {
2221                         ast_log(LOG_NOTICE,
2222                                 "CDR for Party A %s(%s) has inconsistent Party B %s name.  Message can be ignored but this shouldn't happen.\n",
2223                                 cdr->linkedid,
2224                                 cdr->party_a.snapshot->name,
2225                                 cdr->party_b_name);
2226                         return 0;
2227                 }
2228
2229                 cdr->fn_table->process_party_b(cdr, party_b);
2230         }
2231         return 0;
2232 }
2233
2234 /*! \brief Determine if we need to add a new CDR based on snapshots */
2235 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2236                 struct ast_channel_snapshot *new_snapshot)
2237 {
2238         /* If we're dead, we don't need a new CDR */
2239         if (!new_snapshot
2240                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2241                         && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN))) {
2242                 return 0;
2243         }
2244
2245         /* Auto-fall through will increment the priority but have no application */
2246         if (ast_strlen_zero(new_snapshot->appl)) {
2247                 return 0;
2248         }
2249
2250         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2251                 return 0;
2252         }
2253
2254         return 1;
2255 }
2256
2257 /*!
2258  * \brief Handler for Stasis-Core channel cache update messages
2259  * \param data Passed on
2260  * \param sub The stasis subscription for this message callback
2261  * \param topic The topic this message was published for
2262  * \param message The message
2263  */
2264 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2265 {
2266         struct cdr_object *cdr;
2267         struct stasis_cache_update *update = stasis_message_data(message);
2268         struct ast_channel_snapshot *old_snapshot;
2269         struct ast_channel_snapshot *new_snapshot;
2270         struct cdr_object *it_cdr;
2271
2272         ast_assert(update != NULL);
2273         ast_assert(ast_channel_snapshot_type() == update->type);
2274
2275         old_snapshot = stasis_message_data(update->old_snapshot);
2276         new_snapshot = stasis_message_data(update->new_snapshot);
2277
2278         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
2279                 return;
2280         }
2281
2282         if (new_snapshot && !old_snapshot) {
2283                 cdr = cdr_object_alloc(new_snapshot);
2284                 if (!cdr) {
2285                         return;
2286                 }
2287                 cdr->is_root = 1;
2288                 ao2_link(active_cdrs_master, cdr);
2289         } else {
2290                 const char *uniqueid;
2291
2292                 uniqueid = new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid;
2293                 cdr = ao2_find(active_cdrs_master, uniqueid, OBJ_SEARCH_KEY);
2294         }
2295
2296         /* Handle Party A */
2297         if (!cdr) {
2298                 const char *name;
2299
2300                 name = new_snapshot ? new_snapshot->name : old_snapshot->name;
2301                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
2302                 ast_assert(0);
2303         } else if (new_snapshot) {
2304                 int all_reject = 1;
2305
2306                 ao2_lock(cdr);
2307                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2308                         if (!it_cdr->fn_table->process_party_a) {
2309                                 continue;
2310                         }
2311                         all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
2312                 }
2313                 if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
2314                         /* We're not hung up and we have a new snapshot - we need a new CDR */
2315                         struct cdr_object *new_cdr;
2316
2317                         new_cdr = cdr_object_create_and_append(cdr);
2318                         if (new_cdr) {
2319                                 new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
2320                         }
2321                 }
2322                 ao2_unlock(cdr);
2323         } else {
2324                 ao2_lock(cdr);
2325                 CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
2326                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2327                         cdr_object_finalize(it_cdr);
2328                 }
2329                 cdr_object_dispatch(cdr);
2330                 ao2_unlock(cdr);
2331
2332                 cdr_all_unlink(cdr);
2333                 ao2_unlink(active_cdrs_master, cdr);
2334         }
2335
2336         /* Handle Party B */
2337         if (new_snapshot) {
2338                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2339                         cdr_object_update_party_b, (char *) new_snapshot->name, new_snapshot);
2340         } else {
2341                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2342                         cdr_object_finalize_party_b, (char *) old_snapshot->name, old_snapshot);
2343         }
2344
2345         ao2_cleanup(cdr);
2346 }
2347
2348 struct bridge_leave_data {
2349         struct ast_bridge_snapshot *bridge;
2350         struct ast_channel_snapshot *channel;
2351 };
2352
2353 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2354 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2355 {
2356         struct cdr_object *cdr = obj;
2357         struct bridge_leave_data *leave_data = data;
2358
2359         if (cdr->fn_table == &bridge_state_fn_table
2360                 && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2361                 && !strcasecmp(cdr->party_b_name, arg)) {
2362                 /*
2363                  * For sanity's sake we also assert the party_b snapshot
2364                  * is consistent with the key.
2365                  */
2366                 ast_assert(cdr->party_b.snapshot
2367                         && !strcasecmp(cdr->party_b.snapshot->name, leave_data->channel->name));
2368
2369                 /* It is our Party B, in our bridge. Set the end time and let the handler
2370                  * transition our CDR appropriately when we leave the bridge.
2371                  */
2372                 cdr_object_finalize(cdr);
2373         }
2374         return 0;
2375 }
2376
2377 /*! \brief Filter bridge messages based on bridge technology */
2378 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2379 {
2380         /* Ignore holding bridge technology messages. We treat this simply as an application
2381          * that a channel enters into.
2382          */
2383         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2384                 return 1;
2385         }
2386         return 0;
2387 }
2388
2389 /*!
2390  * \brief Handler for when a channel leaves a bridge
2391  * \param data Passed on
2392  * \param sub The stasis subscription for this message callback
2393  * \param topic The topic this message was published for
2394  * \param message The message - hopefully a bridge one!
2395  */
2396 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2397                 struct stasis_message *message)
2398 {
2399         struct ast_bridge_blob *update = stasis_message_data(message);
2400         struct ast_bridge_snapshot *bridge = update->bridge;
2401         struct ast_channel_snapshot *channel = update->channel;
2402         struct cdr_object *cdr;
2403         struct cdr_object *it_cdr;
2404         struct bridge_leave_data leave_data = {
2405                 .bridge = bridge,
2406                 .channel = channel,
2407         };
2408         int left_bridge = 0;
2409
2410         if (filter_bridge_messages(bridge)) {
2411                 return;
2412         }
2413
2414         if (filter_channel_snapshot(channel)) {
2415                 return;
2416         }
2417
2418         CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2419                 channel->name,
2420                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2421                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2422
2423         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2424         if (!cdr) {
2425                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2426                 ast_assert(0);
2427                 return;
2428         }
2429
2430         /* Party A */
2431         ao2_lock(cdr);
2432         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2433                 if (!it_cdr->fn_table->process_bridge_leave) {
2434                         continue;
2435                 }
2436                 CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2437                         it_cdr, channel->name);
2438                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2439                         ast_string_field_set(it_cdr, bridge, "");
2440                         left_bridge = 1;
2441                 }
2442         }
2443         ao2_unlock(cdr);
2444
2445         /* Party B */
2446         if (left_bridge
2447                 && strcmp(bridge->subclass, "parking")) {
2448                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2449                         cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->name,
2450                         &leave_data);
2451         }
2452
2453         ao2_cleanup(cdr);
2454 }
2455
2456 /*!
2457  * \internal
2458  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2459  *
2460  * \note The new CDR will be automatically transitioned to the bridge state
2461  */
2462 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2463                 struct cdr_object_snapshot *party_b)
2464 {
2465         struct cdr_object *new_cdr;
2466
2467         new_cdr = cdr_object_create_and_append(cdr);
2468         if (!new_cdr) {
2469                 return;
2470         }
2471         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2472         cdr_all_relink(new_cdr);
2473         cdr_object_check_party_a_answer(new_cdr);
2474         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2475         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2476         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2477                 new_cdr, new_cdr->party_a.snapshot->name,
2478                 party_b->snapshot->name);
2479 }
2480
2481 /*!
2482  * \brief Process a single \ref bridge_candidate
2483  *
2484  * When a CDR enters a bridge, it needs to make pairings with everyone else
2485  * that it is not currently paired with. This function determines, for the
2486  * CDR for the channel that entered the bridge and the CDR for every other
2487  * channel currently in the bridge, who is Party A and makes new CDRs.
2488  *
2489  * \param cdr The \ref cdr_obj being processed
2490  * \param cand_cdr The \ref cdr_object that is a candidate
2491  *
2492  */
2493 static void bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2494 {
2495         struct cdr_object_snapshot *party_a;
2496         struct cdr_object *cand_cdr;
2497
2498         ao2_lock(base_cand_cdr);
2499
2500         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2501                 /* Skip any records that are not in this bridge */
2502                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2503                         continue;
2504                 }
2505
2506                 /* If the candidate is us or someone we've taken on, pass on by */
2507                 if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)
2508                         || (cdr->party_b.snapshot
2509                                 && !strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name))) {
2510                         break;
2511                 }
2512
2513                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2514                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2515                  * Party B */
2516                 if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2517                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2518                         break;
2519                 }
2520
2521                 /* We're Party B. Check if we can add ourselves immediately or if we need
2522                  * a new CDR for them (they already have a Party B) */
2523                 if (cand_cdr->party_b.snapshot
2524                         && strcasecmp(cand_cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2525                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2526                 } else {
2527                         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2528                                 cand_cdr, cand_cdr->party_a.snapshot->name,
2529                                 cdr->party_a.snapshot->name);
2530                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2531                         cdr_all_relink(cand_cdr);
2532                         /* It's possible that this joined at one point and was never chosen
2533                          * as party A. Clear their end time, as it would be set in such a
2534                          * case.
2535                          */
2536                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2537                 }
2538
2539                 break;
2540         }
2541
2542         ao2_unlock(base_cand_cdr);
2543 }
2544
2545 /*!
2546  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2547  * entered a bridge
2548  * \param cdr The \ref cdr_object that just entered the bridge
2549  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2550  */
2551 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2552 {
2553         struct ao2_iterator it_channels;
2554         char *channel_id;
2555
2556         it_channels = ao2_iterator_init(bridge->channels, 0);
2557         while ((channel_id = ao2_iterator_next(&it_channels))) {
2558                 struct cdr_object *cand_cdr;
2559
2560                 cand_cdr = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
2561                 if (cand_cdr) {
2562                         bridge_candidate_process(cdr, cand_cdr);
2563                         ao2_ref(cand_cdr, -1);
2564                 }
2565
2566                 ao2_ref(channel_id, -1);
2567         }
2568         ao2_iterator_destroy(&it_channels);
2569 }
2570
2571 /*! \brief Handle entering into a parking bridge
2572  * \param cdr The CDR to operate on
2573  * \param bridge The bridge the channel just entered
2574  * \param channel The channel snapshot
2575  */
2576 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2577                 struct ast_bridge_snapshot *bridge,
2578                 struct ast_channel_snapshot *channel)
2579 {
2580         int res = 1;
2581         struct cdr_object *it_cdr;
2582         struct cdr_object *new_cdr;
2583
2584         ao2_lock(cdr);
2585
2586         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2587                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2588                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2589                 }
2590                 if (it_cdr->fn_table->process_party_a) {
2591                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2592                                 channel->name);
2593                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2594                 }
2595         }
2596
2597         if (res) {
2598                 /* No one handled it - we need a new one! */
2599                 new_cdr = cdr_object_create_and_append(cdr);
2600                 if (new_cdr) {
2601                         /* Let the single state transition us to Parked */
2602                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2603                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2604                 }
2605         }
2606         ao2_unlock(cdr);
2607 }
2608
2609 /*! \brief Handle a bridge enter message for a 'normal' bridge
2610  * \param cdr The CDR to operate on
2611  * \param bridge The bridge the channel just entered
2612  * \param channel The channel snapshot
2613  */
2614 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2615                 struct ast_bridge_snapshot *bridge,
2616                 struct ast_channel_snapshot *channel)
2617 {
2618         enum process_bridge_enter_results result;
2619         struct cdr_object *it_cdr;
2620         struct cdr_object *new_cdr;
2621         struct cdr_object *handled_cdr = NULL;
2622
2623         ao2_lock(cdr);
2624
2625 try_again:
2626         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2627                 if (it_cdr->fn_table->process_party_a) {
2628                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2629                                 channel->name);
2630                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2631                 }
2632
2633                 /* Notify all states that they have entered a bridge */
2634                 if (it_cdr->fn_table->process_bridge_enter) {
2635                         CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2636                                 channel->name);
2637                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2638                         switch (result) {
2639                         case BRIDGE_ENTER_ONLY_PARTY:
2640                                 /* Fall through */
2641                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2642                                 if (!handled_cdr) {
2643                                         handled_cdr = it_cdr;
2644                                 }
2645                                 break;
2646                         case BRIDGE_ENTER_NEED_CDR:
2647                                 /* Pass */
2648                                 break;
2649                         case BRIDGE_ENTER_NO_PARTY_B:
2650                                 /* We didn't win on any - end this CDR. If someone else comes in later
2651                                  * that is Party B to this CDR, it can re-activate this CDR.
2652                                  */
2653                                 if (!handled_cdr) {
2654                                         handled_cdr = it_cdr;
2655                                 }
2656                                 cdr_object_finalize(cdr);
2657                                 break;
2658                         }
2659                 }
2660         }
2661
2662         /* Create the new matchings, but only for either:
2663          *  * The first CDR in the chain that handled it. This avoids issues with
2664          *    forked CDRs.
2665          *  * If no one handled it, the last CDR in the chain. This would occur if
2666          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2667          *    to make pairings with everyone in the bridge.
2668          */
2669         if (handled_cdr) {
2670                 handle_bridge_pairings(handled_cdr, bridge);
2671         } else {
2672                 /* Nothing handled it - we need a new one! */
2673                 new_cdr = cdr_object_create_and_append(cdr);
2674                 if (new_cdr) {
2675                         /* This is guaranteed to succeed: the new CDR is created in the single state
2676                          * and will be able to handle the bridge enter message
2677                          */
2678                         goto try_again;
2679                 }
2680         }
2681         ao2_unlock(cdr);
2682 }
2683
2684 /*!
2685  * \internal
2686  * \brief Handler for Stasis-Core bridge enter messages
2687  * \param data Passed on
2688  * \param sub The stasis subscription for this message callback
2689  * \param topic The topic this message was published for
2690  * \param message The message - hopefully a bridge one!
2691  */
2692 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2693                 struct stasis_message *message)
2694 {
2695         struct ast_bridge_blob *update = stasis_message_data(message);
2696         struct ast_bridge_snapshot *bridge = update->bridge;
2697         struct ast_channel_snapshot *channel = update->channel;
2698         struct cdr_object *cdr;
2699
2700         if (filter_bridge_messages(bridge)) {
2701                 return;
2702         }
2703
2704         if (filter_channel_snapshot(channel)) {
2705                 return;
2706         }
2707
2708         CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2709                 channel->name,
2710                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2711                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2712
2713         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2714         if (!cdr) {
2715                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2716                 ast_assert(0);
2717                 return;
2718         }
2719
2720         if (!strcmp(bridge->subclass, "parking")) {
2721                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2722         } else {
2723                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2724         }
2725         ao2_cleanup(cdr);
2726 }
2727
2728 /*!
2729  * \brief Handler for when a channel is parked
2730  * \param data Passed on
2731  * \param sub The stasis subscription for this message callback
2732  * \param topic The topic this message was published for
2733  * \param message The message about who got parked
2734  * */
2735 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2736                 struct stasis_message *message)
2737 {
2738         struct ast_parked_call_payload *payload = stasis_message_data(message);
2739         struct ast_channel_snapshot *channel = payload->parkee;
2740         struct cdr_object *cdr;
2741         int unhandled = 1;
2742         struct cdr_object *it_cdr;
2743
2744         /* Anything other than getting parked will be handled by other updates */
2745         if (payload->event_type != PARKED_CALL) {
2746                 return;
2747         }
2748
2749         /* No one got parked? */
2750         if (!channel) {
2751                 return;
2752         }
2753
2754         if (filter_channel_snapshot(channel)) {
2755                 return;
2756         }
2757
2758         CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2759                 channel->name,
2760                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2761                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2762
2763         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2764         if (!cdr) {
2765                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2766                 ast_assert(0);
2767                 return;
2768         }
2769
2770         ao2_lock(cdr);
2771
2772         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2773                 if (it_cdr->fn_table->process_parked_channel) {
2774                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2775                 }
2776         }
2777
2778         if (unhandled) {
2779                 /* Nothing handled the messgae - we need a new one! */
2780                 struct cdr_object *new_cdr;
2781
2782                 new_cdr = cdr_object_create_and_append(cdr);
2783                 if (new_cdr) {
2784                         /* As the new CDR is created in the single state, it is guaranteed
2785                          * to have a function for the parked call message and will handle
2786                          * the message */
2787                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2788                 }
2789         }
2790
2791         ao2_unlock(cdr);
2792
2793         ao2_cleanup(cdr);
2794 }
2795
2796 /*!
2797  * \brief Handler for a synchronization message
2798  * \param data Passed on
2799  * \param sub The stasis subscription for this message callback
2800  * \param topic The topic this message was published for
2801  * \param message A blank ao2 object
2802  * */
2803 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2804                 struct stasis_message *message)
2805 {
2806         return;
2807 }
2808
2809 struct ast_cdr_config *ast_cdr_get_config(void)
2810 {
2811         struct ast_cdr_config *general;
2812         struct module_config *mod_cfg;
2813
2814         mod_cfg = ao2_global_obj_ref(module_configs);
2815         if (!mod_cfg) {
2816                 return NULL;
2817         }
2818         general = ao2_bump(mod_cfg->general);
2819         ao2_cleanup(mod_cfg);
2820         return general;
2821 }
2822
2823 void ast_cdr_set_config(struct ast_cdr_config *config)
2824 {
2825         struct module_config *mod_cfg;
2826
2827         if (!config) {
2828                 return;
2829         }
2830
2831         mod_cfg = ao2_global_obj_ref(module_configs);
2832         if (!mod_cfg) {
2833                 return;
2834         }
2835
2836         ao2_replace(mod_cfg->general, config);
2837
2838         cdr_set_debug_mode(mod_cfg);
2839         cdr_toggle_runtime_options();
2840
2841         ao2_cleanup(mod_cfg);
2842 }
2843
2844 int ast_cdr_is_enabled(void)
2845 {
2846         return is_cdr_flag_set(CDR_ENABLED);
2847 }
2848
2849 int ast_cdr_backend_suspend(const char *name)
2850 {
2851         int success = -1;
2852         struct cdr_beitem *i = NULL;
2853
2854         AST_RWLIST_WRLOCK(&be_list);
2855         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2856                 if (!strcasecmp(name, i->name)) {
2857                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2858                         i->suspended = 1;
2859                         success = 0;
2860                 }
2861         }
2862         AST_RWLIST_UNLOCK(&be_list);
2863
2864         return success;
2865 }
2866
2867 int ast_cdr_backend_unsuspend(const char *name)
2868 {
2869         int success = -1;
2870         struct cdr_beitem *i = NULL;
2871
2872         AST_RWLIST_WRLOCK(&be_list);
2873         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2874                 if (!strcasecmp(name, i->name)) {
2875                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2876                         i->suspended = 0;
2877                         success = 0;
2878                 }
2879         }
2880         AST_RWLIST_UNLOCK(&be_list);
2881
2882         return success;
2883 }
2884
2885 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2886 {
2887         struct cdr_beitem *i;
2888         struct cdr_beitem *cur;
2889
2890         if (!name) {
2891                 return -1;
2892         }
2893
2894         if (!be) {
2895                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2896
2897                 return -1;
2898         }
2899
2900         i = ast_calloc(1, sizeof(*i));
2901         if (!i) {
2902                 return -1;
2903         }
2904
2905         i->be = be;
2906         ast_copy_string(i->name, name, sizeof(i->name));
2907         ast_copy_string(i->desc, desc, sizeof(i->desc));
2908
2909         AST_RWLIST_WRLOCK(generic_list);
2910         AST_RWLIST_TRAVERSE(generic_list, cur, list) {
2911                 if (!strcasecmp(name, cur->name)) {
2912                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2913                         AST_RWLIST_UNLOCK(generic_list);
2914                         ast_free(i);
2915
2916                         return -1;
2917                 }
2918         }
2919
2920         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2921         AST_RWLIST_UNLOCK(generic_list);
2922
2923         return 0;
2924 }
2925
2926 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2927 {
2928         return cdr_generic_register(&be_list, name, desc, be);
2929 }
2930
2931 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2932 {
2933         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2934 }
2935
2936 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2937 {
2938         struct cdr_beitem *match = NULL;
2939         int active_count;
2940
2941         AST_RWLIST_WRLOCK(generic_list);
2942         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2943                 if (!strcasecmp(name, match->name)) {
2944                         break;
2945                 }
2946         }
2947
2948         if (!match) {
2949                 AST_RWLIST_UNLOCK(generic_list);
2950                 return 0;
2951         }
2952
2953         active_count = ao2_container_count(active_cdrs_master);
2954
2955         if (!match->suspended && active_count != 0) {
2956                 AST_RWLIST_UNLOCK(generic_list);
2957                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2958                         name, active_count);
2959                 return -1;
2960         }
2961
2962         AST_RWLIST_REMOVE(generic_list, match, list);
2963         AST_RWLIST_UNLOCK(generic_list);
2964
2965         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2966         ast_free(match);
2967
2968         return 0;
2969 }
2970
2971 int ast_cdr_unregister(const char *name)
2972 {
2973         return ast_cdr_generic_unregister(&be_list, name);
2974 }
2975
2976 int ast_cdr_modifier_unregister(const char *name)
2977 {
2978         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2979 }
2980
2981 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2982 {
2983         struct ast_cdr *newcdr;
2984
2985         if (!cdr) {
2986                 return NULL;
2987         }
2988         newcdr = ast_cdr_alloc();
2989         if (!newcdr) {
2990                 return NULL;
2991         }
2992
2993         *newcdr = *cdr;
2994         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2995         copy_variables(&newcdr->varshead, &cdr->varshead);
2996         newcdr->next = NULL;
2997
2998         return newcdr;
2999 }
3000
3001 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
3002 {
3003         struct ast_var_t *variables;
3004
3005         if (ast_strlen_zero(name)) {
3006                 return NULL;
3007         }
3008
3009         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
3010                 if (!strcasecmp(name, ast_var_name(variables))) {
3011                         return ast_var_value(variables);
3012                 }
3013         }
3014
3015         return NULL;
3016 }
3017
3018 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
3019 {
3020         if (fmt == NULL) {      /* raw mode */
3021                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
3022         } else {
3023                 buf[0] = '\0';/* Ensure the buffer is initialized. */
3024                 if (when.tv_sec) {
3025                         struct ast_tm tm;
3026
3027                         ast_localtime(&when, &tm, NULL);
3028                         ast_strftime(buf, bufsize, fmt, &tm);
3029                 }
3030         }
3031 }
3032
3033 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
3034 {
3035         const char *fmt = "%Y-%m-%d %T";
3036         const char *varbuf;
3037
3038         if (!cdr) {
3039                 return;
3040         }
3041
3042         *ret = NULL;
3043
3044         if (!strcasecmp(name, "clid")) {
3045                 ast_copy_string(workspace, cdr->clid, workspacelen);
3046         } else if (!strcasecmp(name, "src")) {
3047                 ast_copy_string(workspace, cdr->src, workspacelen);
3048         } else if (!strcasecmp(name, "dst")) {
3049                 ast_copy_string(workspace, cdr->dst, workspacelen);
3050         } else if (!strcasecmp(name, "dcontext")) {
3051                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
3052         } else if (!strcasecmp(name, "channel")) {
3053                 ast_copy_string(workspace, cdr->channel, workspacelen);
3054         } else if (!strcasecmp(name, "dstchannel")) {
3055                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3056         } else if (!strcasecmp(name, "lastapp")) {
3057                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
3058         } else if (!strcasecmp(name, "lastdata")) {
3059                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
3060         } else if (!strcasecmp(name, "start")) {
3061                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3062         } else if (!strcasecmp(name, "answer")) {
3063                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3064         } else if (!strcasecmp(name, "end")) {
3065                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3066         } else if (!strcasecmp(name, "duration")) {
3067                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3068         } else if (!strcasecmp(name, "billsec")) {
3069                 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);
3070         } else if (!strcasecmp(name, "disposition")) {
3071                 if (raw) {
3072                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3073                 } else {
3074                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3075                 }
3076         } else if (!strcasecmp(name, "amaflags")) {
3077                 if (raw) {
3078                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3079                 } else {
3080                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3081                 }
3082         } else if (!strcasecmp(name, "accountcode")) {
3083                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
3084         } else if (!strcasecmp(name, "peeraccount")) {
3085                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3086         } else if (!strcasecmp(name, "uniqueid")) {
3087                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3088         } else if (!strcasecmp(name, "linkedid")) {
3089                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
3090         } else if (!strcasecmp(name, "userfield")) {
3091                 ast_copy_string(workspace, cdr->userfield, workspacelen);
3092         } else if (!strcasecmp(name, "sequence")) {
3093                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
3094         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3095                 ast_copy_string(workspace, varbuf, workspacelen);
3096         } else {
3097                 workspace[0] = '\0';
3098         }
3099
3100         if (!ast_strlen_zero(workspace)) {
3101                 *ret = workspace;
3102         }
3103 }
3104
3105 /*!
3106  * \internal
3107  * \brief Callback that finds all CDRs that reference a particular channel by name
3108  */
3109 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
3110 {
3111         struct cdr_object *cdr = obj;
3112         const char *name = arg;
3113
3114         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
3115                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
3116                 return CMP_MATCH;
3117         }
3118         return 0;
3119 }
3120
3121 /*!
3122  * \internal
3123  * \brief Callback that finds a CDR by channel name
3124  */
3125 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3126 {
3127         struct cdr_object *cdr = obj;
3128         const char *name = arg;
3129
3130         if (!strcasecmp(cdr->party_a.snapshot->name, name)) {
3131                 return CMP_MATCH;
3132         }
3133         return 0;
3134 }
3135
3136 /* Read Only CDR variables */
3137 static const char * const cdr_readonly_vars[] = {
3138         "clid",
3139         "src",
3140         "dst",
3141         "dcontext",
3142         "channel",
3143         "dstchannel",
3144         "lastapp",
3145         "lastdata",
3146         "start",
3147         "answer",
3148         "end",
3149         "duration",
3150         "billsec",
3151         "disposition",
3152         "amaflags",
3153         "accountcode",
3154         "uniqueid",
3155         "linkedid",
3156         "userfield",
3157         "sequence",
3158         NULL
3159 };
3160
3161 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3162 {
3163         struct cdr_object *cdr;
3164         struct cdr_object *it_cdr;
3165         struct ao2_iterator *it_cdrs;
3166         char *arg = ast_strdupa(channel_name);
3167         int x;
3168
3169         for (x = 0; cdr_readonly_vars[x]; x++) {
3170                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
3171                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3172                         return -1;
3173                 }
3174         }
3175
3176         it_cdrs = ao2_callback(active_cdrs_master, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
3177         if (!it_cdrs) {
3178                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3179                 return -1;
3180         }
3181
3182         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3183                 ao2_lock(cdr);
3184                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3185                         struct varshead *headp = NULL;
3186
3187                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3188                                 continue;
3189                         }
3190                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->name)) {
3191                                 headp = &it_cdr->party_a.variables;
3192                         } else if (it_cdr->party_b.snapshot
3193                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->name)) {
3194                                 headp = &it_cdr->party_b.variables;
3195                         }
3196                         if (headp) {
3197                                 set_variable(headp, name, value);
3198                         }
3199                 }
3200         }
3201         ao2_iterator_destroy(it_cdrs);
3202
3203         return 0;
3204 }
3205
3206 /*!
3207  * \brief Format a variable on a \ref cdr_object
3208  */
3209 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3210 {
3211         struct ast_var_t *variable;
3212
3213         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3214                 if (!strcasecmp(name, ast_var_name(variable))) {
3215                         ast_copy_string(value, ast_var_value(variable), length);
3216                         return;
3217                 }
3218         }
3219
3220         *value = '\0';
3221 }
3222
3223 /*!
3224  * \brief Format one of the standard properties on a \ref cdr_object
3225  */
3226 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3227 {
3228         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3229         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3230
3231         if (!strcasecmp(name, "clid")) {
3232                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
3233         } else if (!strcasecmp(name, "src")) {
3234                 ast_copy_string(value, party_a->caller_number, length);
3235         } else if (!strcasecmp(name, "dst")) {
3236                 ast_copy_string(value, party_a->exten, length);
3237         } else if (!strcasecmp(name, "dcontext")) {
3238                 ast_copy_string(value, party_a->context, length);
3239         } else if (!strcasecmp(name, "channel")) {
3240                 ast_copy_string(value, party_a->name, length);
3241         } else if (!strcasecmp(name, "dstchannel")) {
3242                 if (party_b) {
3243                         ast_copy_string(value, party_b->name, length);
3244                 } else {
3245                         ast_copy_string(value, "", length);
3246                 }
3247         } else if (!strcasecmp(name, "lastapp")) {
3248                 ast_copy_string(value, party_a->appl, length);
3249         } else if (!strcasecmp(name, "lastdata")) {
3250                 ast_copy_string(value, party_a->data, length);
3251         } else if (!strcasecmp(name, "start")) {
3252                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3253         } else if (!strcasecmp(name, "answer")) {
3254                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3255         } else if (!strcasecmp(name, "end")) {
3256                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3257         } else if (!strcasecmp(name, "duration")) {
3258                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3259         } else if (!strcasecmp(name, "billsec")) {
3260                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3261         } else if (!strcasecmp(name, "disposition")) {
3262                 snprintf(value, length, "%u", cdr_obj->disposition);
3263         } else if (!strcasecmp(name, "amaflags")) {
3264                 snprintf(value, length, "%d", party_a->amaflags);
3265         } else if (!strcasecmp(name, "accountcode")) {
3266                 ast_copy_string(value, party_a->accountcode, length);
3267         } else if (!strcasecmp(name, "peeraccount")) {
3268                 if (party_b) {
3269                         ast_copy_string(value, party_b->accountcode, length);
3270                 } else {
3271                         ast_copy_string(value, "", length);
3272                 }
3273         } else if (!strcasecmp(name, "uniqueid")) {
3274                 ast_copy_string(value, party_a->uniqueid, length);
3275         } else if (!strcasecmp(name, "linkedid")) {
3276                 ast_copy_string(value, cdr_obj->linkedid, length);
3277         } else if (!strcasecmp(name, "userfield")) {
3278                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3279         } else if (!strcasecmp(name, "sequence")) {
3280                 snprintf(value, length, "%u", cdr_obj->sequence);
3281         } else {
3282                 return 1;
3283         }
3284
3285         return 0;
3286 }
3287
3288 /*! \internal
3289  * \brief Look up and retrieve a CDR object by channel name
3290  * \param name The name of the channel
3291  * \retval NULL on error
3292  * \retval The \ref cdr_object for the channel on success, with the reference
3293  *      count bumped by one.
3294  */
3295 static struct cdr_object *cdr_object_get_by_name(const char *name)
3296 {
3297         char *param;
3298
3299         if (ast_strlen_zero(name)) {
3300                 return NULL;
3301         }
3302
3303         param = ast_strdupa(name);
3304         return ao2_callback(active_cdrs_master, 0, cdr_object_get_by_name_cb, param);
3305 }
3306
3307 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3308 {
3309         struct cdr_object *cdr;
3310         struct cdr_object *cdr_obj;
3311
3312         if (ast_strlen_zero(name)) {
3313                 return 1;
3314         }
3315
3316         cdr = cdr_object_get_by_name(channel_name);
3317         if (!cdr) {
3318