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