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