Skip to content
Snippets Groups Projects
app_agent_pool.c 74.3 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    /*
     * Asterisk -- An open source telephony toolkit.
     *
     * Copyright (C) 2013 Digium, Inc.
     *
     * Richard Mudgett <rmudgett@digium.com>
     *
     * See http://www.asterisk.org for more information about
     * the Asterisk project. Please do not directly contact
     * any of the maintainers of this project for assistance;
     * the project provides a web site, mailing lists and IRC
     * channels for your use.
     *
     * This program is free software, distributed under the terms of
     * the GNU General Public License Version 2. See the LICENSE file
     * at the top of the source tree.
     */
    
    /*!
     * \file
     * \brief Call center agent pool.
     *
     * \author Richard Mudgett <rmudgett@digium.com>
     *
     * See Also:
     * \arg \ref AstCREDITS
     * \arg \ref Config_agent
     */
    /*** MODULEINFO
    	<support_level>core</support_level>
     ***/
    
    
    #include "asterisk.h"
    
    ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
    
    #include "asterisk/cli.h"
    #include "asterisk/app.h"
    #include "asterisk/pbx.h"
    #include "asterisk/module.h"
    #include "asterisk/channel.h"
    #include "asterisk/bridging.h"
    #include "asterisk/bridging_basic.h"
    #include "asterisk/config_options.h"
    #include "asterisk/features_config.h"
    #include "asterisk/astobj2.h"
    #include "asterisk/stringfields.h"
    #include "asterisk/stasis_channels.h"
    
    /*** DOCUMENTATION
    	<application name="AgentLogin" language="en_US">
    		<synopsis>
    			Login an agent.
    		</synopsis>
    		<syntax argsep=",">
    			<parameter name="AgentId" required="true" />
    			<parameter name="options">
    				<optionlist>
    					<option name="s">
    						<para>silent login - do not announce the login ok segment after
    						agent logged on.</para>
    					</option>
    				</optionlist>
    			</parameter>
    		</syntax>
    		<description>
    			<para>Login an agent to the system.  Any agent authentication is assumed to
    			already be done by dialplan.  While logged in, the agent can receive calls
    			and will hear the sound file specified by the config option custom_beep
    			when a new call comes in for the agent.  Login failures will continue in
    			the dialplan with <variable>AGENT_STATUS</variable> set.</para>
    			<para>Before logging in, you can setup on the real agent channel the
    			CHANNEL(dtmf-features) an agent will have when talking to a caller
    			and you can setup on the channel running this application the
    			CONNECTEDLINE() information the agent will see while waiting for a
    			caller.</para>
    			<para><variable>AGENT_STATUS</variable> enumeration values:</para>
    			<enumlist>
    				<enum name = "INVALID"><para>The specified agent is invalid.</para></enum>
    				<enum name = "ALREADY_LOGGED_IN"><para>The agent is already logged in.</para></enum>
    			</enumlist>
    			<note><para>The Agents:<replaceable>AgentId</replaceable> device state is
    			available to monitor the status of the agent.</para></note>
    		</description>
    		<see-also>
    			<ref type="application">Authenticate</ref>
    			<ref type="application">Queue</ref>
    			<ref type="application">AddQueueMember</ref>
    			<ref type="application">RemoveQueueMember</ref>
    			<ref type="application">PauseQueueMember</ref>
    			<ref type="application">UnpauseQueueMember</ref>
    			<ref type="function">AGENT</ref>
    			<ref type="function">CHANNEL(dtmf-features)</ref>
    			<ref type="function">CONNECTEDLINE()</ref>
    			<ref type="filename">agents.conf</ref>
    			<ref type="filename">queues.conf</ref>
    		</see-also>
    	</application>
    	<application name="AgentRequest" language="en_US">
    		<synopsis>
    			Request an agent to connect with the channel.
    		</synopsis>
    		<syntax argsep=",">
    			<parameter name="AgentId" required="true" />
    		</syntax>
    		<description>
    			<para>Request an agent to connect with the channel.  Failure to find and
    			alert an agent will continue in the dialplan with <variable>AGENT_STATUS</variable> set.</para>
    			<para><variable>AGENT_STATUS</variable> enumeration values:</para>
    			<enumlist>
    				<enum name = "INVALID"><para>The specified agent is invalid.</para></enum>
    				<enum name = "NOT_LOGGED_IN"><para>The agent is not available.</para></enum>
    				<enum name = "BUSY"><para>The agent is on another call.</para></enum>
    				<enum name = "ERROR"><para>Alerting the agent failed.</para></enum>
    			</enumlist>
    		</description>
    		<see-also>
    			<ref type="application">AgentLogin</ref>
    		</see-also>
    	</application>
    	<function name="AGENT" language="en_US">
    		<synopsis>
    			Gets information about an Agent
    		</synopsis>
    		<syntax argsep=":">
    			<parameter name="AgentId" required="true" />
    			<parameter name="item">
    				<para>The valid items to retrieve are:</para>
    				<enumlist>
    					<enum name="status">
    						<para>(default) The status of the agent (LOGGEDIN | LOGGEDOUT)</para>
    					</enum>
    					<enum name="password">
    						<para>Deprecated.  The dialplan handles any agent authentication.</para>
    					</enum>
    					<enum name="name">
    						<para>The name of the agent</para>
    					</enum>
    					<enum name="mohclass">
    						<para>MusicOnHold class</para>
    					</enum>
    					<enum name="channel">
    						<para>The name of the active channel for the Agent (AgentLogin)</para>
    					</enum>
    					<enum name="fullchannel">
    						<para>The untruncated name of the active channel for the Agent (AgentLogin)</para>
    					</enum>
    				</enumlist>
    			</parameter>
    		</syntax>
    		<description></description>
    	</function>
    	<manager name="Agents" language="en_US">
    		<synopsis>
    			Lists agents and their status.
    		</synopsis>
    		<syntax>
    			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
    		</syntax>
    		<description>
    			<para>Will list info about all defined agents.</para>
    		</description>
    		<see-also>
    			<ref type="managerEvent">Agents</ref>
    			<ref type="managerEvent">AgentsComplete</ref>
    		</see-also>
    	</manager>
    	<managerEvent language="en_US" name="Agents">
    		<managerEventInstance class="EVENT_FLAG_AGENT">
    			<synopsis>
    				Response event in a series to the Agents AMI action containing
    				information about a defined agent.
    			</synopsis>
    			<syntax>
    				<parameter name="Agent">
    					<para>Agent ID of the agent.</para>
    				</parameter>
    				<parameter name="Name">
    					<para>User friendly name of the agent.</para>
    				</parameter>
    				<parameter name="Status">
    					<para>Current status of the agent.</para>
    					<para>The valid values are:</para>
    					<enumlist>
    						<enum name="AGENT_LOGGEDOFF" />
    						<enum name="AGENT_IDLE" />
    						<enum name="AGENT_ONCALL" />
    					</enumlist>
    				</parameter>
    				<parameter name="TalkingToChan">
    					<para><variable>BRIDGEPEER</variable> value on agent channel.</para>
    					<para>Present if Status value is <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="CallStarted">
    					<para>Epoche time when the agent started talking with the caller.</para>
    					<para>Present if Status value is <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="LoggedInTime">
    					<para>Epoche time when the agent logged in.</para>
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="Channel">
    					<xi:include xpointer="xpointer(/docs/managerEvent[@name='Newchannel']/managerEventInstance/syntax/parameter[@name='Channel']/para)" />
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="ChannelState">
    					<xi:include xpointer="xpointer(/docs/managerEvent[@name='Newchannel']/managerEventInstance/syntax/parameter[@name='ChannelState']/para)" />
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="ChannelStateDesc">
    					<xi:include xpointer="xpointer(/docs/managerEvent[@name='Newchannel']/managerEventInstance/syntax/parameter[@name='ChannelStateDesc']/para)" />
    					<xi:include xpointer="xpointer(/docs/managerEvent[@name='Newchannel']/managerEventInstance/syntax/parameter[@name='ChannelStateDesc']/enumlist)" />
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="CallerIDNum">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="CallerIDName">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="ConnectedLineNum">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="ConnectedLineName">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="AccountCode">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="Context">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="Exten">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="Priority">
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<parameter name="Uniqueid">
    					<xi:include xpointer="xpointer(/docs/managerEvent[@name='Newchannel']/managerEventInstance/syntax/parameter[@name='Uniqueid']/para)" />
    					<para>Present if Status value is <literal>AGENT_IDLE</literal> or <literal>AGENT_ONCALL</literal>.</para>
    				</parameter>
    				<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
    			</syntax>
    			<see-also>
    				<ref type="manager">Agents</ref>
    			</see-also>
    		</managerEventInstance>
    	</managerEvent>
    	<managerEvent language="en_US" name="AgentsComplete">
    		<managerEventInstance class="EVENT_FLAG_AGENT">
    			<synopsis>
    				Final response event in a series of events to the Agents AMI action.
    			</synopsis>
    			<syntax>
    				<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
    			</syntax>
    			<see-also>
    				<ref type="manager">Agents</ref>
    			</see-also>
    		</managerEventInstance>
    	</managerEvent>
    	<manager name="AgentLogoff" language="en_US">
    		<synopsis>
    			Sets an agent as no longer logged in.
    		</synopsis>
    		<syntax>
    			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
    			<parameter name="Agent" required="true">
    				<para>Agent ID of the agent to log off.</para>
    			</parameter>
    			<parameter name="Soft">
    				<para>Set to <literal>true</literal> to not hangup existing calls.</para>
    			</parameter>
    		</syntax>
    		<description>
    			<para>Sets an agent as no longer logged in.</para>
    		</description>
    	</manager>
    	<configInfo name="app_agent_pool" language="en_US">
    		<synopsis>Agent pool applications</synopsis>
    		<description>
    			<note><para>Option changes take effect on agent login or after an agent
    			disconnects from a call.</para></note>
    		</description>
    		<configFile name="agents.conf">
    			<configObject name="global">
    				<synopsis>Unused, but reserved.</synopsis>
    			</configObject>
    			<configObject name="agent-id">
    				<synopsis>Configure an agent for the pool.</synopsis>
    				<description>
    					<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    				</description>
    				<configOption name="ackcall">
    					<synopsis>Enable to require the agent to acknowledge a call.</synopsis>
    					<description>
    						<para>Enable to require the agent to give a DTMF acknowledgement
    						when the agent receives a call.</para>
    						<note><para>The option is overridden by <variable>AGENTACKCALL</variable> on agent login.</para></note>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="acceptdtmf">
    					<synopsis>DTMF key sequence the agent uses to acknowledge a call.</synopsis>
    					<description>
    						<note><para>The option is overridden by <variable>AGENTACCEPTDTMF</variable> on agent login.</para></note>
    						<note><para>The option is ignored unless the ackcall option is enabled.</para></note>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="autologoff">
    					<synopsis>Time the agent has to acknowledge a call before being logged off.</synopsis>
    					<description>
    						<para>Set how many seconds a call for the agent has to wait for the
    						agent to acknowledge the call before the agent is automatically
    						logged off.  If set to zero then the call will wait forever for
    						the agent to acknowledge.</para>
    						<note><para>The option is overridden by <variable>AGENTAUTOLOGOFF</variable> on agent login.</para></note>
    						<note><para>The option is ignored unless the ackcall option is enabled.</para></note>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="wrapuptime">
    					<synopsis>Minimum time the agent has between calls.</synopsis>
    					<description>
    						<para>Set the minimum amount of time in milliseconds after
    						disconnecting a call before the agent can receive a new call.</para>
    						<note><para>The option is overridden by <variable>AGENTWRAPUPTIME</variable> on agent login.</para></note>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="musiconhold">
    					<synopsis>Music on hold class the agent listens to between calls.</synopsis>
    					<description>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="recordagentcalls">
    					<synopsis>Enable to automatically record calls the agent takes.</synopsis>
    					<description>
    						<para>Enable recording calls the agent takes automatically by
    						invoking the automixmon DTMF feature when the agent connects
    						to a caller.  See <filename>features.conf.sample</filename> for information about
    						the automixmon feature.</para>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="custom_beep">
    					<synopsis>Sound file played to alert the agent when a call is present.</synopsis>
    					<description>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    				<configOption name="fullname">
    					<synopsis>A friendly name for the agent used in log messages.</synopsis>
    					<description>
    						<xi:include xpointer="xpointer(/docs/configInfo[@name='app_agent_pool']/description/note)" />
    					</description>
    				</configOption>
    			</configObject>
    		</configFile>
    	</configInfo>
     ***/
    
    /* ------------------------------------------------------------------- */
    
    #define AST_MAX_BUF	256
    
    /*! Maximum wait time (in ms) for the custom_beep file to play announcing the caller. */
    #define CALLER_SAFETY_TIMEOUT_TIME	(2 * 60 * 1000)
    
    /*! Number of seconds to wait for local channel optimizations to complete. */
    #define LOGIN_WAIT_TIMEOUT_TIME		5
    
    static const char app_agent_login[] = "AgentLogin";
    static const char app_agent_request[] = "AgentRequest";
    
    /*! Agent config parameters. */
    struct agent_cfg {
    	AST_DECLARE_STRING_FIELDS(
    		/*! Identification of the agent.  (agents config container key) */
    		AST_STRING_FIELD(username);
    		/*! Name of agent for logging and querying purposes */
    		AST_STRING_FIELD(full_name);
    
    		/*!
    		 * \brief DTMF string for an agent to accept a call.
    		 *
    		 * \note The channel variable AGENTACCEPTDTMF overrides on login.
    		 */
    		AST_STRING_FIELD(dtmf_accept);
    		/*! Beep sound file to use.  Alert the agent a call is waiting. */
    		AST_STRING_FIELD(beep_sound);
    		/*! MOH class to use while agent waiting for call. */
    		AST_STRING_FIELD(moh);
    	);
    	/*!
    	 * \brief Number of seconds for agent to ack a call before being logged off.
    	 *
    	 * \note The channel variable AGENTAUTOLOGOFF overrides on login.
    	 * \note If zero then timer is disabled.
    	 */
    	unsigned int auto_logoff;
    	/*!
    	 * \brief Time after a call in ms before the agent can get a new call.
    	 *
    	 * \note The channel variable AGENTWRAPUPTIME overrides on login.
    	 */
    	unsigned int wrapup_time;
    	/*!
    	 * \brief TRUE if agent needs to ack a call to accept it.
    	 *
    	 * \note The channel variable AGENTACKCALL overrides on login.
    	 */
    	int ack_call;
    	/*! TRUE if agent calls are automatically recorded. */
    	int record_agent_calls;
    };
    
    /*!
     * \internal
     * \brief Agent config ao2 container sort function.
     * \since 12.0.0
     *
     * \param obj_left pointer to the (user-defined part) of an object.
     * \param obj_right pointer to the (user-defined part) of an object.
     * \param flags flags from ao2_callback()
     *   OBJ_POINTER - if set, 'obj_right', is an object.
     *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
     *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
     *
     * \retval <0 if obj_left < obj_right
     * \retval =0 if obj_left == obj_right
     * \retval >0 if obj_left > obj_right
     */
    static int agent_cfg_sort_cmp(const void *obj_left, const void *obj_right, int flags)
    {
    	const struct agent_cfg *cfg_left = obj_left;
    	const struct agent_cfg *cfg_right = obj_right;
    	const char *right_key = obj_right;
    	int cmp;
    
    	switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
    	default:
    	case OBJ_POINTER:
    		right_key = cfg_right->username;
    		/* Fall through */
    	case OBJ_KEY:
    		cmp = strcmp(cfg_left->username, right_key);
    		break;
    	case OBJ_PARTIAL_KEY:
    		cmp = strncmp(cfg_left->username, right_key, strlen(right_key));
    		break;
    	}
    	return cmp;
    }
    
    static void agent_cfg_destructor(void *vdoomed)
    {
    	struct agent_cfg *doomed = vdoomed;
    
    	ast_string_field_free_memory(doomed);
    }
    
    static void *agent_cfg_alloc(const char *name)
    {
    	struct agent_cfg *cfg;
    
    	cfg = ao2_alloc_options(sizeof(*cfg), agent_cfg_destructor,
    		AO2_ALLOC_OPT_LOCK_NOLOCK);
    	if (!cfg || ast_string_field_init(cfg, 64)) {
    		return NULL;
    	}
    	ast_string_field_set(cfg, username, name);
    	return cfg;
    }
    
    static void *agent_cfg_find(struct ao2_container *agents, const char *username)
    {
    	return ao2_find(agents, username, OBJ_KEY);
    }
    
    /*! Agents configuration */
    struct agents_cfg {
    	/*! Master configured agents container. */
    	struct ao2_container *agents;
    };
    
    static struct aco_type agent_type = {
    	.type = ACO_ITEM,
    	.name = "agent-id",
    	.category_match = ACO_BLACKLIST,
    	.category = "^(general|agents)$",
    	.item_alloc = agent_cfg_alloc,
    	.item_find = agent_cfg_find,
    	.item_offset = offsetof(struct agents_cfg, agents),
    };
    
    static struct aco_type *agent_types[] = ACO_TYPES(&agent_type);
    
    /* The general category is reserved, but unused */
    static struct aco_type general_type = {
    	.type = ACO_GLOBAL,
    	.name = "global",
    	.category_match = ACO_WHITELIST,
    	.category = "^general$",
    };
    
    static struct aco_file agents_conf = {
    	.filename = "agents.conf",
    	.types = ACO_TYPES(&general_type, &agent_type),
    };
    
    static AO2_GLOBAL_OBJ_STATIC(cfg_handle);
    
    static void agents_cfg_destructor(void *vdoomed)
    {
    	struct agents_cfg *doomed = vdoomed;
    
    	ao2_cleanup(doomed->agents);
    	doomed->agents = NULL;
    }
    
    /*!
     * \internal
     * \brief Create struct agents_cfg object.
     * \since 12.0.0
     *
     * \note A lock is not needed for the object or any secondary
     * created cfg objects.  These objects are immutable after the
     * config is loaded and applied.
     *
     * \retval New struct agents_cfg object.
     * \retval NULL on error.
     */
    static void *agents_cfg_alloc(void)
    {
    	struct agents_cfg *cfg;
    
    	cfg = ao2_alloc_options(sizeof(*cfg), agents_cfg_destructor,
    		AO2_ALLOC_OPT_LOCK_NOLOCK);
    	if (!cfg) {
    		return NULL;
    	}
    	cfg->agents = ao2_container_alloc_rbtree(AO2_ALLOC_OPT_LOCK_NOLOCK,
    		AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT, agent_cfg_sort_cmp, NULL);
    	if (!cfg->agents) {
    		ao2_ref(cfg, -1);
    		cfg = NULL;
    	}
    	return cfg;
    }
    
    static void agents_post_apply_config(void);
    
    CONFIG_INFO_STANDARD(cfg_info, cfg_handle, agents_cfg_alloc,
    	.files = ACO_FILES(&agents_conf),
    	.post_apply_config = agents_post_apply_config,
    );
    
    static void destroy_config(void)
    {
    	ao2_global_obj_release(cfg_handle);
    	aco_info_destroy(&cfg_info);
    }
    
    static int load_config(void)
    {
    	if (aco_info_init(&cfg_info)) {
    		return -1;
    	}
    
    	/* Agent options */
    	aco_option_register(&cfg_info, "ackcall", ACO_EXACT, agent_types, "no", OPT_BOOL_T, 1, FLDSET(struct agent_cfg, ack_call));
    	aco_option_register(&cfg_info, "acceptdtmf", ACO_EXACT, agent_types, "#", OPT_STRINGFIELD_T, 1, STRFLDSET(struct agent_cfg, dtmf_accept));
    	aco_option_register(&cfg_info, "autologoff", ACO_EXACT, agent_types, "0", OPT_UINT_T, 0, FLDSET(struct agent_cfg, auto_logoff));
    	aco_option_register(&cfg_info, "wrapuptime", ACO_EXACT, agent_types, "0", OPT_UINT_T, 0, FLDSET(struct agent_cfg, wrapup_time));
    	aco_option_register(&cfg_info, "musiconhold", ACO_EXACT, agent_types, "default", OPT_STRINGFIELD_T, 0, STRFLDSET(struct agent_cfg, moh));
    	aco_option_register(&cfg_info, "recordagentcalls", ACO_EXACT, agent_types, "no", OPT_BOOL_T, 1, FLDSET(struct agent_cfg, record_agent_calls));
    	aco_option_register(&cfg_info, "custom_beep", ACO_EXACT, agent_types, "beep", OPT_STRINGFIELD_T, 1, STRFLDSET(struct agent_cfg, beep_sound));
    	aco_option_register(&cfg_info, "fullname", ACO_EXACT, agent_types, NULL, OPT_STRINGFIELD_T, 0, STRFLDSET(struct agent_cfg, full_name));
    
    	if (aco_process_config(&cfg_info, 0) == ACO_PROCESS_ERROR) {
    		goto error;
    	}
    
    	return 0;
    
    error:
    	destroy_config();
    	return -1;
    }
    
    enum agent_state {
    	/*! The agent is defined but an agent is not present. */
    	AGENT_STATE_LOGGED_OUT,
    	/*! Forced initial login wait to allow any local channel optimizations to happen. */
    	AGENT_STATE_PROBATION_WAIT,
    	/*! The agent is ready for a call. */
    	AGENT_STATE_READY_FOR_CALL,
    	/*! The agent has a call waiting to connect. */
    	AGENT_STATE_CALL_PRESENT,
    	/*! The agent needs to ack the call. */
    	AGENT_STATE_CALL_WAIT_ACK,
    	/*! The agent is connected with a call. */
    	AGENT_STATE_ON_CALL,
    	/*! The agent is resting between calls. */
    	AGENT_STATE_CALL_WRAPUP,
    	/*! The agent is being kicked out. */
    	AGENT_STATE_LOGGING_OUT,
    };
    
    /*! Agent config option override flags. */
    enum agent_override_flags {
    	AGENT_FLAG_ACK_CALL = (1 << 0),
    	AGENT_FLAG_DTMF_ACCEPT = (1 << 1),
    	AGENT_FLAG_AUTO_LOGOFF = (1 << 2),
    	AGENT_FLAG_WRAPUP_TIME = (1 << 3),
    };
    
    /*! \brief Structure representing an agent. */
    struct agent_pvt {
    	AST_DECLARE_STRING_FIELDS(
    		/*! Identification of the agent.  (agents container key) */
    		AST_STRING_FIELD(username);
    		/*! Login override DTMF string for an agent to accept a call. */
    		AST_STRING_FIELD(override_dtmf_accept);
    	);
    	/*! Connected line information to send when reentering the holding bridge. */
    	struct ast_party_connected_line waiting_colp;
    	/*! Flags show if settings were overridden by channel vars. */
    	unsigned int flags;
    	/*! Login override number of seconds for agent to ack a call before being logged off. */
    	unsigned int override_auto_logoff;
    	/*! Login override time after a call in ms before the agent can get a new call. */
    	unsigned int override_wrapup_time;
    	/*! Login override if agent needs to ack a call to accept it. */
    	unsigned int override_ack_call:1;
    
    	/*! TRUE if the agent is requested to logoff when the current call ends. */
    	unsigned int deferred_logoff:1;
    
    	/*! Mark and sweep config update to determine if an agent is dead. */
    	unsigned int the_mark:1;
    	/*!
    	 * \brief TRUE if the agent is no longer configured and is being destroyed.
    	 *
    	 * \note Agents cannot log in if they are dead.
    	 */
    	unsigned int dead:1;
    
    	/*! Agent control state variable. */
    	enum agent_state state;
    	/*! Custom device state of agent. */
    	enum ast_device_state devstate;
    
    	/*! When agent first logged in */
    	time_t login_start;
    	/*! When agent login probation started. */
    	time_t probation_start;
    	/*! When call started */
    	time_t call_start;
    	/*! When ack timer started */
    	struct timeval ack_time;
    	/*! When last disconnected */
    	struct timeval last_disconnect;
    
    	/*! Caller is waiting in this bridge for agent to join. (Holds ref) */
    	struct ast_bridge *caller_bridge;
    	/*! Agent is logged in with this channel. (Holds ref) (NULL if not logged in.) */
    	struct ast_channel *logged;
    	/*! Active config values from config file. (Holds ref) */
    	struct agent_cfg *cfg;
    };
    
    /*! Container of defined agents. */
    static struct ao2_container *agents;
    
    /*!
     * \brief Lock the agent.
     *
     * \param agent Agent to lock
     *
     * \return Nothing
     */
    #define agent_lock(agent)	_agent_lock(agent, __FILE__, __PRETTY_FUNCTION__, __LINE__, #agent)
    static inline void _agent_lock(struct agent_pvt *agent, const char *file, const char *function, int line, const char *var)
    {
    	__ao2_lock(agent, AO2_LOCK_REQ_MUTEX, file, function, line, var);
    }
    
    /*!
     * \brief Unlock the agent.
     *
     * \param agent Agent to unlock
     *
     * \return Nothing
     */
    #define agent_unlock(agent)	_agent_unlock(agent, __FILE__, __PRETTY_FUNCTION__, __LINE__, #agent)
    static inline void _agent_unlock(struct agent_pvt *agent, const char *file, const char *function, int line, const char *var)
    {
    	__ao2_unlock(agent, file, function, line, var);
    }
    
    /*!
     * \internal
     * \brief Obtain the agent logged in channel lock if it exists.
     * \since 12.0.0
     *
     * \param agent Pointer to the LOCKED agent_pvt.
     *
     * \note Assumes the agent lock is already obtained.
     *
     * \note Defined locking order is channel lock then agent lock.
     *
     * \return Nothing
     */
    static struct ast_channel *agent_lock_logged(struct agent_pvt *agent)
    {
    	struct ast_channel *logged;
    
    	for (;;) {
    		if (!agent->logged) { /* No owner. Nothing to do. */
    			return NULL;
    		}
    
    		/* If we don't ref the logged, it could be killed when we unlock the agent. */
    		logged = ast_channel_ref(agent->logged);
    
    		/* Locking logged requires us to lock channel, then agent. */
    		agent_unlock(agent);
    		ast_channel_lock(logged);
    		agent_lock(agent);
    
    		/* Check if logged changed during agent unlock period */
    		if (logged != agent->logged) {
    			/* Channel changed. Unref and do another pass. */
    			ast_channel_unlock(logged);
    			ast_channel_unref(logged);
    		} else {
    			/* Channel stayed the same. Return it. */
    			return logged;
    		}
    	}
    }
    
    /*!
     * \internal
     * \brief Get the Agent:agent_id device state.
     * \since 12.0.0
     *
     * \param agent_id Username of the agent.
     *
     * \details
     * Search the agents container for the agent and return the
     * current state.
     *
     * \return Device state of the agent.
     */
    static enum ast_device_state agent_pvt_devstate_get(const char *agent_id)
    {
    	RAII_VAR(struct agent_pvt *, agent, ao2_find(agents, agent_id, OBJ_KEY), ao2_cleanup);
    
    	if (agent) {
    		return agent->devstate;
    	}
    	return AST_DEVICE_INVALID;
    }
    
    /*!
     * \internal
     * \brief Request an agent device state be updated.
     * \since 12.0.0
     *
     * \param agent_id Which agent needs the device state updated.
     *
     * \return Nothing
     */
    static void agent_devstate_changed(const char *agent_id)
    {
    	ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "Agent:%s", agent_id);
    }
    
    static void agent_pvt_destructor(void *vdoomed)
    {
    	struct agent_pvt *doomed = vdoomed;
    
    	/* Make sure device state reflects agent destruction. */
    	if (!ast_strlen_zero(doomed->username)) {
    		ast_debug(1, "Agent %s: Destroyed.\n", doomed->username);
    		agent_devstate_changed(doomed->username);
    	}
    
    	ast_party_connected_line_free(&doomed->waiting_colp);
    	if (doomed->caller_bridge) {
    		ast_bridge_destroy(doomed->caller_bridge);
    		doomed->caller_bridge = NULL;
    	}
    	if (doomed->logged) {
    		doomed->logged = ast_channel_unref(doomed->logged);
    	}
    	ao2_cleanup(doomed->cfg);
    	doomed->cfg = NULL;
    	ast_string_field_free_memory(doomed);
    }
    
    static struct agent_pvt *agent_pvt_new(struct agent_cfg *cfg)
    {
    	struct agent_pvt *agent;
    
    	agent = ao2_alloc(sizeof(*agent), agent_pvt_destructor);
    	if (!agent) {
    		return NULL;
    	}
    	if (ast_string_field_init(agent, 32)) {
    		ao2_ref(agent, -1);
    		return NULL;
    	}
    	ast_string_field_set(agent, username, cfg->username);
    	ast_party_connected_line_init(&agent->waiting_colp);
    	ao2_ref(cfg, +1);
    	agent->cfg = cfg;
    	agent->devstate = AST_DEVICE_UNAVAILABLE;
    	return agent;
    }
    
    /*!
     * \internal
     * \brief Agents ao2 container sort function.
     * \since 12.0.0
     *
     * \param obj_left pointer to the (user-defined part) of an object.
     * \param obj_right pointer to the (user-defined part) of an object.
     * \param flags flags from ao2_callback()
     *   OBJ_POINTER - if set, 'obj_right', is an object.
     *   OBJ_KEY - if set, 'obj_right', is a search key item that is not an object.
     *   OBJ_PARTIAL_KEY - if set, 'obj_right', is a partial search key item that is not an object.
     *
     * \retval <0 if obj_left < obj_right
     * \retval =0 if obj_left == obj_right
     * \retval >0 if obj_left > obj_right
     */
    static int agent_pvt_sort_cmp(const void *obj_left, const void *obj_right, int flags)
    {
    	const struct agent_pvt *agent_left = obj_left;
    	const struct agent_pvt *agent_right = obj_right;
    	const char *right_key = obj_right;
    	int cmp;
    
    	switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
    	default:
    	case OBJ_POINTER:
    		right_key = agent_right->username;
    		/* Fall through */
    	case OBJ_KEY:
    		cmp = strcmp(agent_left->username, right_key);
    		break;
    	case OBJ_PARTIAL_KEY:
    		cmp = strncmp(agent_left->username, right_key, strlen(right_key));
    		break;
    	}
    	return cmp;
    }
    
    /*!
     * \internal
     * \brief ao2_find() callback function.
     * \since 12.0.0
     *
     * Usage:
     * found = ao2_find(agents, agent, OBJ_POINTER);
     * found = ao2_find(agents, "agent-id", OBJ_KEY);
     * found = ao2_find(agents, agent->logged, 0);
     */
    static int agent_pvt_cmp(void *obj, void *arg, int flags)
    {
    	const struct agent_pvt *agent = obj;
    	int cmp;
    
    	switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
    	case OBJ_POINTER:
    	case OBJ_KEY:
    	case OBJ_PARTIAL_KEY:
    		cmp = CMP_MATCH;
    		break;
    	default:
    		if (agent->logged == arg) {
    			cmp = CMP_MATCH;
    		} else {
    			cmp = 0;
    		}
    		break;
    	}
    	return cmp;
    }
    
    static int agent_mark(void *obj, void *arg, int flags)
    {
    	struct agent_pvt *agent = obj;
    
    	agent_lock(agent);
    	agent->the_mark = 1;
    	agent_unlock(agent);
    	return 0;
    }
    
    static void agents_mark(void)
    {
    	ao2_callback(agents, 0, agent_mark, NULL);
    }
    
    static int agent_sweep(void *obj, void *arg, int flags)
    {
    	struct agent_pvt *agent = obj;
    	int cmp = 0;
    
    	agent_lock(agent);
    	if (agent->the_mark) {
    		agent->the_mark = 0;
    		agent->dead = 1;
    		/* Unlink dead agents immediately. */
    		cmp = CMP_MATCH;
    	}
    	agent_unlock(agent);
    	return cmp;
    }
    
    static void agents_sweep(void)
    {
    	struct ao2_iterator *iter;
    	struct agent_pvt *agent;
    	struct ast_channel *logged;
    
    	iter = ao2_callback(agents, OBJ_MULTIPLE | OBJ_UNLINK, agent_sweep, NULL);
    	if (!iter) {
    		return;
    	}
    	for (; (agent = ao2_iterator_next(iter)); ao2_ref(agent, -1)) {
    		agent_lock(agent);
    		if (agent->logged) {
    			logged = ast_channel_ref(agent->logged);
    		} else {
    			logged = NULL;
    		}
    		agent_unlock(agent);
    		if (!logged) {
    			continue;
    		}
    		ast_log(LOG_NOTICE,
    			"Forced logoff of agent %s(%s).  Agent no longer configured.\n",
    			agent->username, ast_channel_name(logged));
    		ast_softhangup(logged, AST_SOFTHANGUP_EXPLICIT);
    		ast_channel_unref(logged);
    	}
    	ao2_iterator_destroy(iter);
    }
    
    static void agents_post_apply_config(void)
    {
    	struct ao2_iterator iter;
    	struct agent_cfg *cfg;
    	RAII_VAR(struct agents_cfg *, cfgs, ao2_global_obj_ref(cfg_handle), ao2_cleanup);
    
    	ast_assert(cfgs != NULL);
    
    	agents_mark();
    	iter = ao2_iterator_init(cfgs->agents, 0);
    	for (; (cfg = ao2_iterator_next(&iter)); ao2_ref(cfg, -1)) {
    		RAII_VAR(struct agent_pvt *, agent, ao2_find(agents, cfg->username, OBJ_KEY), ao2_cleanup);
    
    		if (agent) {
    			agent_lock(agent);
    			agent->the_mark = 0;
    			if (!agent->logged) {
    				struct agent_cfg *cfg_old;
    
    				/* Replace the config of agents not logged in. */
    				cfg_old = agent->cfg;
    				ao2_ref(cfg, +1);
    				agent->cfg = cfg;
    				ao2_cleanup(cfg_old);
    			}
    			agent_unlock(agent);
    			continue;
    		}
    		agent = agent_pvt_new(cfg);
    		if (!agent) {
    			continue;
    		}
    		ao2_link(agents, agent);
    		ast_debug(1, "Agent %s: Created.\n", agent->username);
    		agent_devstate_changed(agent->username);
    	}
    	ao2_iterator_destroy(&iter);
    	agents_sweep();
    }
    
    static int agent_logoff_request(const char *agent_id, int soft)