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