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