cdr: submit: fix logic of test for batch mode
[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 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         ao2_lock(active_cdrs_all);
975         for (cur = cdr->next; cur; cur = next) {
976                 next = cur->next;
977                 ao2_unlink_flags(active_cdrs_all, cur, OBJ_NOLOCK);
978                 ast_string_field_set(cur, party_b_name, "");
979         }
980         ao2_unlock(active_cdrs_all);
981 }
982
983 /*!
984  * \brief \ref cdr_object Destructor
985  */
986 static void cdr_object_dtor(void *obj)
987 {
988         struct cdr_object *cdr = obj;
989         struct ast_var_t *it_var;
990
991         ao2_cleanup(cdr->party_a.snapshot);
992         ao2_cleanup(cdr->party_b.snapshot);
993         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_a.variables, entries))) {
994                 ast_var_delete(it_var);
995         }
996         while ((it_var = AST_LIST_REMOVE_HEAD(&cdr->party_b.variables, entries))) {
997                 ast_var_delete(it_var);
998         }
999         ast_string_field_free_memory(cdr);
1000
1001         /* CDR destruction used to work by calling ao2_cleanup(next) and
1002          * allowing the chain to destroy itself neatly. Unfortunately, for
1003          * really long chains, this can result in a stack overflow. So now
1004          * when the root CDR is destroyed, it is responsible for unreffing
1005          * all CDRs in the chain
1006          */
1007         if (cdr->is_root) {
1008                 struct cdr_object *curr = cdr->next;
1009                 struct cdr_object *next;
1010
1011                 while (curr) {
1012                         next = curr->next;
1013                         ao2_cleanup(curr);
1014                         curr = next;
1015                 }
1016         }
1017 }
1018
1019 /*!
1020  * \brief \ref cdr_object constructor
1021  * \param chan The \ref ast_channel_snapshot that is the CDR's Party A
1022  *
1023  * This implicitly sets the state of the newly created CDR to the Single state
1024  * (\ref single_state_fn_table)
1025  */
1026 static struct cdr_object *cdr_object_alloc(struct ast_channel_snapshot *chan)
1027 {
1028         struct cdr_object *cdr;
1029
1030         ast_assert(chan != NULL);
1031
1032         cdr = ao2_alloc(sizeof(*cdr), cdr_object_dtor);
1033         if (!cdr) {
1034                 return NULL;
1035         }
1036         cdr->last = cdr;
1037         if (ast_string_field_init(cdr, 64)) {
1038                 ao2_cleanup(cdr);
1039                 return NULL;
1040         }
1041         ast_string_field_set(cdr, uniqueid, chan->uniqueid);
1042         ast_string_field_set(cdr, name, chan->name);
1043         ast_string_field_set(cdr, linkedid, chan->linkedid);
1044         cdr->disposition = AST_CDR_NULL;
1045         cdr->sequence = ast_atomic_fetchadd_int(&global_cdr_sequence, +1);
1046
1047         cdr->party_a.snapshot = chan;
1048         ao2_t_ref(cdr->party_a.snapshot, +1, "bump snapshot during CDR creation");
1049
1050         CDR_DEBUG("%p - Created CDR for channel %s\n", cdr, chan->name);
1051
1052         cdr_object_transition_state(cdr, &single_state_fn_table);
1053
1054         return cdr;
1055 }
1056
1057 /*!
1058  * \brief Create a new \ref cdr_object and append it to an existing chain
1059  * \param cdr The \ref cdr_object to append to
1060  */
1061 static struct cdr_object *cdr_object_create_and_append(struct cdr_object *cdr)
1062 {
1063         struct cdr_object *new_cdr;
1064         struct cdr_object *it_cdr;
1065         struct cdr_object *cdr_last;
1066
1067         cdr_last = cdr->last;
1068         new_cdr = cdr_object_alloc(cdr_last->party_a.snapshot);
1069         if (!new_cdr) {
1070                 return NULL;
1071         }
1072         new_cdr->disposition = AST_CDR_NULL;
1073
1074         /* Copy over the linkedid, as it may have changed */
1075         ast_string_field_set(new_cdr, linkedid, cdr_last->linkedid);
1076         ast_string_field_set(new_cdr, appl, cdr_last->appl);
1077         ast_string_field_set(new_cdr, data, cdr_last->data);
1078         ast_string_field_set(new_cdr, context, cdr_last->context);
1079         ast_string_field_set(new_cdr, exten, cdr_last->exten);
1080
1081         /*
1082          * If the current CDR says to disable all future ones,
1083          * keep the disable chain going
1084          */
1085         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
1086                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
1087         }
1088
1089         /* Copy over other Party A information */
1090         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
1091
1092         /* Append the CDR to the end of the list */
1093         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
1094                 it_cdr->last = new_cdr;
1095         }
1096         it_cdr->last = new_cdr;
1097         it_cdr->next = new_cdr;
1098
1099         return new_cdr;
1100 }
1101
1102 /*!
1103  * \internal
1104  * \brief Determine if CDR flag is configured.
1105  *
1106  * \param cdr_flag The configured CDR flag to check.
1107  *
1108  * \retval 0 if the CDR flag is not configured.
1109  * \retval non-zero if the CDR flag is configured.
1110  *
1111  * \return Nothing
1112  */
1113 static int is_cdr_flag_set(unsigned int cdr_flag)
1114 {
1115         struct module_config *mod_cfg;
1116         int flag_set;
1117
1118         mod_cfg = ao2_global_obj_ref(module_configs);
1119         flag_set = mod_cfg && ast_test_flag(&mod_cfg->general->settings, cdr_flag);
1120         ao2_cleanup(mod_cfg);
1121         return flag_set;
1122 }
1123
1124 /*!
1125  * \brief Return whether or not a channel has changed its state in the dialplan, subject
1126  * to endbeforehexten logic
1127  *
1128  * \param old_snapshot The previous state
1129  * \param new_snapshot The new state
1130  *
1131  * \retval 0 if the state has not changed
1132  * \retval 1 if the state changed
1133  */
1134 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
1135         struct ast_channel_snapshot *new_snapshot)
1136 {
1137         /* If we ignore hangup logic, don't indicate that we're executing anything new */
1138         if (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1139                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1140                 return 0;
1141         }
1142
1143         /* When Party A is originated to an application and the application exits, the stack
1144          * will attempt to clear the application and restore the dummy originate application
1145          * of "AppDialX". Ignore application changes to AppDialX as a result.
1146          */
1147         if (strcmp(new_snapshot->appl, old_snapshot->appl)
1148                 && strncasecmp(new_snapshot->appl, "appdial", 7)
1149                 && (strcmp(new_snapshot->context, old_snapshot->context)
1150                         || strcmp(new_snapshot->exten, old_snapshot->exten)
1151                         || new_snapshot->priority != old_snapshot->priority)) {
1152                 return 1;
1153         }
1154
1155         return 0;
1156 }
1157
1158 /*!
1159  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
1160  * that was created as the result of a dial operation
1161  *
1162  * \retval 0 the channel was not created as the result of a dial
1163  * \retval 1 the channel was created as the result of a dial
1164  */
1165 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
1166 {
1167         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
1168                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
1169 }
1170
1171 /*!
1172  * \brief Given two CDR snapshots, figure out who should be Party A for the
1173  * resulting CDR
1174  * \param left One of the snapshots
1175  * \param right The other snapshot
1176  * \retval The snapshot that won
1177  */
1178 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
1179 {
1180         /* Check whether or not the party is dialed. A dialed party is never the
1181          * Party A with a party that was not dialed.
1182          */
1183         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1184                 return left;
1185         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1186                 return right;
1187         }
1188
1189         /* Try the Party A flag */
1190         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1191                 return left;
1192         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1193                 return right;
1194         }
1195
1196         /* Neither party is dialed and neither has the Party A flag - defer to
1197          * creation time */
1198         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
1199                 return left;
1200         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
1201                 return right;
1202         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
1203                 return right;
1204         } else {
1205                 /* Okay, fine, take the left one */
1206                 return left;
1207         }
1208 }
1209
1210 /*!
1211  * Compute the duration for a \ref cdr_object
1212  */
1213 static long cdr_object_get_duration(struct cdr_object *cdr)
1214 {
1215         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1216 }
1217
1218 /*!
1219  * \brief Compute the billsec for a \ref cdr_object
1220  */
1221 static long cdr_object_get_billsec(struct cdr_object *cdr)
1222 {
1223         long int ms;
1224
1225         if (ast_tvzero(cdr->answer)) {
1226                 return 0;
1227         }
1228
1229         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1230         if (ms % 1000 >= 500
1231                 && is_cdr_flag_set(CDR_INITIATED_SECONDS)) {
1232                 ms = (ms / 1000) + 1;
1233         } else {
1234                 ms = ms / 1000;
1235         }
1236
1237         return ms;
1238 }
1239
1240 /*!
1241  * \internal
1242  * \brief Set a variable on a CDR object
1243  *
1244  * \param headp The header pointer to the variable to set
1245  * \param name The name of the variable
1246  * \param value The value of the variable
1247  */
1248 static void set_variable(struct varshead *headp, const char *name, const char *value)
1249 {
1250         struct ast_var_t *newvariable;
1251
1252         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1253                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1254                         AST_LIST_REMOVE_CURRENT(entries);
1255                         ast_var_delete(newvariable);
1256                         break;
1257                 }
1258         }
1259         AST_LIST_TRAVERSE_SAFE_END;
1260
1261         if (value && (newvariable = ast_var_assign(name, value))) {
1262                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1263         }
1264 }
1265
1266 /*!
1267  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1268  * suitable for consumption by the registered CDR backends
1269  * \param cdr The \ref cdr_object to convert to a public record
1270  * \retval A chain of \ref ast_cdr objects on success
1271  * \retval NULL on failure
1272  */
1273 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1274 {
1275         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1276         struct cdr_object *it_cdr;
1277         struct ast_var_t *it_var, *it_copy_var;
1278         struct ast_channel_snapshot *party_a;
1279         struct ast_channel_snapshot *party_b;
1280
1281         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1282                 struct ast_cdr *cdr_copy;
1283
1284                 /* Don't create records for CDRs where the party A was a dialed channel */
1285                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1286                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1287                                 it_cdr->party_a.snapshot->name);
1288                         continue;
1289                 }
1290
1291                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1292                 if (!cdr_copy) {
1293                         ast_free(pub_cdr);
1294                         return NULL;
1295                 }
1296
1297                 party_a = it_cdr->party_a.snapshot;
1298                 party_b = it_cdr->party_b.snapshot;
1299
1300                 /* Party A */
1301                 ast_assert(party_a != NULL);
1302                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
1303                 cdr_copy->amaflags = party_a->amaflags;
1304                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
1305                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
1306                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
1307                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
1308                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1309                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1310                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1311                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1312
1313                 /* Party B */
1314                 if (party_b) {
1315                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
1316                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
1317                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1318                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1319                         }
1320                 }
1321                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1322                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1323                 }
1324
1325                 /* Timestamps/durations */
1326                 cdr_copy->start = it_cdr->start;
1327                 cdr_copy->answer = it_cdr->answer;
1328                 cdr_copy->end = it_cdr->end;
1329                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1330                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1331
1332                 /* Flags and IDs */
1333                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1334                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1335                 cdr_copy->disposition = it_cdr->disposition;
1336                 cdr_copy->sequence = it_cdr->sequence;
1337
1338                 /* Variables */
1339                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1340                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1341                         int found = 0;
1342                         struct ast_var_t *newvariable;
1343                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1344                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1345                                         found = 1;
1346                                         break;
1347                                 }
1348                         }
1349                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1350                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1351                         }
1352                 }
1353
1354                 if (!pub_cdr) {
1355                         pub_cdr = cdr_copy;
1356                         cdr_prev = pub_cdr;
1357                 } else {
1358                         cdr_prev->next = cdr_copy;
1359                         cdr_prev = cdr_copy;
1360                 }
1361         }
1362
1363         return pub_cdr;
1364 }
1365
1366 /*!
1367  * \brief Dispatch a CDR.
1368  * \param cdr The \ref cdr_object to dispatch
1369  *
1370  * This will create a \ref ast_cdr object and publish it to the various backends
1371  */
1372 static void cdr_object_dispatch(struct cdr_object *cdr)
1373 {
1374         struct ast_cdr *pub_cdr;
1375
1376         CDR_DEBUG("%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1377                 cdr->party_a.snapshot->name,
1378                 cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1379         pub_cdr = cdr_object_create_public_records(cdr);
1380         cdr_detach(pub_cdr);
1381 }
1382
1383 /*!
1384  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1385  * \param cdr The \ref cdr_object
1386  * \param hangupcause The Asterisk hangup cause code
1387  */
1388 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1389 {
1390         /* Change the disposition based on the hang up cause */
1391         switch (hangupcause) {
1392         case AST_CAUSE_BUSY:
1393                 cdr->disposition = AST_CDR_BUSY;
1394                 break;
1395         case AST_CAUSE_CONGESTION:
1396                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1397                         cdr->disposition = AST_CDR_FAILED;
1398                 } else {
1399                         cdr->disposition = AST_CDR_CONGESTION;
1400                 }
1401                 break;
1402         case AST_CAUSE_NO_ROUTE_DESTINATION:
1403         case AST_CAUSE_UNREGISTERED:
1404                 cdr->disposition = AST_CDR_FAILED;
1405                 break;
1406         case AST_CAUSE_NORMAL_CLEARING:
1407         case AST_CAUSE_NO_ANSWER:
1408                 cdr->disposition = AST_CDR_NOANSWER;
1409                 break;
1410         default:
1411                 break;
1412         }
1413 }
1414
1415 /*!
1416  * \brief Finalize a CDR.
1417  *
1418  * This function is safe to call multiple times. Note that you can call this
1419  * explicitly before going to the finalized state if there's a chance the CDR
1420  * will be re-activated, in which case the \ref cdr_object's end time should be
1421  * cleared. This function is implicitly called when a CDR transitions to the
1422  * finalized state and right before it is dispatched
1423  *
1424  * \param cdr_object The CDR to finalize
1425  */
1426 static void cdr_object_finalize(struct cdr_object *cdr)
1427 {
1428         if (!ast_tvzero(cdr->end)) {
1429                 return;
1430         }
1431         cdr->end = ast_tvnow();
1432
1433         if (cdr->disposition == AST_CDR_NULL) {
1434                 if (!ast_tvzero(cdr->answer)) {
1435                         cdr->disposition = AST_CDR_ANSWERED;
1436                 } else if (cdr->party_a.snapshot->hangupcause) {
1437                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1438                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1439                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1440                 } else {
1441                         cdr->disposition = AST_CDR_FAILED;
1442                 }
1443         }
1444
1445         /* tv_usec is suseconds_t, which could be int or long */
1446         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1447                         cdr->party_a.snapshot->name,
1448                         (long)cdr->start.tv_sec,
1449                         (long)cdr->start.tv_usec,
1450                         (long)cdr->answer.tv_sec,
1451                         (long)cdr->answer.tv_usec,
1452                         (long)cdr->end.tv_sec,
1453                         (long)cdr->end.tv_usec,
1454                         ast_cdr_disp2str(cdr->disposition));
1455 }
1456
1457 /*!
1458  * \brief Check to see if a CDR needs to move to the finalized state because
1459  * its Party A hungup.
1460  */
1461 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1462 {
1463         if (ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1464                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1465                 cdr_object_finalize(cdr);
1466         }
1467
1468         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1469                 && cdr->fn_table != &finalized_state_fn_table) {
1470                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1471         }
1472 }
1473
1474 /*!
1475  * \brief Check to see if a CDR needs to be answered based on its Party A.
1476  * Note that this is safe to call as much as you want - we won't answer twice
1477  */
1478 static void cdr_object_check_party_a_answer(struct cdr_object *cdr)
1479 {
1480         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1481                 cdr->answer = ast_tvnow();
1482                 /* tv_usec is suseconds_t, which could be int or long */
1483                 CDR_DEBUG("%p - Set answered time to %ld.%06ld\n", cdr,
1484                         (long)cdr->answer.tv_sec,
1485                         (long)cdr->answer.tv_usec);
1486         }
1487 }
1488
1489 /* \brief Set Caller ID information on a CDR */
1490 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1491 {
1492         if (!old_snapshot->snapshot) {
1493                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1494                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1495                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1496                 return;
1497         }
1498         if (strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1499                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1500         }
1501         if (strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1502                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1503         }
1504         if (strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1505                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1506         }
1507 }
1508
1509 /*!
1510  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1511  * a new \ref ast_channel_snapshot
1512  * \param old_snapshot The old \ref cdr_object_snapshot
1513  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1514  */
1515 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1516                 struct ast_channel_snapshot *new_snapshot)
1517 {
1518         cdr_object_update_cid(old_snapshot, new_snapshot);
1519         ao2_t_replace(old_snapshot->snapshot, new_snapshot, "Swap CDR shapshot");
1520 }
1521
1522 /* BASE METHOD IMPLEMENTATIONS */
1523
1524 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1525 {
1526         ast_assert(strcasecmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1527
1528         /* Finalize the CDR if we're in hangup logic and we're set to do so */
1529         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1530                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
1531                 cdr_object_finalize(cdr);
1532                 return 0;
1533         }
1534
1535         /*
1536          * Only record the context and extension if we aren't in a subroutine, or if
1537          * we are executing hangup logic.
1538          */
1539         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1540                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1541                 if (strcmp(cdr->context, snapshot->context)) {
1542                         ast_string_field_set(cdr, context, snapshot->context);
1543                 }
1544                 if (strcmp(cdr->exten, snapshot->exten)) {
1545                         ast_string_field_set(cdr, exten, snapshot->exten);
1546                 }
1547         }
1548
1549         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1550
1551         /* When Party A is originated to an application and the application exits, the stack
1552          * will attempt to clear the application and restore the dummy originate application
1553          * of "AppDialX". Prevent that, and any other application changes we might not want
1554          * here.
1555          */
1556         if (!ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)
1557                 && !ast_strlen_zero(snapshot->appl)
1558                 && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))) {
1559                 if (strcmp(cdr->appl, snapshot->appl)) {
1560                         ast_string_field_set(cdr, appl, snapshot->appl);
1561                 }
1562                 if (strcmp(cdr->data, snapshot->data)) {
1563                         ast_string_field_set(cdr, data, snapshot->data);
1564                 }
1565
1566                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1567                  * execute before the dial begins, will alter the application/data to
1568                  * something people typically don't want to see, if we see a channel enter
1569                  * into Dial here, we set the appl/data accordingly and lock it.
1570                  */
1571                 if (!strcmp(snapshot->appl, "Dial")) {
1572                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1573                 }
1574         }
1575
1576         if (strcmp(cdr->linkedid, snapshot->linkedid)) {
1577                 ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1578         }
1579         cdr_object_check_party_a_answer(cdr);
1580         cdr_object_check_party_a_hangup(cdr);
1581
1582         return 0;
1583 }
1584
1585 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1586 {
1587         return 0;
1588 }
1589
1590 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1591 {
1592         return 0;
1593 }
1594
1595 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1596 {
1597         /* Base process bridge enter simply indicates that we can't handle it */
1598         return BRIDGE_ENTER_NEED_CDR;
1599 }
1600
1601 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1602 {
1603         char park_info[128];
1604
1605         ast_assert(!strcasecmp(parking_info->parkee->name, cdr->party_a.snapshot->name));
1606
1607         /* Update Party A information regardless */
1608         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1609
1610         /* Fake out where we're parked */
1611         ast_string_field_set(cdr, appl, "Park");
1612         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1613         ast_string_field_set(cdr, data, park_info);
1614
1615         /* Prevent any further changes to the App/Data fields for this record */
1616         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1617
1618         return 0;
1619 }
1620
1621 /* SINGLE STATE */
1622
1623 static void single_state_init_function(struct cdr_object *cdr)
1624 {
1625         cdr->start = ast_tvnow();
1626         cdr_object_check_party_a_answer(cdr);
1627 }
1628
1629 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1630 {
1631         /* This should never happen! */
1632         ast_assert(cdr->party_b.snapshot == NULL);
1633         ast_assert(0);
1634         return;
1635 }
1636
1637 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1638 {
1639         if (caller && !strcasecmp(cdr->party_a.snapshot->name, caller->name)) {
1640                 base_process_party_a(cdr, caller);
1641                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1642                         cdr->party_a.snapshot->name);
1643                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1644                 cdr_all_relink(cdr);
1645                 CDR_DEBUG("%p - Updated Party B %s snapshot\n", cdr,
1646                         cdr->party_b.snapshot->name);
1647
1648                 /* If we have two parties, lock the application that caused the
1649                  * two parties to be associated. This prevents mid-call event
1650                  * macros/gosubs from perturbing the CDR application/data
1651                  */
1652                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1653         } else if (!strcasecmp(cdr->party_a.snapshot->name, peer->name)) {
1654                 /* We're the entity being dialed, i.e., outbound origination */
1655                 base_process_party_a(cdr, peer);
1656                 CDR_DEBUG("%p - Updated Party A %s snapshot\n", cdr,
1657                         cdr->party_a.snapshot->name);
1658         }
1659
1660         cdr_object_transition_state(cdr, &dial_state_fn_table);
1661         return 0;
1662 }
1663
1664 /*!
1665  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1666  * already in the bridge while in the Single state. The goal of this is to find
1667  * a Party B for our CDR.
1668  *
1669  * \param cdr Our \ref cdr_object in the Single state
1670  * \param cand_cdr The \ref cdr_object already in the Bridge state
1671  *
1672  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1673  * Party B
1674  * \retval 1 No party in the cand_cdr could be used as our Party B
1675  */
1676 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1677                 struct cdr_object *cand_cdr)
1678 {
1679         struct cdr_object_snapshot *party_a;
1680
1681         /* Don't match on ourselves */
1682         if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1683                 return 1;
1684         }
1685
1686         /* Try the candidate CDR's Party A first */
1687         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1688         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1689                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1690                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name);
1691                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1692                 cdr_all_relink(cdr);
1693                 if (!cand_cdr->party_b.snapshot) {
1694                         /* We just stole them - finalize their CDR. Note that this won't
1695                          * transition their state, it just sets the end time and the
1696                          * disposition - if we need to re-activate them later, we can.
1697                          */
1698                         cdr_object_finalize(cand_cdr);
1699                 }
1700                 return 0;
1701         }
1702
1703         /* Try their Party B, unless it's us */
1704         if (!cand_cdr->party_b.snapshot
1705                 || !strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name)) {
1706                 return 1;
1707         }
1708         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1709         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1710                 CDR_DEBUG("%p - Party A %s has new Party B %s\n",
1711                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name);
1712                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1713                 cdr_all_relink(cdr);
1714                 return 0;
1715         }
1716
1717         return 1;
1718 }
1719
1720 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)
1721 {
1722         struct ao2_iterator it_cdrs;
1723         char *channel_id;
1724         int success = 0;
1725
1726         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1727
1728         if (ao2_container_count(bridge->channels) == 1) {
1729                 /* No one in the bridge yet but us! */
1730                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1731                 return BRIDGE_ENTER_ONLY_PARTY;
1732         }
1733
1734         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1735                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1736                 ao2_ref(channel_id, -1)) {
1737                 struct cdr_object *cand_cdr_master;
1738                 struct cdr_object *cand_cdr;
1739
1740                 cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1741                 if (!cand_cdr_master) {
1742                         continue;
1743                 }
1744
1745                 ao2_lock(cand_cdr_master);
1746                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1747                         /* Skip any records that are not in a bridge or in this bridge.
1748                          * I'm not sure how that would happen, but it pays to be careful. */
1749                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1750                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1751                                 continue;
1752                         }
1753
1754                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1755                                 continue;
1756                         }
1757                         /* We successfully got a party B - break out */
1758                         success = 1;
1759                         break;
1760                 }
1761                 ao2_unlock(cand_cdr_master);
1762                 ao2_cleanup(cand_cdr_master);
1763         }
1764         ao2_iterator_destroy(&it_cdrs);
1765
1766         /* We always transition state, even if we didn't get a peer */
1767         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1768
1769         /* Success implies that we have a Party B */
1770         if (success) {
1771                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1772         }
1773
1774         return BRIDGE_ENTER_NO_PARTY_B;
1775 }
1776
1777 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1778 {
1779         cdr_object_transition_state(cdr, &parked_state_fn_table);
1780         return 0;
1781 }
1782
1783
1784 /* DIAL STATE */
1785
1786 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1787 {
1788         ast_assert(snapshot != NULL);
1789         ast_assert(cdr->party_b.snapshot
1790                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1791
1792         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1793
1794         /* If party B hangs up, finalize this CDR */
1795         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1796                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1797         }
1798 }
1799
1800 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1801 {
1802         /* Don't process a begin dial here. A party A already in the dial state will
1803          * who receives a dial begin for something else will be handled by the
1804          * message router callback and will add a new CDR for the party A */
1805         return 1;
1806 }
1807
1808 /*!
1809  * \internal
1810  * \brief Convert a dial status to a CDR disposition
1811  */
1812 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1813 {
1814         if (!strcmp(dial_status, "ANSWER")) {
1815                 return AST_CDR_ANSWERED;
1816         } else if (!strcmp(dial_status, "BUSY")) {
1817                 return AST_CDR_BUSY;
1818         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1819                 return AST_CDR_NOANSWER;
1820         } else if (!strcmp(dial_status, "CONGESTION")) {
1821                 if (!is_cdr_flag_set(CDR_CONGESTION)) {
1822                         return AST_CDR_FAILED;
1823                 } else {
1824                         return AST_CDR_CONGESTION;
1825                 }
1826         } else if (!strcmp(dial_status, "FAILED")) {
1827                 return AST_CDR_FAILED;
1828         }
1829         return AST_CDR_FAILED;
1830 }
1831
1832 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)
1833 {
1834         struct ast_channel_snapshot *party_a;
1835
1836         if (caller) {
1837                 party_a = caller;
1838         } else {
1839                 party_a = peer;
1840         }
1841         ast_assert(!strcasecmp(cdr->party_a.snapshot->name, party_a->name));
1842         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1843
1844         if (cdr->party_b.snapshot) {
1845                 if (strcasecmp(cdr->party_b.snapshot->name, peer->name)) {
1846                         /* Not the status for this CDR - defer back to the message router */
1847                         return 1;
1848                 }
1849                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1850         }
1851
1852         /* Set the disposition based on the dial string. */
1853         cdr->disposition = dial_status_to_disposition(dial_status);
1854         if (cdr->disposition == AST_CDR_ANSWERED) {
1855                 /* Switch to dial pending to wait and see what the caller does */
1856                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1857         } else {
1858                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1859         }
1860
1861         return 0;
1862 }
1863
1864 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)
1865 {
1866         int success = 0;
1867
1868         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1869
1870         /* Get parties in the bridge */
1871         if (ao2_container_count(bridge->channels) == 1) {
1872                 /* No one in the bridge yet but us! */
1873                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1874                 return BRIDGE_ENTER_ONLY_PARTY;
1875         }
1876
1877         /* If we don't have a Party B (originated channel), skip it */
1878         if (cdr->party_b.snapshot) {
1879                 struct ao2_iterator it_cdrs;
1880                 char *channel_id;
1881
1882                 for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1883                         !success && (channel_id = ao2_iterator_next(&it_cdrs));
1884                         ao2_ref(channel_id, -1)) {
1885                         struct cdr_object *cand_cdr_master;
1886                         struct cdr_object *cand_cdr;
1887
1888                         cand_cdr_master = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
1889                         if (!cand_cdr_master) {
1890                                 continue;
1891                         }
1892
1893                         ao2_lock(cand_cdr_master);
1894                         for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1895                                 /* Skip any records that are not in a bridge or in this bridge.
1896                                  * I'm not sure how that would happen, but it pays to be careful. */
1897                                 if (cand_cdr->fn_table != &bridge_state_fn_table
1898                                         || strcmp(cdr->bridge, cand_cdr->bridge)) {
1899                                         continue;
1900                                 }
1901
1902                                 /* Skip any records that aren't our Party B */
1903                                 if (strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1904                                         continue;
1905                                 }
1906                                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1907                                 /* If they have a Party B, they joined up with someone else as their
1908                                  * Party A. Don't finalize them as they're active. Otherwise, we
1909                                  * have stolen them so they need to be finalized.
1910                                  */
1911                                 if (!cand_cdr->party_b.snapshot) {
1912                                         cdr_object_finalize(cand_cdr);
1913                                 }
1914                                 success = 1;
1915                                 break;
1916                         }
1917                         ao2_unlock(cand_cdr_master);
1918                         ao2_cleanup(cand_cdr_master);
1919                 }
1920                 ao2_iterator_destroy(&it_cdrs);
1921         }
1922
1923         /* We always transition state, even if we didn't get a peer */
1924         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1925
1926         /* Success implies that we have a Party B */
1927         if (success) {
1928                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1929         }
1930         return BRIDGE_ENTER_NO_PARTY_B;
1931 }
1932
1933 /* DIALED PENDING STATE */
1934
1935 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1936 {
1937         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1938          * that means we need a new CDR; otherwise, switch us over to single.
1939          */
1940         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1941                 if (cdr->party_b.snapshot) {
1942                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1943                         cdr->fn_table->process_party_a(cdr, snapshot);
1944                         return 1;
1945                 } else {
1946                         cdr_object_transition_state(cdr, &single_state_fn_table);
1947                         cdr->fn_table->process_party_a(cdr, snapshot);
1948                         return 0;
1949                 }
1950         }
1951         base_process_party_a(cdr, snapshot);
1952         return 0;
1953 }
1954
1955 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)
1956 {
1957         cdr_object_transition_state(cdr, &dial_state_fn_table);
1958         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1959 }
1960
1961 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1962 {
1963         if (cdr->party_b.snapshot) {
1964                 /* We can't handle this as we have a Party B - ask for a new one */
1965                 return 1;
1966         }
1967         cdr_object_transition_state(cdr, &parked_state_fn_table);
1968         return 0;
1969 }
1970
1971 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1972 {
1973         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1974
1975         /* Ask for a new CDR */
1976         return 1;
1977 }
1978
1979 /* BRIDGE STATE */
1980
1981 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1982 {
1983         ast_assert(cdr->party_b.snapshot
1984                 && !strcasecmp(cdr->party_b.snapshot->name, snapshot->name));
1985
1986         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1987
1988         /* If party B hangs up, finalize this CDR */
1989         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1990                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1991         }
1992 }
1993
1994 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1995 {
1996         if (strcmp(cdr->bridge, bridge->uniqueid)) {
1997                 return 1;
1998         }
1999         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)
2000                 && cdr->party_b.snapshot
2001                 && strcasecmp(cdr->party_b.snapshot->name, channel->name)) {
2002                 return 1;
2003         }
2004         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2005
2006         return 0;
2007 }
2008
2009 /* PARKED STATE */
2010
2011 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
2012 {
2013         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)) {
2014                 return 1;
2015         }
2016         cdr_object_transition_state(cdr, &finalized_state_fn_table);
2017
2018         return 0;
2019 }
2020
2021 /* FINALIZED STATE */
2022
2023 static void finalized_state_init_function(struct cdr_object *cdr)
2024 {
2025         cdr_object_finalize(cdr);
2026 }
2027
2028 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
2029 {
2030         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2031                 && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN)) {
2032                 return 0;
2033         }
2034
2035         /* Indicate that, if possible, we should get a new CDR */
2036         return 1;
2037 }
2038
2039 /*!
2040  * \internal
2041  * \brief Filter channel snapshots by technology
2042  */
2043 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
2044 {
2045         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
2046 }
2047
2048 /*!
2049  * \internal
2050  * \brief Filter a channel cache update
2051  */
2052 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
2053                 struct ast_channel_snapshot *new_snapshot)
2054 {
2055         int ret = 0;
2056
2057         /* Drop cache updates from certain channel technologies */
2058         if (old_snapshot) {
2059                 ret |= filter_channel_snapshot(old_snapshot);
2060         }
2061         if (new_snapshot) {
2062                 ret |= filter_channel_snapshot(new_snapshot);
2063         }
2064
2065         return ret;
2066 }
2067
2068 static int dial_status_end(const char *dialstatus)
2069 {
2070         return (strcmp(dialstatus, "RINGING") &&
2071                         strcmp(dialstatus, "PROCEEDING") &&
2072                         strcmp(dialstatus, "PROGRESS"));
2073 }
2074
2075 /* TOPIC ROUTER CALLBACKS */
2076
2077 /*!
2078  * \brief Handler for Stasis-Core dial messages
2079  * \param data Passed on
2080  * \param sub The stasis subscription for this message callback
2081  * \param topic The topic this message was published for
2082  * \param message The message
2083  */
2084 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2085 {
2086         struct cdr_object *cdr;
2087         struct ast_multi_channel_blob *payload = stasis_message_data(message);
2088         struct ast_channel_snapshot *caller;
2089         struct ast_channel_snapshot *peer;
2090         struct cdr_object *it_cdr;
2091         struct ast_json *dial_status_blob;
2092         const char *dial_status = NULL;
2093         int res = 1;
2094
2095         caller = ast_multi_channel_blob_get_channel(payload, "caller");
2096         peer = ast_multi_channel_blob_get_channel(payload, "peer");
2097         if (!peer && !caller) {
2098                 return;
2099         }
2100
2101         if (peer && filter_channel_snapshot(peer)) {
2102                 return;
2103         }
2104
2105         if (caller && filter_channel_snapshot(caller)) {
2106                 return;
2107         }
2108
2109         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
2110         if (dial_status_blob) {
2111                 dial_status = ast_json_string_get(dial_status_blob);
2112         }
2113
2114         CDR_DEBUG("Dial %s message for %s, %s: %u.%08u\n",
2115                 ast_strlen_zero(dial_status) ? "Begin" : "End",
2116                 caller ? caller->name : "(none)",
2117                 peer ? peer->name : "(none)",
2118                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2119                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2120
2121         /* Figure out who is running this show */
2122         if (caller) {
2123                 cdr = ao2_find(active_cdrs_master, caller->uniqueid, OBJ_SEARCH_KEY);
2124         } else {
2125                 cdr = ao2_find(active_cdrs_master, peer->uniqueid, OBJ_SEARCH_KEY);
2126         }
2127         if (!cdr) {
2128                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->name : peer->name);
2129                 ast_assert(0);
2130                 return;
2131         }
2132
2133         ao2_lock(cdr);
2134         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2135                 if (ast_strlen_zero(dial_status)) {
2136                         if (!it_cdr->fn_table->process_dial_begin) {
2137                                 continue;
2138                         }
2139                         CDR_DEBUG("%p - Processing Dial Begin message for channel %s, peer %s\n",
2140                                 it_cdr,
2141                                 caller ? caller->name : "(none)",
2142                                 peer ? peer->name : "(none)");
2143                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
2144                                         caller,
2145                                         peer);
2146                 } else if (dial_status_end(dial_status)) {
2147                         if (!it_cdr->fn_table->process_dial_end) {
2148                                 continue;
2149                         }
2150                         CDR_DEBUG("%p - Processing Dial End message for channel %s, peer %s\n",
2151                                 it_cdr,
2152                                 caller ? caller->name : "(none)",
2153                                 peer ? peer->name : "(none)");
2154                         it_cdr->fn_table->process_dial_end(it_cdr,
2155                                         caller,
2156                                         peer,
2157                                         dial_status);
2158                 }
2159         }
2160
2161         /* If no CDR handled a dial begin message, make a new one */
2162         if (res && ast_strlen_zero(dial_status)) {
2163                 struct cdr_object *new_cdr;
2164
2165                 new_cdr = cdr_object_create_and_append(cdr);
2166                 if (new_cdr) {
2167                         new_cdr->fn_table->process_dial_begin(new_cdr, caller, peer);
2168                 }
2169         }
2170         ao2_unlock(cdr);
2171         ao2_cleanup(cdr);
2172 }
2173
2174 static int cdr_object_finalize_party_b(void *obj, void *arg, void *data, int flags)
2175 {
2176         struct cdr_object *cdr = obj;
2177
2178         if (!strcasecmp(cdr->party_b_name, arg)) {
2179 #ifdef AST_DEVMODE
2180                 struct ast_channel_snapshot *party_b = data;
2181
2182                 /*
2183                  * For sanity's sake we also assert the party_b snapshot
2184                  * is consistent with the key.
2185                  */
2186                 ast_assert(cdr->party_b.snapshot
2187                         && !strcasecmp(cdr->party_b.snapshot->name, party_b->name));
2188 #endif
2189
2190                 /* Don't transition to the finalized state - let the Party A do
2191                  * that when its ready
2192                  */
2193                 cdr_object_finalize(cdr);
2194         }
2195         return 0;
2196 }
2197
2198 static int cdr_object_update_party_b(void *obj, void *arg, void *data, int flags)
2199 {
2200         struct cdr_object *cdr = obj;
2201
2202         if (cdr->fn_table->process_party_b
2203                 && !strcasecmp(cdr->party_b_name, arg)) {
2204                 struct ast_channel_snapshot *party_b = data;
2205
2206                 /*
2207                  * For sanity's sake we also check the party_b snapshot
2208                  * for consistency with the key.  The callback needs and
2209                  * asserts the snapshot to be this way.
2210                  */
2211                 if (!cdr->party_b.snapshot
2212                         || strcasecmp(cdr->party_b.snapshot->name, party_b->name)) {
2213                         ast_log(LOG_NOTICE,
2214                                 "CDR for Party A %s(%s) has inconsistent Party B %s name.  Message can be ignored but this shouldn't happen.\n",
2215                                 cdr->linkedid,
2216                                 cdr->party_a.snapshot->name,
2217                                 cdr->party_b_name);
2218                         return 0;
2219                 }
2220
2221                 cdr->fn_table->process_party_b(cdr, party_b);
2222         }
2223         return 0;
2224 }
2225
2226 /*! \brief Determine if we need to add a new CDR based on snapshots */
2227 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2228                 struct ast_channel_snapshot *new_snapshot)
2229 {
2230         /* If we're dead, we don't need a new CDR */
2231         if (!new_snapshot
2232                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2233                         && is_cdr_flag_set(CDR_END_BEFORE_H_EXTEN))) {
2234                 return 0;
2235         }
2236
2237         /* Auto-fall through will increment the priority but have no application */
2238         if (ast_strlen_zero(new_snapshot->appl)) {
2239                 return 0;
2240         }
2241
2242         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2243                 return 0;
2244         }
2245
2246         return 1;
2247 }
2248
2249 /*!
2250  * \brief Handler for Stasis-Core channel cache update messages
2251  * \param data Passed on
2252  * \param sub The stasis subscription for this message callback
2253  * \param topic The topic this message was published for
2254  * \param message The message
2255  */
2256 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2257 {
2258         struct cdr_object *cdr;
2259         struct stasis_cache_update *update = stasis_message_data(message);
2260         struct ast_channel_snapshot *old_snapshot;
2261         struct ast_channel_snapshot *new_snapshot;
2262         struct cdr_object *it_cdr;
2263
2264         ast_assert(update != NULL);
2265         ast_assert(ast_channel_snapshot_type() == update->type);
2266
2267         old_snapshot = stasis_message_data(update->old_snapshot);
2268         new_snapshot = stasis_message_data(update->new_snapshot);
2269
2270         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
2271                 return;
2272         }
2273
2274         if (new_snapshot && !old_snapshot) {
2275                 cdr = cdr_object_alloc(new_snapshot);
2276                 if (!cdr) {
2277                         return;
2278                 }
2279                 cdr->is_root = 1;
2280                 ao2_link(active_cdrs_master, cdr);
2281         } else {
2282                 const char *uniqueid;
2283
2284                 uniqueid = new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid;
2285                 cdr = ao2_find(active_cdrs_master, uniqueid, OBJ_SEARCH_KEY);
2286         }
2287
2288         /* Handle Party A */
2289         if (!cdr) {
2290                 const char *name;
2291
2292                 name = new_snapshot ? new_snapshot->name : old_snapshot->name;
2293                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
2294                 ast_assert(0);
2295         } else if (new_snapshot) {
2296                 int all_reject = 1;
2297
2298                 ao2_lock(cdr);
2299                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2300                         if (!it_cdr->fn_table->process_party_a) {
2301                                 continue;
2302                         }
2303                         all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
2304                 }
2305                 if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
2306                         /* We're not hung up and we have a new snapshot - we need a new CDR */
2307                         struct cdr_object *new_cdr;
2308
2309                         new_cdr = cdr_object_create_and_append(cdr);
2310                         if (new_cdr) {
2311                                 new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
2312                         }
2313                 }
2314                 ao2_unlock(cdr);
2315         } else {
2316                 ao2_lock(cdr);
2317                 CDR_DEBUG("%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
2318                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2319                         cdr_object_finalize(it_cdr);
2320                 }
2321                 cdr_object_dispatch(cdr);
2322                 ao2_unlock(cdr);
2323
2324                 cdr_all_unlink(cdr);
2325                 ao2_unlink(active_cdrs_master, cdr);
2326         }
2327
2328         /* Handle Party B */
2329         if (new_snapshot) {
2330                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2331                         cdr_object_update_party_b, (char *) new_snapshot->name, new_snapshot);
2332         } else {
2333                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2334                         cdr_object_finalize_party_b, (char *) old_snapshot->name, old_snapshot);
2335         }
2336
2337         ao2_cleanup(cdr);
2338 }
2339
2340 struct bridge_leave_data {
2341         struct ast_bridge_snapshot *bridge;
2342         struct ast_channel_snapshot *channel;
2343 };
2344
2345 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2346 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, void *data, int flags)
2347 {
2348         struct cdr_object *cdr = obj;
2349         struct bridge_leave_data *leave_data = data;
2350
2351         if (cdr->fn_table == &bridge_state_fn_table
2352                 && !strcmp(cdr->bridge, leave_data->bridge->uniqueid)
2353                 && !strcasecmp(cdr->party_b_name, arg)) {
2354                 /*
2355                  * For sanity's sake we also assert the party_b snapshot
2356                  * is consistent with the key.
2357                  */
2358                 ast_assert(cdr->party_b.snapshot
2359                         && !strcasecmp(cdr->party_b.snapshot->name, leave_data->channel->name));
2360
2361                 /* It is our Party B, in our bridge. Set the end time and let the handler
2362                  * transition our CDR appropriately when we leave the bridge.
2363                  */
2364                 cdr_object_finalize(cdr);
2365         }
2366         return 0;
2367 }
2368
2369 /*! \brief Filter bridge messages based on bridge technology */
2370 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2371 {
2372         /* Ignore holding bridge technology messages. We treat this simply as an application
2373          * that a channel enters into.
2374          */
2375         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2376                 return 1;
2377         }
2378         return 0;
2379 }
2380
2381 /*!
2382  * \brief Handler for when a channel leaves a bridge
2383  * \param data Passed on
2384  * \param sub The stasis subscription for this message callback
2385  * \param topic The topic this message was published for
2386  * \param message The message - hopefully a bridge one!
2387  */
2388 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2389                 struct stasis_message *message)
2390 {
2391         struct ast_bridge_blob *update = stasis_message_data(message);
2392         struct ast_bridge_snapshot *bridge = update->bridge;
2393         struct ast_channel_snapshot *channel = update->channel;
2394         struct cdr_object *cdr;
2395         struct cdr_object *it_cdr;
2396         struct bridge_leave_data leave_data = {
2397                 .bridge = bridge,
2398                 .channel = channel,
2399         };
2400         int left_bridge = 0;
2401
2402         if (filter_bridge_messages(bridge)) {
2403                 return;
2404         }
2405
2406         if (filter_channel_snapshot(channel)) {
2407                 return;
2408         }
2409
2410         CDR_DEBUG("Bridge Leave message for %s: %u.%08u\n",
2411                 channel->name,
2412                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2413                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2414
2415         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2416         if (!cdr) {
2417                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2418                 ast_assert(0);
2419                 return;
2420         }
2421
2422         /* Party A */
2423         ao2_lock(cdr);
2424         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2425                 if (!it_cdr->fn_table->process_bridge_leave) {
2426                         continue;
2427                 }
2428                 CDR_DEBUG("%p - Processing Bridge Leave for %s\n",
2429                         it_cdr, channel->name);
2430                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2431                         ast_string_field_set(it_cdr, bridge, "");
2432                         left_bridge = 1;
2433                 }
2434         }
2435         ao2_unlock(cdr);
2436
2437         /* Party B */
2438         if (left_bridge
2439                 && strcmp(bridge->subclass, "parking")) {
2440                 ao2_callback_data(active_cdrs_all, OBJ_NODATA | OBJ_MULTIPLE | OBJ_SEARCH_KEY,
2441                         cdr_object_party_b_left_bridge_cb, (char *) leave_data.channel->name,
2442                         &leave_data);
2443         }
2444
2445         ao2_cleanup(cdr);
2446 }
2447
2448 /*!
2449  * \internal
2450  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2451  *
2452  * \note The new CDR will be automatically transitioned to the bridge state
2453  */
2454 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2455                 struct cdr_object_snapshot *party_b)
2456 {
2457         struct cdr_object *new_cdr;
2458
2459         new_cdr = cdr_object_create_and_append(cdr);
2460         if (!new_cdr) {
2461                 return;
2462         }
2463         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2464         cdr_all_relink(new_cdr);
2465         cdr_object_check_party_a_answer(new_cdr);
2466         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2467         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2468         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2469                 new_cdr, new_cdr->party_a.snapshot->name,
2470                 party_b->snapshot->name);
2471 }
2472
2473 /*!
2474  * \brief Process a single \ref bridge_candidate
2475  *
2476  * When a CDR enters a bridge, it needs to make pairings with everyone else
2477  * that it is not currently paired with. This function determines, for the
2478  * CDR for the channel that entered the bridge and the CDR for every other
2479  * channel currently in the bridge, who is Party A and makes new CDRs.
2480  *
2481  * \param cdr The \ref cdr_obj being processed
2482  * \param cand_cdr The \ref cdr_object that is a candidate
2483  *
2484  */
2485 static void bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2486 {
2487         struct cdr_object_snapshot *party_a;
2488         struct cdr_object *cand_cdr;
2489
2490         ao2_lock(base_cand_cdr);
2491
2492         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2493                 /* Skip any records that are not in this bridge */
2494                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2495                         continue;
2496                 }
2497
2498                 /* If the candidate is us or someone we've taken on, pass on by */
2499                 if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)
2500                         || (cdr->party_b.snapshot
2501                                 && !strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name))) {
2502                         break;
2503                 }
2504
2505                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2506                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2507                  * Party B */
2508                 if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2509                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2510                         break;
2511                 }
2512
2513                 /* We're Party B. Check if we can add ourselves immediately or if we need
2514                  * a new CDR for them (they already have a Party B) */
2515                 if (cand_cdr->party_b.snapshot
2516                         && strcasecmp(cand_cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2517                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2518                 } else {
2519                         CDR_DEBUG("%p - Party A %s has new Party B %s\n",
2520                                 cand_cdr, cand_cdr->party_a.snapshot->name,
2521                                 cdr->party_a.snapshot->name);
2522                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2523                         cdr_all_relink(cand_cdr);
2524                         /* It's possible that this joined at one point and was never chosen
2525                          * as party A. Clear their end time, as it would be set in such a
2526                          * case.
2527                          */
2528                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2529                 }
2530
2531                 break;
2532         }
2533
2534         ao2_unlock(base_cand_cdr);
2535 }
2536
2537 /*!
2538  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2539  * entered a bridge
2540  * \param cdr The \ref cdr_object that just entered the bridge
2541  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2542  */
2543 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2544 {
2545         struct ao2_iterator it_channels;
2546         char *channel_id;
2547
2548         it_channels = ao2_iterator_init(bridge->channels, 0);
2549         while ((channel_id = ao2_iterator_next(&it_channels))) {
2550                 struct cdr_object *cand_cdr;
2551
2552                 cand_cdr = ao2_find(active_cdrs_master, channel_id, OBJ_SEARCH_KEY);
2553                 if (cand_cdr) {
2554                         bridge_candidate_process(cdr, cand_cdr);
2555                         ao2_ref(cand_cdr, -1);
2556                 }
2557
2558                 ao2_ref(channel_id, -1);
2559         }
2560         ao2_iterator_destroy(&it_channels);
2561 }
2562
2563 /*! \brief Handle entering into a parking bridge
2564  * \param cdr The CDR to operate on
2565  * \param bridge The bridge the channel just entered
2566  * \param channel The channel snapshot
2567  */
2568 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2569                 struct ast_bridge_snapshot *bridge,
2570                 struct ast_channel_snapshot *channel)
2571 {
2572         int res = 1;
2573         struct cdr_object *it_cdr;
2574         struct cdr_object *new_cdr;
2575
2576         ao2_lock(cdr);
2577
2578         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2579                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2580                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2581                 }
2582                 if (it_cdr->fn_table->process_party_a) {
2583                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2584                                 channel->name);
2585                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2586                 }
2587         }
2588
2589         if (res) {
2590                 /* No one handled it - we need a new one! */
2591                 new_cdr = cdr_object_create_and_append(cdr);
2592                 if (new_cdr) {
2593                         /* Let the single state transition us to Parked */
2594                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2595                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2596                 }
2597         }
2598         ao2_unlock(cdr);
2599 }
2600
2601 /*! \brief Handle a bridge enter message for a 'normal' bridge
2602  * \param cdr The CDR to operate on
2603  * \param bridge The bridge the channel just entered
2604  * \param channel The channel snapshot
2605  */
2606 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2607                 struct ast_bridge_snapshot *bridge,
2608                 struct ast_channel_snapshot *channel)
2609 {
2610         enum process_bridge_enter_results result;
2611         struct cdr_object *it_cdr;
2612         struct cdr_object *new_cdr;
2613         struct cdr_object *handled_cdr = NULL;
2614
2615         ao2_lock(cdr);
2616
2617 try_again:
2618         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2619                 if (it_cdr->fn_table->process_party_a) {
2620                         CDR_DEBUG("%p - Updating Party A %s snapshot\n", it_cdr,
2621                                 channel->name);
2622                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2623                 }
2624
2625                 /* Notify all states that they have entered a bridge */
2626                 if (it_cdr->fn_table->process_bridge_enter) {
2627                         CDR_DEBUG("%p - Processing bridge enter for %s\n", it_cdr,
2628                                 channel->name);
2629                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2630                         switch (result) {
2631                         case BRIDGE_ENTER_ONLY_PARTY:
2632                                 /* Fall through */
2633                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2634                                 if (!handled_cdr) {
2635                                         handled_cdr = it_cdr;
2636                                 }
2637                                 break;
2638                         case BRIDGE_ENTER_NEED_CDR:
2639                                 /* Pass */
2640                                 break;
2641                         case BRIDGE_ENTER_NO_PARTY_B:
2642                                 /* We didn't win on any - end this CDR. If someone else comes in later
2643                                  * that is Party B to this CDR, it can re-activate this CDR.
2644                                  */
2645                                 if (!handled_cdr) {
2646                                         handled_cdr = it_cdr;
2647                                 }
2648                                 cdr_object_finalize(cdr);
2649                                 break;
2650                         }
2651                 }
2652         }
2653
2654         /* Create the new matchings, but only for either:
2655          *  * The first CDR in the chain that handled it. This avoids issues with
2656          *    forked CDRs.
2657          *  * If no one handled it, the last CDR in the chain. This would occur if
2658          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2659          *    to make pairings with everyone in the bridge.
2660          */
2661         if (handled_cdr) {
2662                 handle_bridge_pairings(handled_cdr, bridge);
2663         } else {
2664                 /* Nothing handled it - we need a new one! */
2665                 new_cdr = cdr_object_create_and_append(cdr);
2666                 if (new_cdr) {
2667                         /* This is guaranteed to succeed: the new CDR is created in the single state
2668                          * and will be able to handle the bridge enter message
2669                          */
2670                         goto try_again;
2671                 }
2672         }
2673         ao2_unlock(cdr);
2674 }
2675
2676 /*!
2677  * \internal
2678  * \brief Handler for Stasis-Core bridge enter messages
2679  * \param data Passed on
2680  * \param sub The stasis subscription for this message callback
2681  * \param topic The topic this message was published for
2682  * \param message The message - hopefully a bridge one!
2683  */
2684 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2685                 struct stasis_message *message)
2686 {
2687         struct ast_bridge_blob *update = stasis_message_data(message);
2688         struct ast_bridge_snapshot *bridge = update->bridge;
2689         struct ast_channel_snapshot *channel = update->channel;
2690         struct cdr_object *cdr;
2691
2692         if (filter_bridge_messages(bridge)) {
2693                 return;
2694         }
2695
2696         if (filter_channel_snapshot(channel)) {
2697                 return;
2698         }
2699
2700         CDR_DEBUG("Bridge Enter message for channel %s: %u.%08u\n",
2701                 channel->name,
2702                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2703                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2704
2705         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2706         if (!cdr) {
2707                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2708                 ast_assert(0);
2709                 return;
2710         }
2711
2712         if (!strcmp(bridge->subclass, "parking")) {
2713                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2714         } else {
2715                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2716         }
2717         ao2_cleanup(cdr);
2718 }
2719
2720 /*!
2721  * \brief Handler for when a channel is parked
2722  * \param data Passed on
2723  * \param sub The stasis subscription for this message callback
2724  * \param topic The topic this message was published for
2725  * \param message The message about who got parked
2726  * */
2727 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2728                 struct stasis_message *message)
2729 {
2730         struct ast_parked_call_payload *payload = stasis_message_data(message);
2731         struct ast_channel_snapshot *channel = payload->parkee;
2732         struct cdr_object *cdr;
2733         int unhandled = 1;
2734         struct cdr_object *it_cdr;
2735
2736         /* Anything other than getting parked will be handled by other updates */
2737         if (payload->event_type != PARKED_CALL) {
2738                 return;
2739         }
2740
2741         /* No one got parked? */
2742         if (!channel) {
2743                 return;
2744         }
2745
2746         if (filter_channel_snapshot(channel)) {
2747                 return;
2748         }
2749
2750         CDR_DEBUG("Parked Call message for channel %s: %u.%08u\n",
2751                 channel->name,
2752                 (unsigned int)stasis_message_timestamp(message)->tv_sec,
2753                 (unsigned int)stasis_message_timestamp(message)->tv_usec);
2754
2755         cdr = ao2_find(active_cdrs_master, channel->uniqueid, OBJ_SEARCH_KEY);
2756         if (!cdr) {
2757                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2758                 ast_assert(0);
2759                 return;
2760         }
2761
2762         ao2_lock(cdr);
2763
2764         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2765                 if (it_cdr->fn_table->process_parked_channel) {
2766                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2767                 }
2768         }
2769
2770         if (unhandled) {
2771                 /* Nothing handled the messgae - we need a new one! */
2772                 struct cdr_object *new_cdr;
2773
2774                 new_cdr = cdr_object_create_and_append(cdr);
2775                 if (new_cdr) {
2776                         /* As the new CDR is created in the single state, it is guaranteed
2777                          * to have a function for the parked call message and will handle
2778                          * the message */
2779                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2780                 }
2781         }
2782
2783         ao2_unlock(cdr);
2784
2785         ao2_cleanup(cdr);
2786 }
2787
2788 /*!
2789  * \brief Handler for a synchronization message
2790  * \param data Passed on
2791  * \param sub The stasis subscription for this message callback
2792  * \param topic The topic this message was published for
2793  * \param message A blank ao2 object
2794  * */
2795 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2796                 struct stasis_message *message)
2797 {
2798         return;
2799 }
2800
2801 struct ast_cdr_config *ast_cdr_get_config(void)
2802 {
2803         struct ast_cdr_config *general;
2804         struct module_config *mod_cfg;
2805
2806         mod_cfg = ao2_global_obj_ref(module_configs);
2807         if (!mod_cfg) {
2808                 return NULL;
2809         }
2810         general = ao2_bump(mod_cfg->general);
2811         ao2_cleanup(mod_cfg);
2812         return general;
2813 }
2814
2815 void ast_cdr_set_config(struct ast_cdr_config *config)
2816 {
2817         struct module_config *mod_cfg;
2818
2819         if (!config) {
2820                 return;
2821         }
2822
2823         mod_cfg = ao2_global_obj_ref(module_configs);
2824         if (!mod_cfg) {
2825                 return;
2826         }
2827
2828         ao2_replace(mod_cfg->general, config);
2829
2830         cdr_set_debug_mode(mod_cfg);
2831         cdr_toggle_runtime_options();
2832
2833         ao2_cleanup(mod_cfg);
2834 }
2835
2836 int ast_cdr_is_enabled(void)
2837 {
2838         return is_cdr_flag_set(CDR_ENABLED);
2839 }
2840
2841 int ast_cdr_backend_suspend(const char *name)
2842 {
2843         int success = -1;
2844         struct cdr_beitem *i = NULL;
2845
2846         AST_RWLIST_WRLOCK(&be_list);
2847         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2848                 if (!strcasecmp(name, i->name)) {
2849                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2850                         i->suspended = 1;
2851                         success = 0;
2852                 }
2853         }
2854         AST_RWLIST_UNLOCK(&be_list);
2855
2856         return success;
2857 }
2858
2859 int ast_cdr_backend_unsuspend(const char *name)
2860 {
2861         int success = -1;
2862         struct cdr_beitem *i = NULL;
2863
2864         AST_RWLIST_WRLOCK(&be_list);
2865         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2866                 if (!strcasecmp(name, i->name)) {
2867                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2868                         i->suspended = 0;
2869                         success = 0;
2870                 }
2871         }
2872         AST_RWLIST_UNLOCK(&be_list);
2873
2874         return success;
2875 }
2876
2877 static int cdr_generic_register(struct be_list *generic_list, const char *name, const char *desc, ast_cdrbe be)
2878 {
2879         struct cdr_beitem *i;
2880         struct cdr_beitem *cur;
2881
2882         if (!name) {
2883                 return -1;
2884         }
2885
2886         if (!be) {
2887                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2888
2889                 return -1;
2890         }
2891
2892         i = ast_calloc(1, sizeof(*i));
2893         if (!i) {
2894                 return -1;
2895         }
2896
2897         i->be = be;
2898         ast_copy_string(i->name, name, sizeof(i->name));
2899         ast_copy_string(i->desc, desc, sizeof(i->desc));
2900
2901         AST_RWLIST_WRLOCK(generic_list);
2902         AST_RWLIST_TRAVERSE(generic_list, cur, list) {
2903                 if (!strcasecmp(name, cur->name)) {
2904                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2905                         AST_RWLIST_UNLOCK(generic_list);
2906                         ast_free(i);
2907
2908                         return -1;
2909                 }
2910         }
2911
2912         AST_RWLIST_INSERT_HEAD(generic_list, i, list);
2913         AST_RWLIST_UNLOCK(generic_list);
2914
2915         return 0;
2916 }
2917
2918 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2919 {
2920         return cdr_generic_register(&be_list, name, desc, be);
2921 }
2922
2923 int ast_cdr_modifier_register(const char *name, const char *desc, ast_cdrbe be)
2924 {
2925         return cdr_generic_register((struct be_list *)&mo_list, name, desc, be);
2926 }
2927
2928 static int ast_cdr_generic_unregister(struct be_list *generic_list, const char *name)
2929 {
2930         struct cdr_beitem *match = NULL;
2931         int active_count;
2932
2933         AST_RWLIST_WRLOCK(generic_list);
2934         AST_RWLIST_TRAVERSE(generic_list, match, list) {
2935                 if (!strcasecmp(name, match->name)) {
2936                         break;
2937                 }
2938         }
2939
2940         if (!match) {
2941                 AST_RWLIST_UNLOCK(generic_list);
2942                 return 0;
2943         }
2944
2945         active_count = ao2_container_count(active_cdrs_master);
2946
2947         if (!match->suspended && active_count != 0) {
2948                 AST_RWLIST_UNLOCK(generic_list);
2949                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2950                         name, active_count);
2951                 return -1;
2952         }
2953
2954         AST_RWLIST_REMOVE(generic_list, match, list);
2955         AST_RWLIST_UNLOCK(generic_list);
2956
2957         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2958         ast_free(match);
2959
2960         return 0;
2961 }
2962
2963 int ast_cdr_unregister(const char *name)
2964 {
2965         return ast_cdr_generic_unregister(&be_list, name);
2966 }
2967
2968 int ast_cdr_modifier_unregister(const char *name)
2969 {
2970         return ast_cdr_generic_unregister((struct be_list *)&mo_list, name);
2971 }
2972
2973 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2974 {
2975         struct ast_cdr *newcdr;
2976
2977         if (!cdr) {
2978                 return NULL;
2979         }
2980         newcdr = ast_cdr_alloc();
2981         if (!newcdr) {
2982                 return NULL;
2983         }
2984
2985         *newcdr = *cdr;
2986         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2987         copy_variables(&newcdr->varshead, &cdr->varshead);
2988         newcdr->next = NULL;
2989
2990         return newcdr;
2991 }
2992
2993 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
2994 {
2995         struct ast_var_t *variables;
2996
2997         if (ast_strlen_zero(name)) {
2998                 return NULL;
2999         }
3000
3001         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
3002                 if (!strcasecmp(name, ast_var_name(variables))) {
3003                         return ast_var_value(variables);
3004                 }
3005         }
3006
3007         return NULL;
3008 }
3009
3010 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
3011 {
3012         if (fmt == NULL) {      /* raw mode */
3013                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
3014         } else {
3015                 buf[0] = '\0';/* Ensure the buffer is initialized. */
3016                 if (when.tv_sec) {
3017                         struct ast_tm tm;
3018
3019                         ast_localtime(&when, &tm, NULL);
3020                         ast_strftime(buf, bufsize, fmt, &tm);
3021                 }
3022         }
3023 }
3024
3025 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
3026 {
3027         const char *fmt = "%Y-%m-%d %T";
3028         const char *varbuf;
3029
3030         if (!cdr) {
3031                 return;
3032         }
3033
3034         *ret = NULL;
3035
3036         if (!strcasecmp(name, "clid")) {
3037                 ast_copy_string(workspace, cdr->clid, workspacelen);
3038         } else if (!strcasecmp(name, "src")) {
3039                 ast_copy_string(workspace, cdr->src, workspacelen);
3040         } else if (!strcasecmp(name, "dst")) {
3041                 ast_copy_string(workspace, cdr->dst, workspacelen);
3042         } else if (!strcasecmp(name, "dcontext")) {
3043                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
3044         } else if (!strcasecmp(name, "channel")) {
3045                 ast_copy_string(workspace, cdr->channel, workspacelen);
3046         } else if (!strcasecmp(name, "dstchannel")) {
3047                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
3048         } else if (!strcasecmp(name, "lastapp")) {
3049                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
3050         } else if (!strcasecmp(name, "lastdata")) {
3051                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
3052         } else if (!strcasecmp(name, "start")) {
3053                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
3054         } else if (!strcasecmp(name, "answer")) {
3055                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
3056         } else if (!strcasecmp(name, "end")) {
3057                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
3058         } else if (!strcasecmp(name, "duration")) {
3059                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
3060         } else if (!strcasecmp(name, "billsec")) {
3061                 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);
3062         } else if (!strcasecmp(name, "disposition")) {
3063                 if (raw) {
3064                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
3065                 } else {
3066                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
3067                 }
3068         } else if (!strcasecmp(name, "amaflags")) {
3069                 if (raw) {
3070                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
3071                 } else {
3072                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
3073                 }
3074         } else if (!strcasecmp(name, "accountcode")) {
3075                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
3076         } else if (!strcasecmp(name, "peeraccount")) {
3077                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
3078         } else if (!strcasecmp(name, "uniqueid")) {
3079                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
3080         } else if (!strcasecmp(name, "linkedid")) {
3081                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
3082         } else if (!strcasecmp(name, "userfield")) {
3083                 ast_copy_string(workspace, cdr->userfield, workspacelen);
3084         } else if (!strcasecmp(name, "sequence")) {
3085                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
3086         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
3087                 ast_copy_string(workspace, varbuf, workspacelen);
3088         } else {
3089                 workspace[0] = '\0';
3090         }
3091
3092         if (!ast_strlen_zero(workspace)) {
3093                 *ret = workspace;
3094         }
3095 }
3096
3097 /*!
3098  * \internal
3099  * \brief Callback that finds all CDRs that reference a particular channel by name
3100  */
3101 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
3102 {
3103         struct cdr_object *cdr = obj;
3104         const char *name = arg;
3105
3106         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
3107                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
3108                 return CMP_MATCH;
3109         }
3110         return 0;
3111 }
3112
3113 /*!
3114  * \internal
3115  * \brief Callback that finds a CDR by channel name
3116  */
3117 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
3118 {
3119         struct cdr_object *cdr = obj;
3120         const char *name = arg;
3121
3122         if (!strcasecmp(cdr->party_a.snapshot->name, name)) {
3123                 return CMP_MATCH;
3124         }
3125         return 0;
3126 }
3127
3128 /* Read Only CDR variables */
3129 static const char * const cdr_readonly_vars[] = {
3130         "clid",
3131         "src",
3132         "dst",
3133         "dcontext",
3134         "channel",
3135         "dstchannel",
3136         "lastapp",
3137         "lastdata",
3138         "start",
3139         "answer",
3140         "end",
3141         "duration",
3142         "billsec",
3143         "disposition",
3144         "amaflags",
3145         "accountcode",
3146         "uniqueid",
3147         "linkedid",
3148         "userfield",
3149         "sequence",
3150         NULL
3151 };
3152
3153 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
3154 {
3155         struct cdr_object *cdr;
3156         struct cdr_object *it_cdr;
3157         struct ao2_iterator *it_cdrs;
3158         char *arg = ast_strdupa(channel_name);
3159         int x;
3160
3161         for (x = 0; cdr_readonly_vars[x]; x++) {
3162                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
3163                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
3164                         return -1;
3165                 }
3166         }
3167
3168         it_cdrs = ao2_callback(active_cdrs_master, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
3169         if (!it_cdrs) {
3170                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3171                 return -1;
3172         }
3173
3174         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
3175                 ao2_lock(cdr);
3176                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3177                         struct varshead *headp = NULL;
3178
3179                         if (it_cdr->fn_table == &finalized_state_fn_table && it_cdr->next != NULL) {
3180                                 continue;
3181                         }
3182                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->name)) {
3183                                 headp = &it_cdr->party_a.variables;
3184                         } else if (it_cdr->party_b.snapshot
3185                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->name)) {
3186                                 headp = &it_cdr->party_b.variables;
3187                         }
3188                         if (headp) {
3189                                 set_variable(headp, name, value);
3190                         }
3191                 }
3192         }
3193         ao2_iterator_destroy(it_cdrs);
3194
3195         return 0;
3196 }
3197
3198 /*!
3199  * \brief Format a variable on a \ref cdr_object
3200  */
3201 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
3202 {
3203         struct ast_var_t *variable;
3204
3205         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
3206                 if (!strcasecmp(name, ast_var_name(variable))) {
3207                         ast_copy_string(value, ast_var_value(variable), length);
3208                         return;
3209                 }
3210         }
3211
3212         *value = '\0';
3213 }
3214
3215 /*!
3216  * \brief Format one of the standard properties on a \ref cdr_object
3217  */
3218 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
3219 {
3220         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
3221         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
3222
3223         if (!strcasecmp(name, "clid")) {
3224                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
3225         } else if (!strcasecmp(name, "src")) {
3226                 ast_copy_string(value, party_a->caller_number, length);
3227         } else if (!strcasecmp(name, "dst")) {
3228                 ast_copy_string(value, party_a->exten, length);
3229         } else if (!strcasecmp(name, "dcontext")) {
3230                 ast_copy_string(value, party_a->context, length);
3231         } else if (!strcasecmp(name, "channel")) {
3232                 ast_copy_string(value, party_a->name, length);
3233         } else if (!strcasecmp(name, "dstchannel")) {
3234                 if (party_b) {
3235                         ast_copy_string(value, party_b->name, length);
3236                 } else {
3237                         ast_copy_string(value, "", length);
3238                 }
3239         } else if (!strcasecmp(name, "lastapp")) {
3240                 ast_copy_string(value, party_a->appl, length);
3241         } else if (!strcasecmp(name, "lastdata")) {
3242                 ast_copy_string(value, party_a->data, length);
3243         } else if (!strcasecmp(name, "start")) {
3244                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3245         } else if (!strcasecmp(name, "answer")) {
3246                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3247         } else if (!strcasecmp(name, "end")) {
3248                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3249         } else if (!strcasecmp(name, "duration")) {
3250                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3251         } else if (!strcasecmp(name, "billsec")) {
3252                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3253         } else if (!strcasecmp(name, "disposition")) {
3254                 snprintf(value, length, "%u", cdr_obj->disposition);
3255         } else if (!strcasecmp(name, "amaflags")) {
3256                 snprintf(value, length, "%d", party_a->amaflags);
3257         } else if (!strcasecmp(name, "accountcode")) {
3258                 ast_copy_string(value, party_a->accountcode, length);
3259         } else if (!strcasecmp(name, "peeraccount")) {
3260                 if (party_b) {
3261                         ast_copy_string(value, party_b->accountcode, length);
3262                 } else {
3263                         ast_copy_string(value, "", length);
3264                 }
3265         } else if (!strcasecmp(name, "uniqueid")) {
3266                 ast_copy_string(value, party_a->uniqueid, length);
3267         } else if (!strcasecmp(name, "linkedid")) {
3268                 ast_copy_string(value, cdr_obj->linkedid, length);
3269         } else if (!strcasecmp(name, "userfield")) {
3270                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3271         } else if (!strcasecmp(name, "sequence")) {
3272                 snprintf(value, length, "%u", cdr_obj->sequence);
3273         } else {
3274                 return 1;
3275         }
3276
3277         return 0;
3278 }
3279
3280 /*! \internal
3281  * \brief Look up and retrieve a CDR object by channel name
3282  * \param name The name of the channel
3283  * \retval NULL on error
3284  * \retval The \ref cdr_object for the channel on success, with the reference
3285  *      count bumped by one.
3286  */
3287 static struct cdr_object *cdr_object_get_by_name(const char *name)
3288 {
3289         char *param;
3290
3291         if (ast_strlen_zero(name)) {
3292                 return NULL;
3293         }
3294
3295         param = ast_strdupa(name);
3296         return ao2_callback(active_cdrs_master, 0, cdr_object_get_by_name_cb, param);
3297 }
3298
3299 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3300 {
3301         struct cdr_object *cdr;
3302         struct cdr_object *cdr_obj;
3303
3304         if (ast_strlen_zero(name)) {
3305                 return 1;
3306         }
3307
3308         cdr = cdr_object_get_by_name(channel_name);
3309         if (!cdr) {
3310                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3311                 return 1;
3312         }
3313
3314         ao2_lock(cdr);
3315
3316         cdr_obj = cdr->last;
3317         if (cdr_object_format_property(cdr_obj, name, value, length)) {
3318                 /* Property failed; attempt variable */
3319                 cdr_object_format_var_internal(cdr_obj, name, value, length);