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