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