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