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