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