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