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