8d7f53f174639b7e1db5c29f3bb7e555d309a27a
[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         /*
919          * If the current CDR says to disable all future ones,
920          * keep the disable chain going
921          */
922         if (ast_test_flag(&cdr_last->flags, AST_CDR_FLAG_DISABLE_ALL)) {
923                 ast_set_flag(&new_cdr->flags, AST_CDR_FLAG_DISABLE_ALL);
924         }
925
926         /* Copy over other Party A information */
927         cdr_object_snapshot_copy(&new_cdr->party_a, &cdr_last->party_a);
928
929         /* Append the CDR to the end of the list */
930         for (it_cdr = cdr; it_cdr->next; it_cdr = it_cdr->next) {
931                 it_cdr->last = new_cdr;
932         }
933         it_cdr->last = new_cdr;
934         it_cdr->next = new_cdr;
935
936         return new_cdr;
937 }
938
939 /*!
940  * \brief Return whether or not a channel has changed its state in the dialplan, subject
941  * to endbeforehexten logic
942  *
943  * \param old_snapshot The previous state
944  * \param new_snapshot The new state
945  *
946  * \retval 0 if the state has not changed
947  * \retval 1 if the state changed
948  */
949 static int snapshot_cep_changed(struct ast_channel_snapshot *old_snapshot,
950         struct ast_channel_snapshot *new_snapshot)
951 {
952         RAII_VAR(struct module_config *, mod_cfg,
953                 ao2_global_obj_ref(module_configs), ao2_cleanup);
954
955         /* If we ignore hangup logic, don't indicate that we're executing anything new */
956         if (ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)
957                 && ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
958                 return 0;
959         }
960
961         /* When Party A is originated to an application and the application exits, the stack
962          * will attempt to clear the application and restore the dummy originate application
963          * of "AppDialX". Ignore application changes to AppDialX as a result.
964          */
965         if (strcmp(new_snapshot->appl, old_snapshot->appl) && strncasecmp(new_snapshot->appl, "appdial", 7)
966                 && (strcmp(new_snapshot->context, old_snapshot->context)
967                 || strcmp(new_snapshot->exten, old_snapshot->exten)
968                 || new_snapshot->priority != old_snapshot->priority)) {
969                 return 1;
970         }
971
972         return 0;
973 }
974
975 /*!
976  * \brief Return whether or not a \ref ast_channel_snapshot is for a channel
977  * that was created as the result of a dial operation
978  *
979  * \retval 0 the channel was not created as the result of a dial
980  * \retval 1 the channel was created as the result of a dial
981  */
982 static int snapshot_is_dialed(struct ast_channel_snapshot *snapshot)
983 {
984         return (ast_test_flag(&snapshot->flags, AST_FLAG_OUTGOING)
985                         && !(ast_test_flag(&snapshot->flags, AST_FLAG_ORIGINATED)));
986 }
987
988 /*!
989  * \brief Given two CDR snapshots, figure out who should be Party A for the
990  * resulting CDR
991  * \param left One of the snapshots
992  * \param right The other snapshot
993  * \retval The snapshot that won
994  */
995 static struct cdr_object_snapshot *cdr_object_pick_party_a(struct cdr_object_snapshot *left, struct cdr_object_snapshot *right)
996 {
997         /* Check whether or not the party is dialed. A dialed party is never the
998          * Party A with a party that was not dialed.
999          */
1000         if (!snapshot_is_dialed(left->snapshot) && snapshot_is_dialed(right->snapshot)) {
1001                 return left;
1002         } else if (snapshot_is_dialed(left->snapshot) && !snapshot_is_dialed(right->snapshot)) {
1003                 return right;
1004         }
1005
1006         /* Try the Party A flag */
1007         if (ast_test_flag(left, AST_CDR_FLAG_PARTY_A) && !ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1008                 return left;
1009         } else if (!ast_test_flag(right, AST_CDR_FLAG_PARTY_A) && ast_test_flag(right, AST_CDR_FLAG_PARTY_A)) {
1010                 return right;
1011         }
1012
1013         /* Neither party is dialed and neither has the Party A flag - defer to
1014          * creation time */
1015         if (left->snapshot->creationtime.tv_sec < right->snapshot->creationtime.tv_sec) {
1016                 return left;
1017         } else if (left->snapshot->creationtime.tv_sec > right->snapshot->creationtime.tv_sec) {
1018                 return right;
1019         } else if (left->snapshot->creationtime.tv_usec > right->snapshot->creationtime.tv_usec) {
1020                 return right;
1021         } else {
1022                 /* Okay, fine, take the left one */
1023                 return left;
1024         }
1025 }
1026
1027 /*!
1028  * Compute the duration for a \ref cdr_object
1029  */
1030 static long cdr_object_get_duration(struct cdr_object *cdr)
1031 {
1032         return (long)(ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->start) / 1000);
1033 }
1034
1035 /*!
1036  * \brief Compute the billsec for a \ref cdr_object
1037  */
1038 static long cdr_object_get_billsec(struct cdr_object *cdr)
1039 {
1040         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1041         long int ms;
1042
1043         if (ast_tvzero(cdr->answer)) {
1044                 return 0;
1045         }
1046         ms = ast_tvdiff_ms(ast_tvzero(cdr->end) ? ast_tvnow() : cdr->end, cdr->answer);
1047         if (ast_test_flag(&mod_cfg->general->settings, CDR_INITIATED_SECONDS)
1048                 && (ms % 1000 >= 500)) {
1049                 ms = (ms / 1000) + 1;
1050         } else {
1051                 ms = ms / 1000;
1052         }
1053
1054         return ms;
1055 }
1056
1057 /*!
1058  * \internal
1059  * \brief Set a variable on a CDR object
1060  *
1061  * \param headp The header pointer to the variable to set
1062  * \param name The name of the variable
1063  * \param value The value of the variable
1064  */
1065 static void set_variable(struct varshead *headp, const char *name, const char *value)
1066 {
1067         struct ast_var_t *newvariable;
1068
1069         AST_LIST_TRAVERSE_SAFE_BEGIN(headp, newvariable, entries) {
1070                 if (!strcasecmp(ast_var_name(newvariable), name)) {
1071                         AST_LIST_REMOVE_CURRENT(entries);
1072                         ast_var_delete(newvariable);
1073                         break;
1074                 }
1075         }
1076         AST_LIST_TRAVERSE_SAFE_END;
1077
1078         if (value && (newvariable = ast_var_assign(name, value))) {
1079                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
1080         }
1081 }
1082
1083 /*!
1084  * \brief Create a chain of \ref ast_cdr objects from a chain of \ref cdr_object
1085  * suitable for consumption by the registered CDR backends
1086  * \param cdr The \ref cdr_object to convert to a public record
1087  * \retval A chain of \ref ast_cdr objects on success
1088  * \retval NULL on failure
1089  */
1090 static struct ast_cdr *cdr_object_create_public_records(struct cdr_object *cdr)
1091 {
1092         struct ast_cdr *pub_cdr = NULL, *cdr_prev = NULL;
1093         struct cdr_object *it_cdr;
1094         struct ast_var_t *it_var, *it_copy_var;
1095         struct ast_channel_snapshot *party_a;
1096         struct ast_channel_snapshot *party_b;
1097
1098         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1099                 struct ast_cdr *cdr_copy;
1100
1101                 /* Don't create records for CDRs where the party A was a dialed channel */
1102                 if (snapshot_is_dialed(it_cdr->party_a.snapshot) && !it_cdr->party_b.snapshot) {
1103                         ast_debug(1, "CDR for %s is dialed and has no Party B; discarding\n",
1104                                 it_cdr->party_a.snapshot->name);
1105                         continue;
1106                 }
1107
1108                 cdr_copy = ast_calloc(1, sizeof(*cdr_copy));
1109                 if (!cdr_copy) {
1110                         ast_free(pub_cdr);
1111                         return NULL;
1112                 }
1113
1114                 party_a = it_cdr->party_a.snapshot;
1115                 party_b = it_cdr->party_b.snapshot;
1116
1117                 /* Party A */
1118                 ast_assert(party_a != NULL);
1119                 ast_copy_string(cdr_copy->accountcode, party_a->accountcode, sizeof(cdr_copy->accountcode));
1120                 cdr_copy->amaflags = party_a->amaflags;
1121                 ast_copy_string(cdr_copy->channel, party_a->name, sizeof(cdr_copy->channel));
1122                 ast_callerid_merge(cdr_copy->clid, sizeof(cdr_copy->clid), party_a->caller_name, party_a->caller_number, "");
1123                 ast_copy_string(cdr_copy->src, party_a->caller_number, sizeof(cdr_copy->src));
1124                 ast_copy_string(cdr_copy->uniqueid, party_a->uniqueid, sizeof(cdr_copy->uniqueid));
1125                 ast_copy_string(cdr_copy->lastapp, it_cdr->appl, sizeof(cdr_copy->lastapp));
1126                 ast_copy_string(cdr_copy->lastdata, it_cdr->data, sizeof(cdr_copy->lastdata));
1127                 ast_copy_string(cdr_copy->dst, it_cdr->exten, sizeof(cdr_copy->dst));
1128                 ast_copy_string(cdr_copy->dcontext, it_cdr->context, sizeof(cdr_copy->dcontext));
1129
1130                 /* Party B */
1131                 if (party_b) {
1132                         ast_copy_string(cdr_copy->dstchannel, party_b->name, sizeof(cdr_copy->dstchannel));
1133                         ast_copy_string(cdr_copy->peeraccount, party_b->accountcode, sizeof(cdr_copy->peeraccount));
1134                         if (!ast_strlen_zero(it_cdr->party_b.userfield)) {
1135                                 snprintf(cdr_copy->userfield, sizeof(cdr_copy->userfield), "%s;%s", it_cdr->party_a.userfield, it_cdr->party_b.userfield);
1136                         }
1137                 }
1138                 if (ast_strlen_zero(cdr_copy->userfield) && !ast_strlen_zero(it_cdr->party_a.userfield)) {
1139                         ast_copy_string(cdr_copy->userfield, it_cdr->party_a.userfield, sizeof(cdr_copy->userfield));
1140                 }
1141
1142                 /* Timestamps/durations */
1143                 cdr_copy->start = it_cdr->start;
1144                 cdr_copy->answer = it_cdr->answer;
1145                 cdr_copy->end = it_cdr->end;
1146                 cdr_copy->billsec = cdr_object_get_billsec(it_cdr);
1147                 cdr_copy->duration = cdr_object_get_duration(it_cdr);
1148
1149                 /* Flags and IDs */
1150                 ast_copy_flags(cdr_copy, &it_cdr->flags, AST_FLAGS_ALL);
1151                 ast_copy_string(cdr_copy->linkedid, it_cdr->linkedid, sizeof(cdr_copy->linkedid));
1152                 cdr_copy->disposition = it_cdr->disposition;
1153                 cdr_copy->sequence = it_cdr->sequence;
1154
1155                 /* Variables */
1156                 copy_variables(&cdr_copy->varshead, &it_cdr->party_a.variables);
1157                 AST_LIST_TRAVERSE(&it_cdr->party_b.variables, it_var, entries) {
1158                         int found = 0;
1159                         struct ast_var_t *newvariable;
1160                         AST_LIST_TRAVERSE(&cdr_copy->varshead, it_copy_var, entries) {
1161                                 if (!strcasecmp(ast_var_name(it_var), ast_var_name(it_copy_var))) {
1162                                         found = 1;
1163                                         break;
1164                                 }
1165                         }
1166                         if (!found && (newvariable = ast_var_assign(ast_var_name(it_var), ast_var_value(it_var)))) {
1167                                 AST_LIST_INSERT_TAIL(&cdr_copy->varshead, newvariable, entries);
1168                         }
1169                 }
1170
1171                 if (!pub_cdr) {
1172                         pub_cdr = cdr_copy;
1173                         cdr_prev = pub_cdr;
1174                 } else {
1175                         cdr_prev->next = cdr_copy;
1176                         cdr_prev = cdr_copy;
1177                 }
1178         }
1179
1180         return pub_cdr;
1181 }
1182
1183 /*!
1184  * \brief Dispatch a CDR.
1185  * \param cdr The \ref cdr_object to dispatch
1186  *
1187  * This will create a \ref ast_cdr object and publish it to the various backends
1188  */
1189 static void cdr_object_dispatch(struct cdr_object *cdr)
1190 {
1191         RAII_VAR(struct module_config *, mod_cfg,
1192                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1193         struct ast_cdr *pub_cdr;
1194
1195         CDR_DEBUG(mod_cfg, "%p - Dispatching CDR for Party A %s, Party B %s\n", cdr,
1196                         cdr->party_a.snapshot->name,
1197                         cdr->party_b.snapshot ? cdr->party_b.snapshot->name : "<none>");
1198         pub_cdr = cdr_object_create_public_records(cdr);
1199         cdr_detach(pub_cdr);
1200 }
1201
1202 /*!
1203  * \brief Set the disposition on a \ref cdr_object based on a hangupcause code
1204  * \param cdr The \ref cdr_object
1205  * \param hangupcause The Asterisk hangup cause code
1206  */
1207 static void cdr_object_set_disposition(struct cdr_object *cdr, int hangupcause)
1208 {
1209         RAII_VAR(struct module_config *, mod_cfg,
1210                         ao2_global_obj_ref(module_configs), ao2_cleanup);
1211
1212         /* Change the disposition based on the hang up cause */
1213         switch (hangupcause) {
1214         case AST_CAUSE_BUSY:
1215                 cdr->disposition = AST_CDR_BUSY;
1216                 break;
1217         case AST_CAUSE_CONGESTION:
1218                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION)) {
1219                         cdr->disposition = AST_CDR_FAILED;
1220                 } else {
1221                         cdr->disposition = AST_CDR_CONGESTION;
1222                 }
1223                 break;
1224         case AST_CAUSE_NO_ROUTE_DESTINATION:
1225         case AST_CAUSE_UNREGISTERED:
1226                 cdr->disposition = AST_CDR_FAILED;
1227                 break;
1228         case AST_CAUSE_NORMAL_CLEARING:
1229         case AST_CAUSE_NO_ANSWER:
1230                 cdr->disposition = AST_CDR_NOANSWER;
1231                 break;
1232         default:
1233                 break;
1234         }
1235 }
1236
1237 /*!
1238  * \brief Finalize a CDR.
1239  *
1240  * This function is safe to call multiple times. Note that you can call this
1241  * explicitly before going to the finalized state if there's a chance the CDR
1242  * will be re-activated, in which case the \ref cdr_object's end time should be
1243  * cleared. This function is implicitly called when a CDR transitions to the
1244  * finalized state and right before it is dispatched
1245  *
1246  * \param cdr_object The CDR to finalize
1247  */
1248 static void cdr_object_finalize(struct cdr_object *cdr)
1249 {
1250         if (!ast_tvzero(cdr->end)) {
1251                 return;
1252         }
1253         cdr->end = ast_tvnow();
1254
1255         if (cdr->disposition == AST_CDR_NULL) {
1256                 if (!ast_tvzero(cdr->answer)) {
1257                         cdr->disposition = AST_CDR_ANSWERED;
1258                 } else if (cdr->party_a.snapshot->hangupcause) {
1259                         cdr_object_set_disposition(cdr, cdr->party_a.snapshot->hangupcause);
1260                 } else if (cdr->party_b.snapshot && cdr->party_b.snapshot->hangupcause) {
1261                         cdr_object_set_disposition(cdr, cdr->party_b.snapshot->hangupcause);
1262                 } else {
1263                         cdr->disposition = AST_CDR_FAILED;
1264                 }
1265         }
1266
1267         /* tv_usec is suseconds_t, which could be int or long */
1268         ast_debug(1, "Finalized CDR for %s - start %ld.%06ld answer %ld.%06ld end %ld.%06ld dispo %s\n",
1269                         cdr->party_a.snapshot->name,
1270                         (long)cdr->start.tv_sec,
1271                         (long)cdr->start.tv_usec,
1272                         (long)cdr->answer.tv_sec,
1273                         (long)cdr->answer.tv_usec,
1274                         (long)cdr->end.tv_sec,
1275                         (long)cdr->end.tv_usec,
1276                         ast_cdr_disp2str(cdr->disposition));
1277 }
1278
1279 /*!
1280  * \brief Check to see if a CDR needs to move to the finalized state because
1281  * its Party A hungup.
1282  */
1283 static void cdr_object_check_party_a_hangup(struct cdr_object *cdr)
1284 {
1285         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1286
1287         if (ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)
1288                 && ast_test_flag(&cdr->party_a.snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1289                 cdr_object_finalize(cdr);
1290         }
1291
1292         if (ast_test_flag(&cdr->party_a.snapshot->flags, AST_FLAG_DEAD)
1293                 && cdr->fn_table != &finalized_state_fn_table) {
1294                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1295         }
1296 }
1297
1298 /*!
1299  * \brief Check to see if a CDR needs to be answered based on its Party A.
1300  * Note that this is safe to call as much as you want - we won't answer twice
1301  */
1302 static void cdr_object_check_party_a_answer(struct cdr_object *cdr) {
1303         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1304
1305         if (cdr->party_a.snapshot->state == AST_STATE_UP && ast_tvzero(cdr->answer)) {
1306                 cdr->answer = ast_tvnow();
1307                 /* tv_usec is suseconds_t, which could be int or long */
1308                 CDR_DEBUG(mod_cfg, "%p - Set answered time to %ld.%06ld\n", cdr,
1309                         (long)cdr->answer.tv_sec,
1310                         (long)cdr->answer.tv_usec);
1311         }
1312 }
1313
1314 /* \brief Set Caller ID information on a CDR */
1315 static void cdr_object_update_cid(struct cdr_object_snapshot *old_snapshot, struct ast_channel_snapshot *new_snapshot)
1316 {
1317         if (!old_snapshot->snapshot) {
1318                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1319                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1320                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1321                 return;
1322         }
1323         if (!strcmp(old_snapshot->snapshot->caller_dnid, new_snapshot->caller_dnid)) {
1324                 set_variable(&old_snapshot->variables, "dnid", new_snapshot->caller_dnid);
1325         }
1326         if (!strcmp(old_snapshot->snapshot->caller_subaddr, new_snapshot->caller_subaddr)) {
1327                 set_variable(&old_snapshot->variables, "callingsubaddr", new_snapshot->caller_subaddr);
1328         }
1329         if (!strcmp(old_snapshot->snapshot->dialed_subaddr, new_snapshot->dialed_subaddr)) {
1330                 set_variable(&old_snapshot->variables, "calledsubaddr", new_snapshot->dialed_subaddr);
1331         }
1332 }
1333
1334 /*!
1335  * \brief Swap an old \ref cdr_object_snapshot's \ref ast_channel_snapshot for
1336  * a new \ref ast_channel_snapshot
1337  * \param old_snapshot The old \ref cdr_object_snapshot
1338  * \param new_snapshot The new \ref ast_channel_snapshot for old_snapshot
1339  */
1340 static void cdr_object_swap_snapshot(struct cdr_object_snapshot *old_snapshot,
1341                 struct ast_channel_snapshot *new_snapshot)
1342 {
1343         cdr_object_update_cid(old_snapshot, new_snapshot);
1344         if (old_snapshot->snapshot) {
1345                 ao2_t_ref(old_snapshot->snapshot, -1, "Drop ref for swap");
1346         }
1347         ao2_t_ref(new_snapshot, +1, "Bump ref for swap");
1348         old_snapshot->snapshot = new_snapshot;
1349 }
1350
1351 /* BASE METHOD IMPLEMENTATIONS */
1352
1353 static int base_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1354 {
1355         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1356
1357         ast_assert(strcasecmp(snapshot->name, cdr->party_a.snapshot->name) == 0);
1358
1359         /* Ignore any snapshots from a dead or dying channel */
1360         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1361                         && ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)) {
1362                 cdr_object_check_party_a_hangup(cdr);
1363                 return 0;
1364         }
1365
1366         /*
1367          * Only record the context and extension if we aren't in a subroutine, or if
1368          * we are executing hangup logic.
1369          */
1370         if (!ast_test_flag(&snapshot->flags, AST_FLAG_SUBROUTINE_EXEC)
1371                 || ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)) {
1372                 ast_string_field_set(cdr, context, snapshot->context);
1373                 ast_string_field_set(cdr, exten, snapshot->exten);
1374         }
1375
1376         cdr_object_swap_snapshot(&cdr->party_a, snapshot);
1377
1378         /* When Party A is originated to an application and the application exits, the stack
1379          * will attempt to clear the application and restore the dummy originate application
1380          * of "AppDialX". Prevent that, and any other application changes we might not want
1381          * here.
1382          */
1383         if (!ast_strlen_zero(snapshot->appl)
1384                         && (strncasecmp(snapshot->appl, "appdial", 7) || ast_strlen_zero(cdr->appl))
1385                         && !ast_test_flag(&cdr->flags, AST_CDR_LOCK_APP)) {
1386                 ast_string_field_set(cdr, appl, snapshot->appl);
1387                 ast_string_field_set(cdr, data, snapshot->data);
1388
1389                 /* Dial (app_dial) is a special case. Because pre-dial handlers, which
1390                  * execute before the dial begins, will alter the application/data to
1391                  * something people typically don't want to see, if we see a channel enter
1392                  * into Dial here, we set the appl/data accordingly and lock it.
1393                  */
1394                 if (!strcmp(snapshot->appl, "Dial")) {
1395                         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1396                 }
1397         }
1398
1399         ast_string_field_set(cdr, linkedid, snapshot->linkedid);
1400         cdr_object_check_party_a_answer(cdr);
1401         cdr_object_check_party_a_hangup(cdr);
1402
1403         return 0;
1404 }
1405
1406 static int base_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1407 {
1408         /* In general, most things shouldn't get a bridge leave */
1409         ast_assert(0);
1410         return 1;
1411 }
1412
1413 static int base_process_dial_end(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer, const char *dial_status)
1414 {
1415         /* In general, most things shouldn't get a dial end. */
1416         ast_assert(0);
1417         return 0;
1418 }
1419
1420 static enum process_bridge_enter_results base_process_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1421 {
1422         /* Base process bridge enter simply indicates that we can't handle it */
1423         return BRIDGE_ENTER_NEED_CDR;
1424 }
1425
1426 static int base_process_parked_channel(struct cdr_object *cdr, struct ast_parked_call_payload *parking_info)
1427 {
1428         char park_info[128];
1429
1430         ast_assert(!strcasecmp(parking_info->parkee->name, cdr->party_a.snapshot->name));
1431
1432         /* Update Party A information regardless */
1433         cdr->fn_table->process_party_a(cdr, parking_info->parkee);
1434
1435         /* Fake out where we're parked */
1436         ast_string_field_set(cdr, appl, "Park");
1437         snprintf(park_info, sizeof(park_info), "%s:%u", parking_info->parkinglot, parking_info->parkingspace);
1438         ast_string_field_set(cdr, data, park_info);
1439
1440         /* Prevent any further changes to the App/Data fields for this record */
1441         ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1442
1443         return 0;
1444 }
1445
1446 /* SINGLE STATE */
1447
1448 static void single_state_init_function(struct cdr_object *cdr) {
1449         cdr->start = ast_tvnow();
1450         cdr_object_check_party_a_answer(cdr);
1451 }
1452
1453 static void single_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1454 {
1455         /* This should never happen! */
1456         ast_assert(cdr->party_b.snapshot == NULL);
1457         ast_assert(0);
1458         return;
1459 }
1460
1461 static int single_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1462 {
1463         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1464
1465         if (caller && !strcasecmp(cdr->party_a.snapshot->name, caller->name)) {
1466                 base_process_party_a(cdr, caller);
1467                 CDR_DEBUG(mod_cfg, "%p - Updated Party A %s snapshot\n", cdr,
1468                                 cdr->party_a.snapshot->name);
1469                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1470                 CDR_DEBUG(mod_cfg, "%p - Updated Party B %s snapshot\n", cdr,
1471                                 cdr->party_b.snapshot->name);
1472
1473                 /* If we have two parties, lock the application that caused the
1474                  * two parties to be associated. This prevents mid-call event
1475                  * macros/gosubs from perturbing the CDR application/data
1476                  */
1477                 ast_set_flag(&cdr->flags, AST_CDR_LOCK_APP);
1478         } else if (!strcasecmp(cdr->party_a.snapshot->name, peer->name)) {
1479                 /* We're the entity being dialed, i.e., outbound origination */
1480                 base_process_party_a(cdr, peer);
1481                 CDR_DEBUG(mod_cfg, "%p - Updated Party A %s snapshot\n", cdr,
1482                                 cdr->party_a.snapshot->name);
1483         }
1484
1485         cdr_object_transition_state(cdr, &dial_state_fn_table);
1486         return 0;
1487 }
1488
1489 /*!
1490  * \brief Handle a comparison between our \ref cdr_object and a \ref cdr_object
1491  * already in the bridge while in the Single state. The goal of this is to find
1492  * a Party B for our CDR.
1493  *
1494  * \param cdr Our \ref cdr_object in the Single state
1495  * \param cand_cdr The \ref cdr_object already in the Bridge state
1496  *
1497  * \retval 0 The cand_cdr had a Party A or Party B that we could use as our
1498  * Party B
1499  * \retval 1 No party in the cand_cdr could be used as our Party B
1500  */
1501 static int single_state_bridge_enter_comparison(struct cdr_object *cdr,
1502                 struct cdr_object *cand_cdr)
1503 {
1504         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1505         struct cdr_object_snapshot *party_a;
1506
1507         /* Don't match on ourselves */
1508         if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1509                 return 1;
1510         }
1511
1512         /* Try the candidate CDR's Party A first */
1513         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
1514         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1515                 CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
1516                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name);
1517                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1518                 if (!cand_cdr->party_b.snapshot) {
1519                         /* We just stole them - finalize their CDR. Note that this won't
1520                          * transition their state, it just sets the end time and the
1521                          * disposition - if we need to re-activate them later, we can.
1522                          */
1523                         cdr_object_finalize(cand_cdr);
1524                 }
1525                 return 0;
1526         }
1527
1528         /* Try their Party B, unless it's us */
1529         if (!cand_cdr->party_b.snapshot
1530                 || !strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name)) {
1531                 return 1;
1532         }
1533         party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_b);
1534         if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
1535                 CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
1536                         cdr, cdr->party_a.snapshot->name, cand_cdr->party_b.snapshot->name);
1537                 cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_b);
1538                 return 0;
1539         }
1540
1541         return 1;
1542 }
1543
1544 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)
1545 {
1546         struct ao2_iterator it_cdrs;
1547         char *channel_id;
1548         int success = 0;
1549
1550         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1551
1552         if (ao2_container_count(bridge->channels) == 1) {
1553                 /* No one in the bridge yet but us! */
1554                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1555                 return BRIDGE_ENTER_ONLY_PARTY;
1556         }
1557
1558         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1559                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1560                 ao2_ref(channel_id, -1)) {
1561                 RAII_VAR(struct cdr_object *, cand_cdr_master,
1562                         ao2_find(active_cdrs_by_channel, channel_id, OBJ_KEY),
1563                         ao2_cleanup);
1564                 struct cdr_object *cand_cdr;
1565
1566                 if (!cand_cdr_master) {
1567                         continue;
1568                 }
1569
1570                 ao2_lock(cand_cdr_master);
1571                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1572                         /* Skip any records that are not in a bridge or in this bridge.
1573                          * I'm not sure how that would happen, but it pays to be careful. */
1574                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1575                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1576                                 continue;
1577                         }
1578
1579                         if (single_state_bridge_enter_comparison(cdr, cand_cdr)) {
1580                                 continue;
1581                         }
1582                         /* We successfully got a party B - break out */
1583                         success = 1;
1584                         break;
1585                 }
1586                 ao2_unlock(cand_cdr_master);
1587         }
1588         ao2_iterator_destroy(&it_cdrs);
1589
1590         /* We always transition state, even if we didn't get a peer */
1591         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1592
1593         /* Success implies that we have a Party B */
1594         if (success) {
1595                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1596         }
1597
1598         return BRIDGE_ENTER_NO_PARTY_B;
1599 }
1600
1601 static int single_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1602 {
1603         cdr_object_transition_state(cdr, &parked_state_fn_table);
1604         return 0;
1605 }
1606
1607
1608 /* DIAL STATE */
1609
1610 static void dial_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1611 {
1612         ast_assert(snapshot != NULL);
1613
1614         if (!cdr->party_b.snapshot
1615                 || strcasecmp(cdr->party_b.snapshot->name, snapshot->name)) {
1616                 return;
1617         }
1618         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1619
1620         /* If party B hangs up, finalize this CDR */
1621         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1622                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1623         }
1624 }
1625
1626 static int dial_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1627 {
1628         /* Don't process a begin dial here. A party A already in the dial state will
1629          * who receives a dial begin for something else will be handled by the
1630          * message router callback and will add a new CDR for the party A */
1631         return 1;
1632 }
1633
1634 /*!
1635  * \internal
1636  * \brief Convert a dial status to a CDR disposition
1637  */
1638 static enum ast_cdr_disposition dial_status_to_disposition(const char *dial_status)
1639 {
1640         RAII_VAR(struct module_config *, mod_cfg,
1641                 ao2_global_obj_ref(module_configs), ao2_cleanup);
1642
1643         if (!strcmp(dial_status, "ANSWER")) {
1644                 return AST_CDR_ANSWERED;
1645         } else if (!strcmp(dial_status, "BUSY")) {
1646                 return AST_CDR_BUSY;
1647         } else if (!strcmp(dial_status, "CANCEL") || !strcmp(dial_status, "NOANSWER")) {
1648                 return AST_CDR_NOANSWER;
1649         } else if (!strcmp(dial_status, "CONGESTION")) {
1650                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_CONGESTION)) {
1651                         return AST_CDR_FAILED;
1652                 } else {
1653                         return AST_CDR_CONGESTION;
1654                 }
1655         } else if (!strcmp(dial_status, "FAILED")) {
1656                 return AST_CDR_FAILED;
1657         }
1658         return AST_CDR_FAILED;
1659 }
1660
1661 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)
1662 {
1663         struct ast_channel_snapshot *party_a;
1664
1665         if (caller) {
1666                 party_a = caller;
1667         } else {
1668                 party_a = peer;
1669         }
1670         ast_assert(!strcasecmp(cdr->party_a.snapshot->name, party_a->name));
1671         cdr_object_swap_snapshot(&cdr->party_a, party_a);
1672
1673         if (cdr->party_b.snapshot) {
1674                 if (strcasecmp(cdr->party_b.snapshot->name, peer->name)) {
1675                         /* Not the status for this CDR - defer back to the message router */
1676                         return 1;
1677                 }
1678                 cdr_object_swap_snapshot(&cdr->party_b, peer);
1679         }
1680
1681         /* Set the disposition based on the dial string. */
1682         cdr->disposition = dial_status_to_disposition(dial_status);
1683         if (cdr->disposition == AST_CDR_ANSWERED) {
1684                 /* Switch to dial pending to wait and see what the caller does */
1685                 cdr_object_transition_state(cdr, &dialed_pending_state_fn_table);
1686         } else {
1687                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1688         }
1689
1690         return 0;
1691 }
1692
1693 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)
1694 {
1695         struct ao2_iterator it_cdrs;
1696         char *channel_id;
1697         int success = 0;
1698
1699         ast_string_field_set(cdr, bridge, bridge->uniqueid);
1700
1701         /* Get parties in the bridge */
1702         if (ao2_container_count(bridge->channels) == 1) {
1703                 /* No one in the bridge yet but us! */
1704                 cdr_object_transition_state(cdr, &bridge_state_fn_table);
1705                 return BRIDGE_ENTER_ONLY_PARTY;
1706         }
1707
1708         for (it_cdrs = ao2_iterator_init(bridge->channels, 0);
1709                 !success && (channel_id = ao2_iterator_next(&it_cdrs));
1710                 ao2_ref(channel_id, -1)) {
1711                 RAII_VAR(struct cdr_object *, cand_cdr_master,
1712                         ao2_find(active_cdrs_by_channel, channel_id, OBJ_KEY),
1713                         ao2_cleanup);
1714                 struct cdr_object *cand_cdr;
1715
1716                 if (!cand_cdr_master) {
1717                         continue;
1718                 }
1719
1720                 ao2_lock(cand_cdr_master);
1721                 for (cand_cdr = cand_cdr_master; cand_cdr; cand_cdr = cand_cdr->next) {
1722                         /* Skip any records that are not in a bridge or in this bridge.
1723                          * I'm not sure how that would happen, but it pays to be careful. */
1724                         if (cand_cdr->fn_table != &bridge_state_fn_table ||
1725                                         strcmp(cdr->bridge, cand_cdr->bridge)) {
1726                                 continue;
1727                         }
1728
1729                         /* If we don't have a Party B (originated channel), skip it */
1730                         if (!cdr->party_b.snapshot) {
1731                                 continue;
1732                         }
1733
1734                         /* Skip any records that aren't our Party B */
1735                         if (strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name)) {
1736                                 continue;
1737                         }
1738                         cdr_object_snapshot_copy(&cdr->party_b, &cand_cdr->party_a);
1739                         /* If they have a Party B, they joined up with someone else as their
1740                          * Party A. Don't finalize them as they're active. Otherwise, we
1741                          * have stolen them so they need to be finalized.
1742                          */
1743                         if (!cand_cdr->party_b.snapshot) {
1744                                 cdr_object_finalize(cand_cdr);
1745                         }
1746                         success = 1;
1747                         break;
1748                 }
1749                 ao2_unlock(cand_cdr_master);
1750         }
1751         ao2_iterator_destroy(&it_cdrs);
1752
1753         /* We always transition state, even if we didn't get a peer */
1754         cdr_object_transition_state(cdr, &bridge_state_fn_table);
1755
1756         /* Success implies that we have a Party B */
1757         if (success) {
1758                 return BRIDGE_ENTER_OBTAINED_PARTY_B;
1759         }
1760         return BRIDGE_ENTER_NO_PARTY_B;
1761 }
1762
1763 /* DIALED PENDING STATE */
1764
1765 static int dialed_pending_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1766 {
1767         /* If we get a CEP change, we're executing dialplan. If we have a Party B
1768          * that means we need a new CDR; otherwise, switch us over to single.
1769          */
1770         if (snapshot_cep_changed(cdr->party_a.snapshot, snapshot)) {
1771                 if (cdr->party_b.snapshot) {
1772                         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1773                         cdr->fn_table->process_party_a(cdr, snapshot);
1774                         return 1;
1775                 } else {
1776                         cdr_object_transition_state(cdr, &single_state_fn_table);
1777                         cdr->fn_table->process_party_a(cdr, snapshot);
1778                         return 0;
1779                 }
1780         }
1781         base_process_party_a(cdr, snapshot);
1782         return 0;
1783 }
1784
1785 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)
1786 {
1787         cdr_object_transition_state(cdr, &dial_state_fn_table);
1788         return cdr->fn_table->process_bridge_enter(cdr, bridge, channel);
1789 }
1790
1791 static int dialed_pending_state_process_parking_bridge_enter(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1792 {
1793         if (cdr->party_b.snapshot) {
1794                 /* We can't handle this as we have a Party B - ask for a new one */
1795                 return 1;
1796         }
1797         cdr_object_transition_state(cdr, &parked_state_fn_table);
1798         return 0;
1799 }
1800
1801 static int dialed_pending_state_process_dial_begin(struct cdr_object *cdr, struct ast_channel_snapshot *caller, struct ast_channel_snapshot *peer)
1802 {
1803         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1804
1805         /* Ask for a new CDR */
1806         return 1;
1807 }
1808
1809 /* BRIDGE STATE */
1810
1811 static void bridge_state_process_party_b(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1812 {
1813         if (!cdr->party_b.snapshot
1814                 || strcasecmp(cdr->party_b.snapshot->name, snapshot->name)) {
1815                 return;
1816         }
1817         cdr_object_swap_snapshot(&cdr->party_b, snapshot);
1818
1819         /* If party B hangs up, finalize this CDR */
1820         if (ast_test_flag(&cdr->party_b.snapshot->flags, AST_FLAG_DEAD)) {
1821                 cdr_object_transition_state(cdr, &finalized_state_fn_table);
1822         }
1823 }
1824
1825 static int bridge_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1826 {
1827         if (strcmp(cdr->bridge, bridge->uniqueid)) {
1828                 return 1;
1829         }
1830         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)
1831                 && cdr->party_b.snapshot
1832                 && strcasecmp(cdr->party_b.snapshot->name, channel->name)) {
1833                 return 1;
1834         }
1835         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1836
1837         return 0;
1838 }
1839
1840 /* PARKED STATE */
1841
1842 static int parked_state_process_bridge_leave(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge, struct ast_channel_snapshot *channel)
1843 {
1844         if (strcasecmp(cdr->party_a.snapshot->name, channel->name)) {
1845                 return 1;
1846         }
1847         cdr_object_transition_state(cdr, &finalized_state_fn_table);
1848
1849         return 0;
1850 }
1851
1852 /* FINALIZED STATE */
1853
1854 static void finalized_state_init_function(struct cdr_object *cdr)
1855 {
1856         cdr_object_finalize(cdr);
1857 }
1858
1859 static int finalized_state_process_party_a(struct cdr_object *cdr, struct ast_channel_snapshot *snapshot)
1860 {
1861         RAII_VAR(struct module_config *, mod_cfg,
1862                 ao2_global_obj_ref(module_configs), ao2_cleanup);
1863
1864         if (ast_test_flag(&snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
1865                         && ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN)) {
1866                 return 0;
1867         }
1868
1869         /* Indicate that, if possible, we should get a new CDR */
1870         return 1;
1871 }
1872
1873 /*!
1874  * \internal
1875  * \brief Filter channel snapshots by technology
1876  */
1877 static int filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1878 {
1879         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
1880 }
1881
1882 /*!
1883  * \internal
1884  * \brief Filter a channel cache update
1885  */
1886 static int filter_channel_cache_message(struct ast_channel_snapshot *old_snapshot,
1887                 struct ast_channel_snapshot *new_snapshot)
1888 {
1889         int ret = 0;
1890
1891         /* Drop cache updates from certain channel technologies */
1892         if (old_snapshot) {
1893                 ret |= filter_channel_snapshot(old_snapshot);
1894         }
1895         if (new_snapshot) {
1896                 ret |= filter_channel_snapshot(new_snapshot);
1897         }
1898
1899         return ret;
1900 }
1901
1902 /* TOPIC ROUTER CALLBACKS */
1903
1904 /*!
1905  * \brief Handler for Stasis-Core dial messages
1906  * \param data Passed on
1907  * \param sub The stasis subscription for this message callback
1908  * \param topic The topic this message was published for
1909  * \param message The message
1910  */
1911 static void handle_dial_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
1912 {
1913         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
1914         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
1915         struct ast_multi_channel_blob *payload = stasis_message_data(message);
1916         struct ast_channel_snapshot *caller;
1917         struct ast_channel_snapshot *peer;
1918         struct cdr_object *it_cdr;
1919         struct ast_json *dial_status_blob;
1920         const char *dial_status = NULL;
1921         int res = 1;
1922
1923         caller = ast_multi_channel_blob_get_channel(payload, "caller");
1924         peer = ast_multi_channel_blob_get_channel(payload, "peer");
1925         if (!peer && !caller) {
1926                 return;
1927         }
1928         dial_status_blob = ast_json_object_get(ast_multi_channel_blob_get_json(payload), "dialstatus");
1929         if (dial_status_blob) {
1930                 dial_status = ast_json_string_get(dial_status_blob);
1931         }
1932
1933         CDR_DEBUG(mod_cfg, "Dial %s message for %s, %s: %u.%08u\n",
1934                         ast_strlen_zero(dial_status) ? "Begin" : "End",
1935                         caller ? caller->name : "(none)",
1936                         peer ? peer->name : "(none)",
1937                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
1938                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
1939
1940         if (filter_channel_snapshot(peer) || (caller && filter_channel_snapshot(caller))) {
1941                 return;
1942         }
1943
1944         /* Figure out who is running this show */
1945         if (caller) {
1946                 cdr = ao2_find(active_cdrs_by_channel, caller->uniqueid, OBJ_KEY);
1947         } else {
1948                 cdr = ao2_find(active_cdrs_by_channel, peer->uniqueid, OBJ_KEY);
1949         }
1950
1951         if (!cdr) {
1952                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", caller ? caller->name : peer->name);
1953                 ast_assert(0);
1954                 return;
1955         }
1956
1957         ao2_lock(cdr);
1958         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
1959                 if (ast_strlen_zero(dial_status)) {
1960                         if (!it_cdr->fn_table->process_dial_begin) {
1961                                 continue;
1962                         }
1963                         CDR_DEBUG(mod_cfg, "%p - Processing Dial Begin message for channel %s, peer %s\n",
1964                                         it_cdr,
1965                                         caller ? caller->name : "(none)",
1966                                         peer ? peer->name : "(none)");
1967                         res &= it_cdr->fn_table->process_dial_begin(it_cdr,
1968                                         caller,
1969                                         peer);
1970                 } else {
1971                         if (!it_cdr->fn_table->process_dial_end) {
1972                                 continue;
1973                         }
1974                         CDR_DEBUG(mod_cfg, "%p - Processing Dial End message for channel %s, peer %s\n",
1975                                         it_cdr,
1976                                         caller ? caller->name : "(none)",
1977                                         peer ? peer->name : "(none)");
1978                         it_cdr->fn_table->process_dial_end(it_cdr,
1979                                         caller,
1980                                         peer,
1981                                         dial_status);
1982                 }
1983         }
1984
1985         /* If no CDR handled a dial begin message, make a new one */
1986         if (res && ast_strlen_zero(dial_status)) {
1987                 struct cdr_object *new_cdr;
1988
1989                 new_cdr = cdr_object_create_and_append(cdr);
1990                 if (!new_cdr) {
1991                         ao2_unlock(cdr);
1992                         return;
1993                 }
1994                 new_cdr->fn_table->process_dial_begin(new_cdr,
1995                                 caller,
1996                                 peer);
1997         }
1998         ao2_unlock(cdr);
1999 }
2000
2001 static int cdr_object_finalize_party_b(void *obj, void *arg, int flags)
2002 {
2003         struct cdr_object *cdr = obj;
2004         struct ast_channel_snapshot *party_b = arg;
2005         struct cdr_object *it_cdr;
2006         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2007                 if (it_cdr->party_b.snapshot
2008                         && !strcasecmp(it_cdr->party_b.snapshot->name, party_b->name)) {
2009                         /* Don't transition to the finalized state - let the Party A do
2010                          * that when its ready
2011                          */
2012                         cdr_object_finalize(it_cdr);
2013                 }
2014         }
2015         return 0;
2016 }
2017
2018 static int cdr_object_update_party_b(void *obj, void *arg, int flags)
2019 {
2020         struct cdr_object *cdr = obj;
2021         struct ast_channel_snapshot *party_b = arg;
2022         struct cdr_object *it_cdr;
2023         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2024                 if (!it_cdr->fn_table->process_party_b) {
2025                         continue;
2026                 }
2027                 if (it_cdr->party_b.snapshot
2028                         && !strcasecmp(it_cdr->party_b.snapshot->name, party_b->name)) {
2029                         it_cdr->fn_table->process_party_b(it_cdr, party_b);
2030                 }
2031         }
2032         return 0;
2033 }
2034
2035 /*! \brief Determine if we need to add a new CDR based on snapshots */
2036 static int check_new_cdr_needed(struct ast_channel_snapshot *old_snapshot,
2037                 struct ast_channel_snapshot *new_snapshot)
2038 {
2039         RAII_VAR(struct module_config *, mod_cfg,
2040                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2041
2042         /* If we're dead, we don't need a new CDR */
2043         if (!new_snapshot
2044                 || (ast_test_flag(&new_snapshot->softhangup_flags, AST_SOFTHANGUP_HANGUP_EXEC)
2045                         && ast_test_flag(&mod_cfg->general->settings, CDR_END_BEFORE_H_EXTEN))) {
2046                 return 0;
2047         }
2048
2049         /* Auto-fall through will increment the priority but have no application */
2050         if (ast_strlen_zero(new_snapshot->appl)) {
2051                 return 0;
2052         }
2053
2054         if (old_snapshot && !snapshot_cep_changed(old_snapshot, new_snapshot)) {
2055                 return 0;
2056         }
2057
2058         return 1;
2059 }
2060
2061 /*!
2062  * \brief Handler for Stasis-Core channel cache update messages
2063  * \param data Passed on
2064  * \param sub The stasis subscription for this message callback
2065  * \param topic The topic this message was published for
2066  * \param message The message
2067  */
2068 static void handle_channel_cache_message(void *data, struct stasis_subscription *sub, struct stasis_message *message)
2069 {
2070         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
2071         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2072         struct stasis_cache_update *update = stasis_message_data(message);
2073         struct ast_channel_snapshot *old_snapshot;
2074         struct ast_channel_snapshot *new_snapshot;
2075         const char *uniqueid;
2076         const char *name;
2077         struct cdr_object *it_cdr;
2078
2079         ast_assert(update != NULL);
2080         ast_assert(ast_channel_snapshot_type() == update->type);
2081
2082         old_snapshot = stasis_message_data(update->old_snapshot);
2083         new_snapshot = stasis_message_data(update->new_snapshot);
2084         uniqueid = new_snapshot ? new_snapshot->uniqueid : old_snapshot->uniqueid;
2085         name = new_snapshot ? new_snapshot->name : old_snapshot->name;
2086
2087         if (filter_channel_cache_message(old_snapshot, new_snapshot)) {
2088                 return;
2089         }
2090
2091         if (new_snapshot && !old_snapshot) {
2092                 cdr = cdr_object_alloc(new_snapshot);
2093                 if (!cdr) {
2094                         return;
2095                 }
2096                 ao2_link(active_cdrs_by_channel, cdr);
2097         }
2098
2099         /* Handle Party A */
2100         if (!cdr) {
2101                 cdr = ao2_find(active_cdrs_by_channel, uniqueid, OBJ_KEY);
2102         }
2103         if (!cdr) {
2104                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", name);
2105                 ast_assert(0);
2106         } else {
2107                 ao2_lock(cdr);
2108                 if (new_snapshot) {
2109                         int all_reject = 1;
2110                         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2111                                 if (!it_cdr->fn_table->process_party_a) {
2112                                         continue;
2113                                 }
2114                                 all_reject &= it_cdr->fn_table->process_party_a(it_cdr, new_snapshot);
2115                         }
2116                         if (all_reject && check_new_cdr_needed(old_snapshot, new_snapshot)) {
2117                                 /* We're not hung up and we have a new snapshot - we need a new CDR */
2118                                 struct cdr_object *new_cdr;
2119                                 new_cdr = cdr_object_create_and_append(cdr);
2120                                 if (new_cdr) {
2121                                         new_cdr->fn_table->process_party_a(new_cdr, new_snapshot);
2122                                 }
2123                         }
2124                 } else {
2125                         CDR_DEBUG(mod_cfg, "%p - Beginning finalize/dispatch for %s\n", cdr, old_snapshot->name);
2126                         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2127                                 cdr_object_finalize(it_cdr);
2128                         }
2129                         cdr_object_dispatch(cdr);
2130                         ao2_unlink(active_cdrs_by_channel, cdr);
2131                 }
2132                 ao2_unlock(cdr);
2133         }
2134
2135         /* Handle Party B */
2136         if (new_snapshot) {
2137                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_update_party_b,
2138                         new_snapshot);
2139         } else {
2140                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA, cdr_object_finalize_party_b,
2141                         old_snapshot);
2142         }
2143
2144 }
2145
2146 struct bridge_leave_data {
2147         struct ast_bridge_snapshot *bridge;
2148         struct ast_channel_snapshot *channel;
2149 };
2150
2151 /*! \brief Callback used to notify CDRs of a Party B leaving the bridge */
2152 static int cdr_object_party_b_left_bridge_cb(void *obj, void *arg, int flags)
2153 {
2154         struct cdr_object *cdr = obj;
2155         struct bridge_leave_data *leave_data = arg;
2156         struct cdr_object *it_cdr;
2157
2158         if (strcmp(cdr->bridge, leave_data->bridge->uniqueid)) {
2159                 return 0;
2160         }
2161         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2162                 if (it_cdr->fn_table != &bridge_state_fn_table) {
2163                         continue;
2164                 }
2165                 if (!it_cdr->party_b.snapshot) {
2166                         continue;
2167                 }
2168                 if (strcasecmp(it_cdr->party_b.snapshot->name, leave_data->channel->name)) {
2169                         continue;
2170                 }
2171                 /* It is our Party B, in our bridge. Set the end time and let the handler
2172                  * transition our CDR appropriately when we leave the bridge.
2173                  */
2174                 cdr_object_finalize(it_cdr);
2175         }
2176         return 0;
2177 }
2178
2179 /*! \brief Filter bridge messages based on bridge technology */
2180 static int filter_bridge_messages(struct ast_bridge_snapshot *bridge)
2181 {
2182         /* Ignore holding bridge technology messages. We treat this simply as an application
2183          * that a channel enters into.
2184          */
2185         if (!strcmp(bridge->technology, "holding_bridge") && strcmp(bridge->subclass, "parking")) {
2186                 return 1;
2187         }
2188         return 0;
2189 }
2190
2191 /*!
2192  * \brief Handler for when a channel leaves a bridge
2193  * \param data Passed on
2194  * \param sub The stasis subscription for this message callback
2195  * \param topic The topic this message was published for
2196  * \param message The message - hopefully a bridge one!
2197  */
2198 static void handle_bridge_leave_message(void *data, struct stasis_subscription *sub,
2199                 struct stasis_message *message)
2200 {
2201         struct ast_bridge_blob *update = stasis_message_data(message);
2202         struct ast_bridge_snapshot *bridge = update->bridge;
2203         struct ast_channel_snapshot *channel = update->channel;
2204         RAII_VAR(struct module_config *, mod_cfg,
2205                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2206         RAII_VAR(struct cdr_object *, cdr,
2207                         ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_KEY),
2208                         ao2_cleanup);
2209         struct cdr_object *it_cdr;
2210         struct bridge_leave_data leave_data = {
2211                 .bridge = bridge,
2212                 .channel = channel,
2213         };
2214         int left_bridge = 0;
2215
2216         if (filter_bridge_messages(bridge)) {
2217                 return;
2218         }
2219
2220         if (filter_channel_snapshot(channel)) {
2221                 return;
2222         }
2223
2224         CDR_DEBUG(mod_cfg, "Bridge Leave message for %s: %u.%08u\n",
2225                         channel->name,
2226                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
2227                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
2228
2229         if (!cdr) {
2230                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2231                 ast_assert(0);
2232                 return;
2233         }
2234
2235         /* Party A */
2236         ao2_lock(cdr);
2237         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2238                 if (!it_cdr->fn_table->process_bridge_leave) {
2239                         continue;
2240                 }
2241                 CDR_DEBUG(mod_cfg, "%p - Processing Bridge Leave for %s\n",
2242                                 it_cdr, channel->name);
2243                 if (!it_cdr->fn_table->process_bridge_leave(it_cdr, bridge, channel)) {
2244                         ast_string_field_set(it_cdr, bridge, "");
2245                         left_bridge = 1;
2246                 }
2247         }
2248         ao2_unlock(cdr);
2249         if (!left_bridge) {
2250                 return;
2251         }
2252
2253         if (strcmp(bridge->subclass, "parking")) {
2254                 /* Party B */
2255                 ao2_callback(active_cdrs_by_channel, OBJ_NODATA,
2256                                 cdr_object_party_b_left_bridge_cb,
2257                                 &leave_data);
2258         }
2259 }
2260
2261 /*!
2262  * \internal
2263  * \brief Create a new CDR, append it to an existing CDR, and update its snapshots
2264  *
2265  * \note The new CDR will be automatically transitioned to the bridge state
2266  */
2267 static void bridge_candidate_add_to_cdr(struct cdr_object *cdr,
2268                 struct cdr_object_snapshot *party_b)
2269 {
2270         RAII_VAR(struct module_config *,  mod_cfg,
2271                 ao2_global_obj_ref(module_configs), ao2_cleanup);
2272         struct cdr_object *new_cdr;
2273
2274         new_cdr = cdr_object_create_and_append(cdr);
2275         if (!new_cdr) {
2276                 return;
2277         }
2278         cdr_object_snapshot_copy(&new_cdr->party_b, party_b);
2279         cdr_object_check_party_a_answer(new_cdr);
2280         ast_string_field_set(new_cdr, bridge, cdr->bridge);
2281         cdr_object_transition_state(new_cdr, &bridge_state_fn_table);
2282         CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
2283                 new_cdr, new_cdr->party_a.snapshot->name,
2284                 party_b->snapshot->name);
2285 }
2286
2287 /*!
2288  * \brief Process a single \ref bridge_candidate
2289  *
2290  * When a CDR enters a bridge, it needs to make pairings with everyone else
2291  * that it is not currently paired with. This function determines, for the
2292  * CDR for the channel that entered the bridge and the CDR for every other
2293  * channel currently in the bridge, who is Party A and makes new CDRs.
2294  *
2295  * \param cdr The \ref cdr_obj being processed
2296  * \param cand_cdr The \ref cdr_object that is a candidate
2297  *
2298  */
2299 static int bridge_candidate_process(struct cdr_object *cdr, struct cdr_object *base_cand_cdr)
2300 {
2301         RAII_VAR(struct module_config *, mod_cfg,
2302                 ao2_global_obj_ref(module_configs), ao2_cleanup);
2303         struct cdr_object_snapshot *party_a;
2304         struct cdr_object *cand_cdr;
2305
2306         SCOPED_AO2LOCK(lock, base_cand_cdr);
2307
2308         for (cand_cdr = base_cand_cdr; cand_cdr; cand_cdr = cand_cdr->next) {
2309                 /* Skip any records that are not in this bridge */
2310                 if (strcmp(cand_cdr->bridge, cdr->bridge)) {
2311                         continue;
2312                 }
2313
2314                 /* If the candidate is us or someone we've taken on, pass on by */
2315                 if (!strcasecmp(cdr->party_a.snapshot->name, cand_cdr->party_a.snapshot->name)
2316                         || (cdr->party_b.snapshot
2317                                 && !strcasecmp(cdr->party_b.snapshot->name, cand_cdr->party_a.snapshot->name))) {
2318                         return 0;
2319                 }
2320
2321                 party_a = cdr_object_pick_party_a(&cdr->party_a, &cand_cdr->party_a);
2322                 /* We're party A - make a new CDR, append it to us, and set the candidate as
2323                  * Party B */
2324                 if (!strcasecmp(party_a->snapshot->name, cdr->party_a.snapshot->name)) {
2325                         bridge_candidate_add_to_cdr(cdr, &cand_cdr->party_a);
2326                         return 0;
2327                 }
2328
2329                 /* We're Party B. Check if we can add ourselves immediately or if we need
2330                  * a new CDR for them (they already have a Party B) */
2331                 if (cand_cdr->party_b.snapshot
2332                         && strcasecmp(cand_cdr->party_b.snapshot->name, cdr->party_a.snapshot->name)) {
2333                         bridge_candidate_add_to_cdr(cand_cdr, &cdr->party_a);
2334                 } else {
2335                         CDR_DEBUG(mod_cfg, "%p - Party A %s has new Party B %s\n",
2336                                 cand_cdr, cand_cdr->party_a.snapshot->name,
2337                                 cdr->party_a.snapshot->name);
2338                         cdr_object_snapshot_copy(&cand_cdr->party_b, &cdr->party_a);
2339                         /* It's possible that this joined at one point and was never chosen
2340                          * as party A. Clear their end time, as it would be set in such a
2341                          * case.
2342                          */
2343                         memset(&cand_cdr->end, 0, sizeof(cand_cdr->end));
2344                 }
2345                 return 0;
2346         }
2347         return 0;
2348 }
2349
2350 /*!
2351  * \brief Handle creating bridge pairings for the \ref cdr_object that just
2352  * entered a bridge
2353  * \param cdr The \ref cdr_object that just entered the bridge
2354  * \param bridge The \ref ast_bridge_snapshot representing the bridge it just entered
2355  */
2356 static void handle_bridge_pairings(struct cdr_object *cdr, struct ast_bridge_snapshot *bridge)
2357 {
2358         struct ao2_iterator it_channels;
2359         char *channel_id;
2360
2361         it_channels = ao2_iterator_init(bridge->channels, 0);
2362         while ((channel_id = ao2_iterator_next(&it_channels))) {
2363                 RAII_VAR(struct cdr_object *, cand_cdr,
2364                         ao2_find(active_cdrs_by_channel, channel_id, OBJ_KEY),
2365                         ao2_cleanup);
2366
2367                 if (!cand_cdr) {
2368                         ao2_ref(channel_id, -1);
2369                         continue;
2370                 }
2371
2372                 bridge_candidate_process(cdr, cand_cdr);
2373
2374                 ao2_ref(channel_id, -1);
2375         }
2376         ao2_iterator_destroy(&it_channels);
2377 }
2378
2379 /*! \brief Handle entering into a parking bridge
2380  * \param cdr The CDR to operate on
2381  * \param bridge The bridge the channel just entered
2382  * \param channel The channel snapshot
2383  */
2384 static void handle_parking_bridge_enter_message(struct cdr_object *cdr,
2385                 struct ast_bridge_snapshot *bridge,
2386                 struct ast_channel_snapshot *channel)
2387 {
2388         RAII_VAR(struct module_config *, mod_cfg,
2389                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2390         int res = 1;
2391         struct cdr_object *it_cdr;
2392         struct cdr_object *new_cdr;
2393
2394         ao2_lock(cdr);
2395
2396         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2397                 if (it_cdr->fn_table->process_parking_bridge_enter) {
2398                         res &= it_cdr->fn_table->process_parking_bridge_enter(it_cdr, bridge, channel);
2399                 }
2400                 if (it_cdr->fn_table->process_party_a) {
2401                         CDR_DEBUG(mod_cfg, "%p - Updating Party A %s snapshot\n", it_cdr,
2402                                         channel->name);
2403                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2404                 }
2405         }
2406
2407         if (res) {
2408                 /* No one handled it - we need a new one! */
2409                 new_cdr = cdr_object_create_and_append(cdr);
2410                 if (new_cdr) {
2411                         /* Let the single state transition us to Parked */
2412                         cdr_object_transition_state(new_cdr, &single_state_fn_table);
2413                         new_cdr->fn_table->process_parking_bridge_enter(new_cdr, bridge, channel);
2414                 }
2415         }
2416         ao2_unlock(cdr);
2417 }
2418
2419 /*! \brief Handle a bridge enter message for a 'normal' bridge
2420  * \param cdr The CDR to operate on
2421  * \param bridge The bridge the channel just entered
2422  * \param channel The channel snapshot
2423  */
2424 static void handle_standard_bridge_enter_message(struct cdr_object *cdr,
2425                 struct ast_bridge_snapshot *bridge,
2426                 struct ast_channel_snapshot *channel)
2427 {
2428         RAII_VAR(struct module_config *, mod_cfg,
2429                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2430         enum process_bridge_enter_results result;
2431         struct cdr_object *it_cdr;
2432         struct cdr_object *new_cdr;
2433         struct cdr_object *handled_cdr = NULL;
2434
2435         ao2_lock(cdr);
2436
2437         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2438                 if (it_cdr->fn_table->process_party_a) {
2439                         CDR_DEBUG(mod_cfg, "%p - Updating Party A %s snapshot\n", it_cdr,
2440                                         channel->name);
2441                         it_cdr->fn_table->process_party_a(it_cdr, channel);
2442                 }
2443
2444                 /* Notify all states that they have entered a bridge */
2445                 if (it_cdr->fn_table->process_bridge_enter) {
2446                         CDR_DEBUG(mod_cfg, "%p - Processing bridge enter for %s\n", it_cdr,
2447                                         channel->name);
2448                         result = it_cdr->fn_table->process_bridge_enter(it_cdr, bridge, channel);
2449                         switch (result) {
2450                         case BRIDGE_ENTER_ONLY_PARTY:
2451                                 /* Fall through */
2452                         case BRIDGE_ENTER_OBTAINED_PARTY_B:
2453                                 if (!handled_cdr) {
2454                                         handled_cdr = it_cdr;
2455                                 }
2456                                 break;
2457                         case BRIDGE_ENTER_NEED_CDR:
2458                                 /* Pass */
2459                                 break;
2460                         case BRIDGE_ENTER_NO_PARTY_B:
2461                                 /* We didn't win on any - end this CDR. If someone else comes in later
2462                                  * that is Party B to this CDR, it can re-activate this CDR.
2463                                  */
2464                                 if (!handled_cdr) {
2465                                         handled_cdr = it_cdr;
2466                                 }
2467                                 cdr_object_finalize(cdr);
2468                                 break;
2469                         }
2470                 }
2471         }
2472
2473         /* Create the new matchings, but only for either:
2474          *  * The first CDR in the chain that handled it. This avoids issues with
2475          *    forked CDRs.
2476          *  * If no one handled it, the last CDR in the chain. This would occur if
2477          *    a CDR joined a bridge and it wasn't Party A for anyone. We still need
2478          *    to make pairings with everyone in the bridge.
2479          */
2480         if (handled_cdr) {
2481                 handle_bridge_pairings(handled_cdr, bridge);
2482         } else {
2483                 /* Nothing handled it - we need a new one! */
2484                 new_cdr = cdr_object_create_and_append(cdr);
2485                 if (new_cdr) {
2486                         /* This is guaranteed to succeed: the new CDR is created in the single state
2487                          * and will be able to handle the bridge enter message
2488                          */
2489                         handle_standard_bridge_enter_message(cdr, bridge, channel);
2490                 }
2491         }
2492         ao2_unlock(cdr);
2493 }
2494
2495 /*!
2496  * \internal
2497  * \brief Handler for Stasis-Core bridge enter messages
2498  * \param data Passed on
2499  * \param sub The stasis subscription for this message callback
2500  * \param topic The topic this message was published for
2501  * \param message The message - hopefully a bridge one!
2502  */
2503 static void handle_bridge_enter_message(void *data, struct stasis_subscription *sub,
2504                 struct stasis_message *message)
2505 {
2506         struct ast_bridge_blob *update = stasis_message_data(message);
2507         struct ast_bridge_snapshot *bridge = update->bridge;
2508         struct ast_channel_snapshot *channel = update->channel;
2509         RAII_VAR(struct cdr_object *, cdr,
2510                         ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_KEY),
2511                         ao2_cleanup);
2512         RAII_VAR(struct module_config *, mod_cfg,
2513                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2514
2515         if (filter_bridge_messages(bridge)) {
2516                 return;
2517         }
2518
2519         if (filter_channel_snapshot(channel)) {
2520                 return;
2521         }
2522
2523         CDR_DEBUG(mod_cfg, "Bridge Enter message for channel %s: %u.%08u\n",
2524                         channel->name,
2525                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
2526                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
2527
2528         if (!cdr) {
2529                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2530                 ast_assert(0);
2531                 return;
2532         }
2533
2534         if (!strcmp(bridge->subclass, "parking")) {
2535                 handle_parking_bridge_enter_message(cdr, bridge, channel);
2536         } else {
2537                 handle_standard_bridge_enter_message(cdr, bridge, channel);
2538         }
2539 }
2540
2541 /*!
2542  * \brief Handler for when a channel is parked
2543  * \param data Passed on
2544  * \param sub The stasis subscription for this message callback
2545  * \param topic The topic this message was published for
2546  * \param message The message about who got parked
2547  * */
2548 static void handle_parked_call_message(void *data, struct stasis_subscription *sub,
2549                 struct stasis_message *message)
2550 {
2551         struct ast_parked_call_payload *payload = stasis_message_data(message);
2552         struct ast_channel_snapshot *channel = payload->parkee;
2553         RAII_VAR(struct cdr_object *, cdr, NULL, ao2_cleanup);
2554         RAII_VAR(struct module_config *, mod_cfg,
2555                         ao2_global_obj_ref(module_configs), ao2_cleanup);
2556         int unhandled = 1;
2557         struct cdr_object *it_cdr;
2558
2559         /* Anything other than getting parked will be handled by other updates */
2560         if (payload->event_type != PARKED_CALL) {
2561                 return;
2562         }
2563
2564         /* No one got parked? */
2565         if (!channel) {
2566                 return;
2567         }
2568
2569         if (filter_channel_snapshot(channel)) {
2570                 return;
2571         }
2572
2573         CDR_DEBUG(mod_cfg, "Parked Call message for channel %s: %u.%08u\n",
2574                         channel->name,
2575                         (unsigned int)stasis_message_timestamp(message)->tv_sec,
2576                         (unsigned int)stasis_message_timestamp(message)->tv_usec);
2577
2578         cdr = ao2_find(active_cdrs_by_channel, channel->uniqueid, OBJ_KEY);
2579         if (!cdr) {
2580                 ast_log(AST_LOG_WARNING, "No CDR for channel %s\n", channel->name);
2581                 ast_assert(0);
2582                 return;
2583         }
2584
2585         ao2_lock(cdr);
2586
2587         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2588                 if (it_cdr->fn_table->process_parked_channel) {
2589                         unhandled &= it_cdr->fn_table->process_parked_channel(it_cdr, payload);
2590                 }
2591         }
2592
2593         if (unhandled) {
2594                 /* Nothing handled the messgae - we need a new one! */
2595                 struct cdr_object *new_cdr = cdr_object_create_and_append(cdr);
2596                 if (new_cdr) {
2597                         /* As the new CDR is created in the single state, it is guaranteed
2598                          * to have a function for the parked call message and will handle
2599                          * the message */
2600                         new_cdr->fn_table->process_parked_channel(new_cdr, payload);
2601                 }
2602         }
2603
2604         ao2_unlock(cdr);
2605
2606 }
2607
2608 /*!
2609  * \brief Handler for a synchronization message
2610  * \param data Passed on
2611  * \param sub The stasis subscription for this message callback
2612  * \param topic The topic this message was published for
2613  * \param message A blank ao2 object
2614  * */
2615 static void handle_cdr_sync_message(void *data, struct stasis_subscription *sub,
2616                 struct stasis_message *message)
2617 {
2618         return;
2619 }
2620
2621 struct ast_cdr_config *ast_cdr_get_config(void)
2622 {
2623         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2624         ao2_ref(mod_cfg->general, +1);
2625         return mod_cfg->general;
2626 }
2627
2628 void ast_cdr_set_config(struct ast_cdr_config *config)
2629 {
2630         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2631
2632         ao2_cleanup(mod_cfg->general);
2633         mod_cfg->general = config;
2634         ao2_ref(mod_cfg->general, +1);
2635
2636         cdr_toggle_runtime_options();
2637 }
2638
2639 int ast_cdr_is_enabled(void)
2640 {
2641         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
2642         return ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED);
2643 }
2644
2645 int ast_cdr_backend_suspend(const char *name)
2646 {
2647         int success = -1;
2648         struct cdr_beitem *i = NULL;
2649
2650         AST_RWLIST_WRLOCK(&be_list);
2651         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2652                 if (!strcasecmp(name, i->name)) {
2653                         ast_debug(3, "Suspending CDR backend %s\n", i->name);
2654                         i->suspended = 1;
2655                         success = 0;
2656                 }
2657         }
2658         AST_RWLIST_UNLOCK(&be_list);
2659
2660         return success;
2661 }
2662
2663 int ast_cdr_backend_unsuspend(const char *name)
2664 {
2665         int success = -1;
2666         struct cdr_beitem *i = NULL;
2667
2668         AST_RWLIST_WRLOCK(&be_list);
2669         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2670                 if (!strcasecmp(name, i->name)) {
2671                         ast_debug(3, "Unsuspending CDR backend %s\n", i->name);
2672                         i->suspended = 0;
2673                         success = 0;
2674                 }
2675         }
2676         AST_RWLIST_UNLOCK(&be_list);
2677
2678         return success;
2679 }
2680
2681 int ast_cdr_register(const char *name, const char *desc, ast_cdrbe be)
2682 {
2683         struct cdr_beitem *i = NULL;
2684
2685         if (!name)
2686                 return -1;
2687
2688         if (!be) {
2689                 ast_log(LOG_WARNING, "CDR engine '%s' lacks backend\n", name);
2690                 return -1;
2691         }
2692
2693         AST_RWLIST_WRLOCK(&be_list);
2694         AST_RWLIST_TRAVERSE(&be_list, i, list) {
2695                 if (!strcasecmp(name, i->name)) {
2696                         ast_log(LOG_WARNING, "Already have a CDR backend called '%s'\n", name);
2697                         AST_RWLIST_UNLOCK(&be_list);
2698                         return -1;
2699                 }
2700         }
2701
2702         if (!(i = ast_calloc(1, sizeof(*i))))
2703                 return -1;
2704
2705         i->be = be;
2706         ast_copy_string(i->name, name, sizeof(i->name));
2707         ast_copy_string(i->desc, desc, sizeof(i->desc));
2708
2709         AST_RWLIST_INSERT_HEAD(&be_list, i, list);
2710         AST_RWLIST_UNLOCK(&be_list);
2711
2712         return 0;
2713 }
2714
2715 int ast_cdr_unregister(const char *name)
2716 {
2717         struct cdr_beitem *match = NULL;
2718         int active_count;
2719
2720         AST_RWLIST_WRLOCK(&be_list);
2721         AST_RWLIST_TRAVERSE(&be_list, match, list) {
2722                 if (!strcasecmp(name, match->name)) {
2723                         break;
2724                 }
2725         }
2726
2727         if (!match) {
2728                 AST_RWLIST_UNLOCK(&be_list);
2729                 return 0;
2730         }
2731
2732         active_count = ao2_container_count(active_cdrs_by_channel);
2733
2734         if (!match->suspended && active_count != 0) {
2735                 AST_RWLIST_UNLOCK(&be_list);
2736                 ast_log(AST_LOG_WARNING, "Unable to unregister CDR backend %s; %d CDRs are still active\n",
2737                         name, active_count);
2738                 return -1;
2739         }
2740
2741         AST_RWLIST_REMOVE(&be_list, match, list);
2742         AST_RWLIST_UNLOCK(&be_list);
2743
2744         ast_verb(2, "Unregistered '%s' CDR backend\n", name);
2745         ast_free(match);
2746
2747         return 0;
2748 }
2749
2750 struct ast_cdr *ast_cdr_dup(struct ast_cdr *cdr)
2751 {
2752         struct ast_cdr *newcdr;
2753
2754         if (!cdr) {
2755                 return NULL;
2756         }
2757         newcdr = ast_cdr_alloc();
2758         if (!newcdr) {
2759                 return NULL;
2760         }
2761
2762         *newcdr = *cdr;
2763         AST_LIST_HEAD_INIT_NOLOCK(&newcdr->varshead);
2764         copy_variables(&newcdr->varshead, &cdr->varshead);
2765         newcdr->next = NULL;
2766
2767         return newcdr;
2768 }
2769
2770 static const char *cdr_format_var_internal(struct ast_cdr *cdr, const char *name)
2771 {
2772         struct ast_var_t *variables;
2773
2774         if (ast_strlen_zero(name)) {
2775                 return NULL;
2776         }
2777
2778         AST_LIST_TRAVERSE(&cdr->varshead, variables, entries) {
2779                 if (!strcasecmp(name, ast_var_name(variables))) {
2780                         return ast_var_value(variables);
2781                 }
2782         }
2783
2784         return NULL;
2785 }
2786
2787 static void cdr_get_tv(struct timeval when, const char *fmt, char *buf, int bufsize)
2788 {
2789         if (fmt == NULL) {      /* raw mode */
2790                 snprintf(buf, bufsize, "%ld.%06ld", (long)when.tv_sec, (long)when.tv_usec);
2791         } else {
2792                 buf[0] = '\0';/* Ensure the buffer is initialized. */
2793                 if (when.tv_sec) {
2794                         struct ast_tm tm;
2795
2796                         ast_localtime(&when, &tm, NULL);
2797                         ast_strftime(buf, bufsize, fmt, &tm);
2798                 }
2799         }
2800 }
2801
2802 void ast_cdr_format_var(struct ast_cdr *cdr, const char *name, char **ret, char *workspace, int workspacelen, int raw)
2803 {
2804         const char *fmt = "%Y-%m-%d %T";
2805         const char *varbuf;
2806
2807         if (!cdr) {
2808                 return;
2809         }
2810
2811         *ret = NULL;
2812
2813         if (!strcasecmp(name, "clid")) {
2814                 ast_copy_string(workspace, cdr->clid, workspacelen);
2815         } else if (!strcasecmp(name, "src")) {
2816                 ast_copy_string(workspace, cdr->src, workspacelen);
2817         } else if (!strcasecmp(name, "dst")) {
2818                 ast_copy_string(workspace, cdr->dst, workspacelen);
2819         } else if (!strcasecmp(name, "dcontext")) {
2820                 ast_copy_string(workspace, cdr->dcontext, workspacelen);
2821         } else if (!strcasecmp(name, "channel")) {
2822                 ast_copy_string(workspace, cdr->channel, workspacelen);
2823         } else if (!strcasecmp(name, "dstchannel")) {
2824                 ast_copy_string(workspace, cdr->dstchannel, workspacelen);
2825         } else if (!strcasecmp(name, "lastapp")) {
2826                 ast_copy_string(workspace, cdr->lastapp, workspacelen);
2827         } else if (!strcasecmp(name, "lastdata")) {
2828                 ast_copy_string(workspace, cdr->lastdata, workspacelen);
2829         } else if (!strcasecmp(name, "start")) {
2830                 cdr_get_tv(cdr->start, raw ? NULL : fmt, workspace, workspacelen);
2831         } else if (!strcasecmp(name, "answer")) {
2832                 cdr_get_tv(cdr->answer, raw ? NULL : fmt, workspace, workspacelen);
2833         } else if (!strcasecmp(name, "end")) {
2834                 cdr_get_tv(cdr->end, raw ? NULL : fmt, workspace, workspacelen);
2835         } else if (!strcasecmp(name, "duration")) {
2836                 snprintf(workspace, workspacelen, "%ld", cdr->end.tv_sec != 0 ? cdr->duration : (long)ast_tvdiff_ms(ast_tvnow(), cdr->start) / 1000);
2837         } else if (!strcasecmp(name, "billsec")) {
2838                 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);
2839         } else if (!strcasecmp(name, "disposition")) {
2840                 if (raw) {
2841                         snprintf(workspace, workspacelen, "%ld", cdr->disposition);
2842                 } else {
2843                         ast_copy_string(workspace, ast_cdr_disp2str(cdr->disposition), workspacelen);
2844                 }
2845         } else if (!strcasecmp(name, "amaflags")) {
2846                 if (raw) {
2847                         snprintf(workspace, workspacelen, "%ld", cdr->amaflags);
2848                 } else {
2849                         ast_copy_string(workspace, ast_channel_amaflags2string(cdr->amaflags), workspacelen);
2850                 }
2851         } else if (!strcasecmp(name, "accountcode")) {
2852                 ast_copy_string(workspace, cdr->accountcode, workspacelen);
2853         } else if (!strcasecmp(name, "peeraccount")) {
2854                 ast_copy_string(workspace, cdr->peeraccount, workspacelen);
2855         } else if (!strcasecmp(name, "uniqueid")) {
2856                 ast_copy_string(workspace, cdr->uniqueid, workspacelen);
2857         } else if (!strcasecmp(name, "linkedid")) {
2858                 ast_copy_string(workspace, cdr->linkedid, workspacelen);
2859         } else if (!strcasecmp(name, "userfield")) {
2860                 ast_copy_string(workspace, cdr->userfield, workspacelen);
2861         } else if (!strcasecmp(name, "sequence")) {
2862                 snprintf(workspace, workspacelen, "%d", cdr->sequence);
2863         } else if ((varbuf = cdr_format_var_internal(cdr, name))) {
2864                 ast_copy_string(workspace, varbuf, workspacelen);
2865         } else {
2866                 workspace[0] = '\0';
2867         }
2868
2869         if (!ast_strlen_zero(workspace)) {
2870                 *ret = workspace;
2871         }
2872 }
2873
2874 /*
2875  * \internal
2876  * \brief Callback that finds all CDRs that reference a particular channel by name
2877  */
2878 static int cdr_object_select_all_by_name_cb(void *obj, void *arg, int flags)
2879 {
2880         struct cdr_object *cdr = obj;
2881         const char *name = arg;
2882
2883         if (!strcasecmp(cdr->party_a.snapshot->name, name) ||
2884                         (cdr->party_b.snapshot && !strcasecmp(cdr->party_b.snapshot->name, name))) {
2885                 return CMP_MATCH;
2886         }
2887         return 0;
2888 }
2889
2890 /*
2891  * \internal
2892  * \brief Callback that finds a CDR by channel name
2893  */
2894 static int cdr_object_get_by_name_cb(void *obj, void *arg, int flags)
2895 {
2896         struct cdr_object *cdr = obj;
2897         const char *name = arg;
2898
2899         if (!strcasecmp(cdr->party_a.snapshot->name, name)) {
2900                 return CMP_MATCH;
2901         }
2902         return 0;
2903 }
2904
2905 /* Read Only CDR variables */
2906 static const char * const cdr_readonly_vars[] = {
2907         "clid",
2908         "src",
2909         "dst",
2910         "dcontext",
2911         "channel",
2912         "dstchannel",
2913         "lastapp",
2914         "lastdata",
2915         "start",
2916         "answer",
2917         "end",
2918         "duration",
2919         "billsec",
2920         "disposition",
2921         "amaflags",
2922         "accountcode",
2923         "uniqueid",
2924         "linkedid",
2925         "userfield",
2926         "sequence",
2927         NULL
2928 };
2929
2930 int ast_cdr_setvar(const char *channel_name, const char *name, const char *value)
2931 {
2932         struct cdr_object *cdr;
2933         struct cdr_object *it_cdr;
2934         struct ao2_iterator *it_cdrs;
2935         char *arg = ast_strdupa(channel_name);
2936         int x;
2937
2938         for (x = 0; cdr_readonly_vars[x]; x++) {
2939                 if (!strcasecmp(name, cdr_readonly_vars[x])) {
2940                         ast_log(LOG_ERROR, "Attempt to set the '%s' read-only variable!\n", name);
2941                         return -1;
2942                 }
2943         }
2944
2945         it_cdrs = ao2_callback(active_cdrs_by_channel, OBJ_MULTIPLE, cdr_object_select_all_by_name_cb, arg);
2946         if (!it_cdrs) {
2947                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
2948                 return -1;
2949         }
2950
2951         for (; (cdr = ao2_iterator_next(it_cdrs)); ao2_unlock(cdr), ao2_cleanup(cdr)) {
2952                 ao2_lock(cdr);
2953                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
2954                         struct varshead *headp = NULL;
2955
2956                         if (it_cdr->fn_table == &finalized_state_fn_table) {
2957                                 continue;
2958                         }
2959                         if (!strcasecmp(channel_name, it_cdr->party_a.snapshot->name)) {
2960                                 headp = &it_cdr->party_a.variables;
2961                         } else if (it_cdr->party_b.snapshot
2962                                 && !strcasecmp(channel_name, it_cdr->party_b.snapshot->name)) {
2963                                 headp = &it_cdr->party_b.variables;
2964                         }
2965                         if (headp) {
2966                                 set_variable(headp, name, value);
2967                         }
2968                 }
2969         }
2970         ao2_iterator_destroy(it_cdrs);
2971
2972         return 0;
2973 }
2974
2975 /*!
2976  * \brief Format a variable on a \ref cdr_object
2977  */
2978 static void cdr_object_format_var_internal(struct cdr_object *cdr, const char *name, char *value, size_t length)
2979 {
2980         struct ast_var_t *variable;
2981
2982         AST_LIST_TRAVERSE(&cdr->party_a.variables, variable, entries) {
2983                 if (!strcasecmp(name, ast_var_name(variable))) {
2984                         ast_copy_string(value, ast_var_value(variable), length);
2985                         return;
2986                 }
2987         }
2988
2989         *value = '\0';
2990 }
2991
2992 /*!
2993  * \brief Format one of the standard properties on a \ref cdr_object
2994  */
2995 static int cdr_object_format_property(struct cdr_object *cdr_obj, const char *name, char *value, size_t length)
2996 {
2997         struct ast_channel_snapshot *party_a = cdr_obj->party_a.snapshot;
2998         struct ast_channel_snapshot *party_b = cdr_obj->party_b.snapshot;
2999
3000         if (!strcasecmp(name, "clid")) {
3001                 ast_callerid_merge(value, length, party_a->caller_name, party_a->caller_number, "");
3002         } else if (!strcasecmp(name, "src")) {
3003                 ast_copy_string(value, party_a->caller_number, length);
3004         } else if (!strcasecmp(name, "dst")) {
3005                 ast_copy_string(value, party_a->exten, length);
3006         } else if (!strcasecmp(name, "dcontext")) {
3007                 ast_copy_string(value, party_a->context, length);
3008         } else if (!strcasecmp(name, "channel")) {
3009                 ast_copy_string(value, party_a->name, length);
3010         } else if (!strcasecmp(name, "dstchannel")) {
3011                 if (party_b) {
3012                         ast_copy_string(value, party_b->name, length);
3013                 } else {
3014                         ast_copy_string(value, "", length);
3015                 }
3016         } else if (!strcasecmp(name, "lastapp")) {
3017                 ast_copy_string(value, party_a->appl, length);
3018         } else if (!strcasecmp(name, "lastdata")) {
3019                 ast_copy_string(value, party_a->data, length);
3020         } else if (!strcasecmp(name, "start")) {
3021                 cdr_get_tv(cdr_obj->start, NULL, value, length);
3022         } else if (!strcasecmp(name, "answer")) {
3023                 cdr_get_tv(cdr_obj->answer, NULL, value, length);
3024         } else if (!strcasecmp(name, "end")) {
3025                 cdr_get_tv(cdr_obj->end, NULL, value, length);
3026         } else if (!strcasecmp(name, "duration")) {
3027                 snprintf(value, length, "%ld", cdr_object_get_duration(cdr_obj));
3028         } else if (!strcasecmp(name, "billsec")) {
3029                 snprintf(value, length, "%ld", cdr_object_get_billsec(cdr_obj));
3030         } else if (!strcasecmp(name, "disposition")) {
3031                 snprintf(value, length, "%u", cdr_obj->disposition);
3032         } else if (!strcasecmp(name, "amaflags")) {
3033                 snprintf(value, length, "%d", party_a->amaflags);
3034         } else if (!strcasecmp(name, "accountcode")) {
3035                 ast_copy_string(value, party_a->accountcode, length);
3036         } else if (!strcasecmp(name, "peeraccount")) {
3037                 if (party_b) {
3038                         ast_copy_string(value, party_b->accountcode, length);
3039                 } else {
3040                         ast_copy_string(value, "", length);
3041                 }
3042         } else if (!strcasecmp(name, "uniqueid")) {
3043                 ast_copy_string(value, party_a->uniqueid, length);
3044         } else if (!strcasecmp(name, "linkedid")) {
3045                 ast_copy_string(value, cdr_obj->linkedid, length);
3046         } else if (!strcasecmp(name, "userfield")) {
3047                 ast_copy_string(value, cdr_obj->party_a.userfield, length);
3048         } else if (!strcasecmp(name, "sequence")) {
3049                 snprintf(value, length, "%u", cdr_obj->sequence);
3050         } else {
3051                 return 1;
3052         }
3053
3054         return 0;
3055 }
3056
3057 /*! \internal
3058  * \brief Look up and retrieve a CDR object by channel name
3059  * \param name The name of the channel
3060  * \retval NULL on error
3061  * \retval The \ref cdr_object for the channel on success, with the reference
3062  *      count bumped by one.
3063  */
3064 static struct cdr_object *cdr_object_get_by_name(const char *name)
3065 {
3066         char *param;
3067
3068         if (ast_strlen_zero(name)) {
3069                 return NULL;
3070         }
3071
3072         param = ast_strdupa(name);
3073         return ao2_callback(active_cdrs_by_channel, 0, cdr_object_get_by_name_cb, param);
3074 }
3075
3076 int ast_cdr_getvar(const char *channel_name, const char *name, char *value, size_t length)
3077 {
3078         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3079         struct cdr_object *cdr_obj;
3080
3081         if (!cdr) {
3082                 ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3083                 return 1;
3084         }
3085
3086         if (ast_strlen_zero(name)) {
3087                 return 1;
3088         }
3089
3090         ao2_lock(cdr);
3091
3092         cdr_obj = cdr->last;
3093         if (cdr_object_format_property(cdr_obj, name, value, length)) {
3094                 /* Property failed; attempt variable */
3095                 cdr_object_format_var_internal(cdr_obj, name, value, length);
3096         }
3097
3098         ao2_unlock(cdr);
3099
3100         return 0;
3101 }
3102
3103 int ast_cdr_serialize_variables(const char *channel_name, struct ast_str **buf, char delim, char sep)
3104 {
3105         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3106         struct cdr_object *it_cdr;
3107         struct ast_var_t *variable;
3108         const char *var;
3109         char workspace[256];
3110         int total = 0, x = 0, i;
3111
3112         if (!cdr) {
3113                 RAII_VAR(struct module_config *, mod_cfg,
3114                          ao2_global_obj_ref(module_configs), ao2_cleanup);
3115
3116                 if (ast_test_flag(&mod_cfg->general->settings, CDR_ENABLED)) {
3117                         ast_log(AST_LOG_ERROR, "Unable to find CDR for channel %s\n", channel_name);
3118                 }
3119
3120                 return 0;
3121         }
3122
3123         ast_str_reset(*buf);
3124
3125         ao2_lock(cdr);
3126         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3127                 if (++x > 1)
3128                         ast_str_append(buf, 0, "\n");
3129
3130                 AST_LIST_TRAVERSE(&it_cdr->party_a.variables, variable, entries) {
3131                         if (!(var = ast_var_name(variable))) {
3132                                 continue;
3133                         }
3134
3135                         if (ast_str_append(buf, 0, "level %d: %s%c%s%c", x, var, delim, S_OR(ast_var_value(variable), ""), sep) < 0) {
3136                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3137                                 break;
3138                         }
3139
3140                         total++;
3141                 }
3142
3143                 for (i = 0; cdr_readonly_vars[i]; i++) {
3144                         if (cdr_object_format_property(it_cdr, cdr_readonly_vars[i], workspace, sizeof(workspace))) {
3145                                 /* Unhandled read-only CDR variable. */
3146                                 ast_assert(0);
3147                                 continue;
3148                         }
3149
3150                         if (!ast_strlen_zero(workspace)
3151                                 && ast_str_append(buf, 0, "level %d: %s%c%s%c", x, cdr_readonly_vars[i], delim, workspace, sep) < 0) {
3152                                 ast_log(LOG_ERROR, "Data Buffer Size Exceeded!\n");
3153                                 break;
3154                         }
3155                         total++;
3156                 }
3157         }
3158         ao2_unlock(cdr);
3159         return total;
3160 }
3161
3162 void ast_cdr_free(struct ast_cdr *cdr)
3163 {
3164         while (cdr) {
3165                 struct ast_cdr *next = cdr->next;
3166
3167                 free_variables(&cdr->varshead);
3168                 ast_free(cdr);
3169                 cdr = next;
3170         }
3171 }
3172
3173 struct ast_cdr *ast_cdr_alloc(void)
3174 {
3175         struct ast_cdr *x;
3176
3177         x = ast_calloc(1, sizeof(*x));
3178         return x;
3179 }
3180
3181 const char *ast_cdr_disp2str(int disposition)
3182 {
3183         switch (disposition) {
3184         case AST_CDR_NULL:
3185                 return "NO ANSWER"; /* by default, for backward compatibility */
3186         case AST_CDR_NOANSWER:
3187                 return "NO ANSWER";
3188         case AST_CDR_FAILED:
3189                 return "FAILED";
3190         case AST_CDR_BUSY:
3191                 return "BUSY";
3192         case AST_CDR_ANSWERED:
3193                 return "ANSWERED";
3194         case AST_CDR_CONGESTION:
3195                 return "CONGESTION";
3196         }
3197         return "UNKNOWN";
3198 }
3199
3200 struct party_b_userfield_update {
3201         const char *channel_name;
3202         const char *userfield;
3203 };
3204
3205 /*! \brief Callback used to update the userfield on Party B on all CDRs */
3206 static int cdr_object_update_party_b_userfield_cb(void *obj, void *arg, int flags)
3207 {
3208         struct cdr_object *cdr = obj;
3209         struct party_b_userfield_update *info = arg;
3210         struct cdr_object *it_cdr;
3211         for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3212                 if (it_cdr->fn_table == &finalized_state_fn_table) {
3213                         continue;
3214                 }
3215                 if (it_cdr->party_b.snapshot
3216                         && !strcasecmp(it_cdr->party_b.snapshot->name, info->channel_name)) {
3217                         strcpy(it_cdr->party_b.userfield, info->userfield);
3218                 }
3219         }
3220         return 0;
3221 }
3222
3223 void ast_cdr_setuserfield(const char *channel_name, const char *userfield)
3224 {
3225         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3226         struct party_b_userfield_update party_b_info = {
3227                         .channel_name = channel_name,
3228                         .userfield = userfield,
3229         };
3230         struct cdr_object *it_cdr;
3231
3232         /* Handle Party A */
3233         if (cdr) {
3234                 ao2_lock(cdr);
3235                 for (it_cdr = cdr; it_cdr; it_cdr = it_cdr->next) {
3236                         if (it_cdr->fn_table == &finalized_state_fn_table) {
3237                                 continue;
3238                         }
3239                         strcpy(it_cdr->party_a.userfield, userfield);
3240                 }
3241                 ao2_unlock(cdr);
3242         }
3243
3244         /* Handle Party B */
3245         ao2_callback(active_cdrs_by_channel, OBJ_NODATA,
3246                         cdr_object_update_party_b_userfield_cb,
3247                         &party_b_info);
3248
3249 }
3250
3251 static void post_cdr(struct ast_cdr *cdr)
3252 {
3253         RAII_VAR(struct module_config *, mod_cfg, ao2_global_obj_ref(module_configs), ao2_cleanup);
3254         struct cdr_beitem *i;
3255
3256         for (; cdr ; cdr = cdr->next) {
3257                 /* For people, who don't want to see unanswered single-channel events */
3258                 if (!ast_test_flag(&mod_cfg->general->settings, CDR_UNANSWERED) &&
3259                                 cdr->disposition < AST_CDR_ANSWERED &&
3260                                 (ast_strlen_zero(cdr->channel) || ast_strlen_zero(cdr->dstchannel))) {
3261                         ast_debug(1, "Skipping CDR  for %s since we weren't answered\n", cdr->channel);
3262                         continue;
3263                 }
3264
3265                 if (ast_test_flag(cdr, AST_CDR_FLAG_DISABLE)) {
3266                         continue;
3267                 }
3268                 AST_RWLIST_RDLOCK(&be_list);
3269                 AST_RWLIST_TRAVERSE(&be_list, i, list) {
3270                         if (!i->suspended) {
3271                                 i->be(cdr);
3272                         }
3273                 }
3274                 AST_RWLIST_UNLOCK(&be_list);
3275         }
3276 }
3277
3278 int ast_cdr_set_property(const char *channel_name, enum ast_cdr_options option)
3279 {
3280         RAII_VAR(struct cdr_object *, cdr, cdr_object_get_by_name(channel_name), ao2_cleanup);
3281         struct cdr_object *it_cdr;
3282
3283         if (!cdr) {
3284                 return -1;
3285         }