Wed Aug 11 01:04:59 2010

Asterisk developer's documentation


app_meetme.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2007, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * SLA Implementation by:
00009  * Russell Bryant <russell@digium.com>
00010  *
00011  * See http://www.asterisk.org for more information about
00012  * the Asterisk project. Please do not directly contact
00013  * any of the maintainers of this project for assistance;
00014  * the project provides a web site, mailing lists and IRC
00015  * channels for your use.
00016  *
00017  * This program is free software, distributed under the terms of
00018  * the GNU General Public License Version 2. See the LICENSE file
00019  * at the top of the source tree.
00020  */
00021 
00022 /*! \file
00023  *
00024  * \brief Meet me conference bridge and Shared Line Appearances
00025  *
00026  * \author Mark Spencer <markster@digium.com>
00027  * \author (SLA) Russell Bryant <russell@digium.com>
00028  * 
00029  * \ingroup applications
00030  */
00031 
00032 /*** MODULEINFO
00033    <depend>dahdi</depend>
00034  ***/
00035 
00036 #include "asterisk.h"
00037 
00038 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 278464 $")
00039 
00040 #include <dahdi/user.h>
00041 
00042 #include "asterisk/lock.h"
00043 #include "asterisk/file.h"
00044 #include "asterisk/channel.h"
00045 #include "asterisk/pbx.h"
00046 #include "asterisk/module.h"
00047 #include "asterisk/config.h"
00048 #include "asterisk/app.h"
00049 #include "asterisk/dsp.h"
00050 #include "asterisk/musiconhold.h"
00051 #include "asterisk/manager.h"
00052 #include "asterisk/cli.h"
00053 #include "asterisk/say.h"
00054 #include "asterisk/utils.h"
00055 #include "asterisk/translate.h"
00056 #include "asterisk/ulaw.h"
00057 #include "asterisk/astobj2.h"
00058 #include "asterisk/devicestate.h"
00059 #include "asterisk/dial.h"
00060 #include "asterisk/causes.h"
00061 #include "asterisk/paths.h"
00062 
00063 #include "enter.h"
00064 #include "leave.h"
00065 
00066 /*** DOCUMENTATION
00067    <application name="MeetMe" language="en_US">
00068       <synopsis>
00069          MeetMe conference bridge.
00070       </synopsis>
00071       <syntax>
00072          <parameter name="confno">
00073             <para>The conference number</para>
00074          </parameter>
00075          <parameter name="options">
00076             <optionlist>
00077                <option name="a">
00078                   <para>Set admin mode.</para>
00079                </option>
00080                <option name="A">
00081                   <para>Set marked mode.</para>
00082                </option>
00083                <option name="b">
00084                   <para>Run AGI script specified in <variable>MEETME_AGI_BACKGROUND</variable>
00085                   Default: <literal>conf-background.agi</literal>.</para>
00086                   <note><para>This does not work with non-DAHDI channels in the same
00087                   conference).</para></note>
00088                </option>
00089                <option name="c">
00090                   <para>Announce user(s) count on joining a conference.</para>
00091                </option>
00092                <option name="C">
00093                   <para>Continue in dialplan when kicked out of conference.</para>
00094                </option>
00095                <option name="d">
00096                   <para>Dynamically add conference.</para>
00097                </option>
00098                <option name="D">
00099                   <para>Dynamically add conference, prompting for a PIN.</para>
00100                </option>
00101                <option name="e">
00102                   <para>Select an empty conference.</para>
00103                </option>
00104                <option name="E">
00105                   <para>Select an empty pinless conference.</para>
00106                </option>
00107                <option name="F">
00108                   <para>Pass DTMF through the conference.</para>
00109                </option>
00110                <option name="i">
00111                   <para>Announce user join/leave with review.</para>
00112                </option>
00113                <option name="I">
00114                   <para>Announce user join/leave without review.</para>
00115                </option>
00116                <option name="l">
00117                   <para>Set listen only mode (Listen only, no talking).</para>
00118                </option>
00119                <option name="m">
00120                   <para>Set initially muted.</para>
00121                </option>
00122                <option name="M" hasparams="optional">
00123                   <para>Enable music on hold when the conference has a single caller. Optionally,
00124                   specify a musiconhold class to use. If one is not provided, it will use the
00125                   channel's currently set music class, or <literal>default</literal>.</para>
00126                   <argument name="class" required="true" />
00127                </option>
00128                <option name="o">
00129                   <para>Set talker optimization - treats talkers who aren't speaking as
00130                   being muted, meaning (a) No encode is done on transmission and (b)
00131                   Received audio that is not registered as talking is omitted causing no
00132                   buildup in background noise.</para>
00133                </option>
00134                <option name="p" hasparams="optional">
00135                   <para>Allow user to exit the conference by pressing <literal>#</literal> (default)
00136                   or any of the defined keys. If keys contain <literal>*</literal> this will override
00137                   option <literal>s</literal>. The key used is set to channel variable
00138                   <variable>MEETME_EXIT_KEY</variable>.</para>
00139                   <argument name="keys" required="true" />
00140                </option>
00141                <option name="P">
00142                   <para>Always prompt for the pin even if it is specified.</para>
00143                </option>
00144                <option name="q">
00145                   <para>Quiet mode (don't play enter/leave sounds).</para>
00146                </option>
00147                <option name="r">
00148                   <para>Record conference (records as <variable>MEETME_RECORDINGFILE</variable>
00149                   using format <variable>MEETME_RECORDINGFORMAT</variable>. Default filename is
00150                   <literal>meetme-conf-rec-${CONFNO}-${UNIQUEID}</literal> and the default format is
00151                   wav.</para>
00152                </option>
00153                <option name="s">
00154                   <para>Present menu (user or admin) when <literal>*</literal> is received
00155                   (send to menu).</para>
00156                </option>
00157                <option name="t">
00158                   <para>Set talk only mode. (Talk only, no listening).</para>
00159                </option>
00160                <option name="T">
00161                   <para>Set talker detection (sent to manager interface and meetme list).</para>
00162                </option>
00163                <option name="w" hasparams="optional">
00164                   <para>Wait until the marked user enters the conference.</para>
00165                   <argument name="secs" required="true" />
00166                </option>
00167                <option name="x">
00168                   <para>Close the conference when last marked user exits</para>
00169                </option>
00170                <option name="X">
00171                   <para>Allow user to exit the conference by entering a valid single digit
00172                   extension <variable>MEETME_EXIT_CONTEXT</variable> or the current context
00173                   if that variable is not defined.</para>
00174                </option>
00175                <option name="1">
00176                   <para>Do not play message when first person enters</para>
00177                </option>
00178                <option name="S">
00179                   <para>Kick the user <replaceable>x</replaceable> seconds <emphasis>after</emphasis> he entered into
00180                   the conference.</para>
00181                   <argument name="x" required="true" />
00182                </option>
00183                <option name="L" argsep=":">
00184                   <para>Limit the conference to <replaceable>x</replaceable> ms. Play a warning when
00185                   <replaceable>y</replaceable> ms are left. Repeat the warning every <replaceable>z</replaceable> ms.
00186                   The following special variables can be used with this option:</para>
00187                   <variablelist>
00188                      <variable name="CONF_LIMIT_TIMEOUT_FILE">
00189                         <para>File to play when time is up.</para>
00190                      </variable>
00191                      <variable name="CONF_LIMIT_WARNING_FILE">
00192                         <para>File to play as warning if <replaceable>y</replaceable> is defined. The
00193                         default is to say the time remaining.</para>
00194                      </variable>
00195                   </variablelist>
00196                   <argument name="x" />
00197                   <argument name="y" />
00198                   <argument name="z" />
00199                </option>
00200             </optionlist>
00201          </parameter>
00202          <parameter name="pin" />
00203       </syntax>
00204       <description>
00205          <para>Enters the user into a specified MeetMe conference.  If the <replaceable>confno</replaceable>
00206          is omitted, the user will be prompted to enter one.  User can exit the conference by hangup, or
00207          if the <literal>p</literal> option is specified, by pressing <literal>#</literal>.</para>
00208          <note><para>The DAHDI kernel modules and at least one hardware driver (or dahdi_dummy)
00209          must be present for conferencing to operate properly. In addition, the chan_dahdi channel driver
00210          must be loaded for the <literal>i</literal> and <literal>r</literal> options to operate at
00211          all.</para></note>
00212       </description>
00213       <see-also>
00214          <ref type="application">MeetMeCount</ref>
00215          <ref type="application">MeetMeAdmin</ref>
00216          <ref type="application">MeetMeChannelAdmin</ref>
00217       </see-also>
00218    </application>
00219    <application name="MeetMeCount" language="en_US">
00220       <synopsis>
00221          MeetMe participant count.
00222       </synopsis>
00223       <syntax>
00224          <parameter name="confno" required="true">
00225             <para>Conference number.</para>
00226          </parameter>
00227          <parameter name="var" />
00228       </syntax>
00229       <description>
00230          <para>Plays back the number of users in the specified MeetMe conference.
00231          If <replaceable>var</replaceable> is specified, playback will be skipped and the value
00232          will be returned in the variable. Upon application completion, MeetMeCount will hangup
00233          the channel, unless priority <literal>n+1</literal> exists, in which case priority progress will
00234          continue.</para>
00235       </description>
00236       <see-also>
00237          <ref type="application">MeetMe</ref>
00238       </see-also>
00239    </application>
00240    <application name="MeetMeAdmin" language="en_US">
00241       <synopsis>
00242          MeetMe conference administration.
00243       </synopsis>
00244       <syntax>
00245          <parameter name="confno" required="true" />
00246          <parameter name="command" required="true">
00247             <optionlist>
00248                <option name="e">
00249                   <para>Eject last user that joined.</para>
00250                </option>
00251                <option name="E">
00252                   <para>Extend conference end time, if scheduled.</para>
00253                </option>
00254                <option name="k">
00255                   <para>Kick one user out of conference.</para>
00256                </option>
00257                <option name="K">
00258                   <para>Kick all users out of conference.</para>
00259                </option>
00260                <option name="l">
00261                   <para>Unlock conference.</para>
00262                </option>
00263                <option name="L">
00264                   <para>Lock conference.</para>
00265                </option>
00266                <option name="m">
00267                   <para>Unmute one user.</para>
00268                </option>
00269                <option name="M">
00270                   <para>Mute one user.</para>
00271                </option>
00272                <option name="n">
00273                   <para>Unmute all users in the conference.</para>
00274                </option>
00275                <option name="N">
00276                   <para>Mute all non-admin users in the conference.</para>
00277                </option>
00278                <option name="r">
00279                   <para>Reset one user's volume settings.</para>
00280                </option>
00281                <option name="R">
00282                   <para>Reset all users volume settings.</para>
00283                </option>
00284                <option name="s">
00285                   <para>Lower entire conference speaking volume.</para>
00286                </option>
00287                <option name="S">
00288                   <para>Raise entire conference speaking volume.</para>
00289                </option>
00290                <option name="t">
00291                   <para>Lower one user's talk volume.</para>
00292                </option>
00293                <option name="T">
00294                   <para>Raise one user's talk volume.</para>
00295                </option>
00296                <option name="u">
00297                   <para>Lower one user's listen volume.</para>
00298                </option>
00299                <option name="U">
00300                   <para>Raise one user's listen volume.</para>
00301                </option>
00302                <option name="v">
00303                   <para>Lower entire conference listening volume.</para>
00304                </option>
00305                <option name="V">
00306                   <para>Raise entire conference listening volume.</para>
00307                </option>
00308             </optionlist>
00309          </parameter>
00310          <parameter name="user" />
00311       </syntax>
00312       <description>
00313          <para>Run admin <replaceable>command</replaceable> for conference <replaceable>confno</replaceable>.</para>
00314          <para>Will additionally set the variable <variable>MEETMEADMINSTATUS</variable> with one of
00315          the following values:</para>
00316          <variablelist>
00317             <variable name="MEETMEADMINSTATUS">
00318                <value name="NOPARSE">
00319                   Invalid arguments.
00320                </value>
00321                <value name="NOTFOUND">
00322                   User specified was not found.
00323                </value>
00324                <value name="FAILED">
00325                   Another failure occurred.
00326                </value>
00327                <value name="OK">
00328                   The operation was completed successfully.
00329                </value>
00330             </variable>
00331          </variablelist>
00332       </description>
00333       <see-also>
00334          <ref type="application">MeetMe</ref>
00335       </see-also>
00336    </application>
00337    <application name="MeetMeChannelAdmin" language="en_US">
00338       <synopsis>
00339          MeetMe conference Administration (channel specific).
00340       </synopsis>
00341       <syntax>
00342          <parameter name="channel" required="true" />
00343          <parameter name="command" required="true">
00344             <optionlist>
00345                <option name="k">
00346                   <para>Kick the specified user out of the conference he is in.</para>
00347                </option>
00348                <option name="m">
00349                   <para>Unmute the specified user.</para>
00350                </option>
00351                <option name="M">
00352                   <para>Mute the specified user.</para>
00353                </option>
00354             </optionlist>
00355          </parameter>
00356       </syntax>
00357       <description>
00358          <para>Run admin <replaceable>command</replaceable> for a specific
00359          <replaceable>channel</replaceable> in any coference.</para>
00360       </description>
00361    </application>
00362    <application name="SLAStation" language="en_US">
00363       <synopsis>
00364          Shared Line Appearance Station.
00365       </synopsis>
00366       <syntax>
00367          <parameter name="station" required="true">
00368             <para>Station name</para>
00369          </parameter>
00370       </syntax>
00371       <description>
00372          <para>This application should be executed by an SLA station. The argument depends
00373          on how the call was initiated. If the phone was just taken off hook, then the argument
00374          <replaceable>station</replaceable> should be just the station name. If the call was
00375          initiated by pressing a line key, then the station name should be preceded by an underscore
00376          and the trunk name associated with that line button.</para>
00377          <para>For example: <literal>station1_line1</literal></para>
00378          <para>On exit, this application will set the variable <variable>SLASTATION_STATUS</variable> to
00379          one of the following values:</para>
00380          <variablelist>
00381             <variable name="SLASTATION_STATUS">
00382                <value name="FAILURE" />
00383                <value name="CONGESTION" />
00384                <value name="SUCCESS" />
00385             </variable>
00386          </variablelist>
00387       </description>
00388    </application>
00389    <application name="SLATrunk" language="en_US">
00390       <synopsis>
00391          Shared Line Appearance Trunk.
00392       </synopsis>
00393       <syntax>
00394          <parameter name="trunk" required="true">
00395             <para>Trunk name</para>
00396          </parameter>
00397          <parameter name="options">
00398             <optionlist>
00399                <option name="M" hasparams="optional">
00400                   <para>Play back the specified MOH <replaceable>class</replaceable>
00401                   instead of ringing</para>
00402                   <argument name="class" required="true" />
00403                </option>
00404             </optionlist>
00405          </parameter>
00406       </syntax>
00407       <description>
00408          <para>This application should be executed by an SLA trunk on an inbound call. The channel calling
00409          this application should correspond to the SLA trunk with the name <replaceable>trunk</replaceable>
00410          that is being passed as an argument.</para>
00411          <para>On exit, this application will set the variable <variable>SLATRUNK_STATUS</variable> to
00412          one of the following values:</para>
00413          <variablelist>
00414             <variable name="SLATRUNK_STATUS">
00415                <value name="FAILURE" />
00416                <value name="SUCCESS" />
00417                <value name="UNANSWERED" />
00418                <value name="RINGTIMEOUT" />
00419             </variable>
00420          </variablelist>
00421       </description>
00422    </application>
00423  ***/
00424 
00425 #define CONFIG_FILE_NAME "meetme.conf"
00426 #define SLA_CONFIG_FILE  "sla.conf"
00427 
00428 /*! each buffer is 20ms, so this is 640ms total */
00429 #define DEFAULT_AUDIO_BUFFERS  32
00430 
00431 /*! String format for scheduled conferences */
00432 #define DATE_FORMAT "%Y-%m-%d %H:%M:%S"
00433 
00434 enum {
00435    ADMINFLAG_MUTED =     (1 << 1), /*!< User is muted */
00436    ADMINFLAG_SELFMUTED = (1 << 2), /*!< User muted self */
00437    ADMINFLAG_KICKME =    (1 << 3),  /*!< User has been kicked */
00438    /*! User has requested to speak */
00439    ADMINFLAG_T_REQUEST = (1 << 4),
00440 };
00441 
00442 #define MEETME_DELAYDETECTTALK     300
00443 #define MEETME_DELAYDETECTENDTALK  1000
00444 
00445 #define AST_FRAME_BITS  32
00446 
00447 enum volume_action {
00448    VOL_UP,
00449    VOL_DOWN
00450 };
00451 
00452 enum entrance_sound {
00453    ENTER,
00454    LEAVE
00455 };
00456 
00457 enum recording_state {
00458    MEETME_RECORD_OFF,
00459    MEETME_RECORD_STARTED,
00460    MEETME_RECORD_ACTIVE,
00461    MEETME_RECORD_TERMINATE
00462 };
00463 
00464 #define CONF_SIZE  320
00465 
00466 enum {
00467    /*! user has admin access on the conference */
00468    CONFFLAG_ADMIN = (1 << 0),
00469    /*! If set the user can only receive audio from the conference */
00470    CONFFLAG_MONITOR = (1 << 1),
00471    /*! If set asterisk will exit conference when key defined in p() option is pressed */
00472    CONFFLAG_KEYEXIT = (1 << 2),
00473    /*! If set asterisk will provide a menu to the user when '*' is pressed */
00474    CONFFLAG_STARMENU = (1 << 3),
00475    /*! If set the use can only send audio to the conference */
00476    CONFFLAG_TALKER = (1 << 4),
00477    /*! If set there will be no enter or leave sounds */
00478    CONFFLAG_QUIET = (1 << 5),
00479    /*! If set, when user joins the conference, they will be told the number 
00480     *  of users that are already in */
00481    CONFFLAG_ANNOUNCEUSERCOUNT = (1 << 6),
00482    /*! Set to run AGI Script in Background */
00483    CONFFLAG_AGI = (1 << 7),
00484    /*! Set to have music on hold when user is alone in conference */
00485    CONFFLAG_MOH = (1 << 8),
00486    /*! If set the MeetMe will return if all marked with this flag left */
00487    CONFFLAG_MARKEDEXIT = (1 << 9),
00488    /*! If set, the MeetMe will wait until a marked user enters */
00489    CONFFLAG_WAITMARKED = (1 << 10),
00490    /*! If set, the MeetMe will exit to the specified context */
00491    CONFFLAG_EXIT_CONTEXT = (1 << 11),
00492    /*! If set, the user will be marked */
00493    CONFFLAG_MARKEDUSER = (1 << 12),
00494    /*! If set, user will be ask record name on entry of conference */
00495    CONFFLAG_INTROUSER = (1 << 13),
00496    /*! If set, the MeetMe will be recorded */
00497    CONFFLAG_RECORDCONF = (1<< 14),
00498    /*! If set, the user will be monitored if the user is talking or not */
00499    CONFFLAG_MONITORTALKER = (1 << 15),
00500    CONFFLAG_DYNAMIC = (1 << 16),
00501    CONFFLAG_DYNAMICPIN = (1 << 17),
00502    CONFFLAG_EMPTY = (1 << 18),
00503    CONFFLAG_EMPTYNOPIN = (1 << 19),
00504    CONFFLAG_ALWAYSPROMPT = (1 << 20),
00505    /*! If set, treat talking users as muted users */
00506    CONFFLAG_OPTIMIZETALKER = (1 << 21),
00507    /*! If set, won't speak the extra prompt when the first person 
00508     *  enters the conference */
00509    CONFFLAG_NOONLYPERSON = (1 << 22),
00510    /*! If set, user will be asked to record name on entry of conference 
00511     *  without review */
00512    CONFFLAG_INTROUSERNOREVIEW = (1 << 23),
00513    /*! If set, the user will be initially self-muted */
00514    CONFFLAG_STARTMUTED = (1 << 24),
00515    /*! Pass DTMF through the conference */
00516    CONFFLAG_PASS_DTMF = (1 << 25),
00517    CONFFLAG_SLA_STATION = (1 << 26),
00518    CONFFLAG_SLA_TRUNK = (1 << 27),
00519    /*! If set, the user should continue in the dialplan if kicked out */
00520    CONFFLAG_KICK_CONTINUE = (1 << 28),
00521    CONFFLAG_DURATION_STOP = (1 << 29),
00522    CONFFLAG_DURATION_LIMIT = (1 << 30),
00523    /*! Do not write any audio to this channel until the state is up. */
00524    CONFFLAG_NO_AUDIO_UNTIL_UP = (1 << 31),
00525 };
00526 
00527 enum {
00528    OPT_ARG_WAITMARKED = 0,
00529    OPT_ARG_EXITKEYS   = 1,
00530    OPT_ARG_DURATION_STOP = 2,
00531    OPT_ARG_DURATION_LIMIT = 3,
00532    OPT_ARG_MOH_CLASS = 4,
00533    OPT_ARG_ARRAY_SIZE = 5,
00534 };
00535 
00536 AST_APP_OPTIONS(meetme_opts, BEGIN_OPTIONS
00537    AST_APP_OPTION('A', CONFFLAG_MARKEDUSER ),
00538    AST_APP_OPTION('a', CONFFLAG_ADMIN ),
00539    AST_APP_OPTION('b', CONFFLAG_AGI ),
00540    AST_APP_OPTION('c', CONFFLAG_ANNOUNCEUSERCOUNT ),
00541    AST_APP_OPTION('C', CONFFLAG_KICK_CONTINUE),
00542    AST_APP_OPTION('D', CONFFLAG_DYNAMICPIN ),
00543    AST_APP_OPTION('d', CONFFLAG_DYNAMIC ),
00544    AST_APP_OPTION('E', CONFFLAG_EMPTYNOPIN ),
00545    AST_APP_OPTION('e', CONFFLAG_EMPTY ),
00546    AST_APP_OPTION('F', CONFFLAG_PASS_DTMF ),
00547    AST_APP_OPTION('i', CONFFLAG_INTROUSER ),
00548    AST_APP_OPTION('I', CONFFLAG_INTROUSERNOREVIEW ),
00549    AST_APP_OPTION_ARG('M', CONFFLAG_MOH, OPT_ARG_MOH_CLASS ),
00550    AST_APP_OPTION('m', CONFFLAG_STARTMUTED ),
00551    AST_APP_OPTION('o', CONFFLAG_OPTIMIZETALKER ),
00552    AST_APP_OPTION('P', CONFFLAG_ALWAYSPROMPT ),
00553    AST_APP_OPTION_ARG('p', CONFFLAG_KEYEXIT, OPT_ARG_EXITKEYS ),
00554    AST_APP_OPTION('q', CONFFLAG_QUIET ),
00555    AST_APP_OPTION('r', CONFFLAG_RECORDCONF ),
00556    AST_APP_OPTION('s', CONFFLAG_STARMENU ),
00557    AST_APP_OPTION('T', CONFFLAG_MONITORTALKER ),
00558    AST_APP_OPTION('l', CONFFLAG_MONITOR ),
00559    AST_APP_OPTION('t', CONFFLAG_TALKER ),
00560    AST_APP_OPTION_ARG('w', CONFFLAG_WAITMARKED, OPT_ARG_WAITMARKED ),
00561    AST_APP_OPTION('X', CONFFLAG_EXIT_CONTEXT ),
00562    AST_APP_OPTION('x', CONFFLAG_MARKEDEXIT ),
00563    AST_APP_OPTION('1', CONFFLAG_NOONLYPERSON ),
00564    AST_APP_OPTION_ARG('S', CONFFLAG_DURATION_STOP, OPT_ARG_DURATION_STOP),
00565    AST_APP_OPTION_ARG('L', CONFFLAG_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
00566 END_OPTIONS );
00567 
00568 static const char *app = "MeetMe";
00569 static const char *app2 = "MeetMeCount";
00570 static const char *app3 = "MeetMeAdmin";
00571 static const char *app4 = "MeetMeChannelAdmin";
00572 static const char *slastation_app = "SLAStation";
00573 static const char *slatrunk_app = "SLATrunk";
00574 
00575 /* Lookup RealTime conferences based on confno and current time */
00576 static int rt_schedule;
00577 static int fuzzystart;
00578 static int earlyalert;
00579 static int endalert;
00580 static int extendby;
00581 
00582 /* Log participant count to the RealTime backend */
00583 static int rt_log_members;
00584 
00585 #define MAX_CONFNUM 80
00586 #define MAX_PIN     80
00587 #define OPTIONS_LEN 100
00588 
00589 /* Enough space for "<conference #>,<pin>,<admin pin>" followed by a 0 byte. */
00590 #define MAX_SETTINGS (MAX_CONFNUM + MAX_PIN + MAX_PIN + 3)
00591 
00592 enum announcetypes {
00593    CONF_HASJOIN,
00594    CONF_HASLEFT
00595 };
00596 
00597 struct announce_listitem {
00598    AST_LIST_ENTRY(announce_listitem) entry;
00599    char namerecloc[PATH_MAX];          /*!< Name Recorded file Location */
00600    char language[MAX_LANGUAGE];
00601    struct ast_channel *confchan;
00602    int confusers;
00603    enum announcetypes announcetype;
00604 };
00605 
00606 /*! \brief The MeetMe Conference object */
00607 struct ast_conference {
00608    ast_mutex_t playlock;                   /*!< Conference specific lock (players) */
00609    ast_mutex_t listenlock;                 /*!< Conference specific lock (listeners) */
00610    char confno[MAX_CONFNUM];               /*!< Conference */
00611    struct ast_channel *chan;               /*!< Announcements channel */
00612    struct ast_channel *lchan;              /*!< Listen/Record channel */
00613    int fd;                                 /*!< Announcements fd */
00614    int dahdiconf;                            /*!< DAHDI Conf # */
00615    int users;                              /*!< Number of active users */
00616    int markedusers;                        /*!< Number of marked users */
00617    int maxusers;                           /*!< Participant limit if scheduled */
00618    int endalert;                           /*!< When to play conf ending message */
00619    time_t start;                           /*!< Start time (s) */
00620    int refcount;                           /*!< reference count of usage */
00621    enum recording_state recording:2;       /*!< recording status */
00622    unsigned int isdynamic:1;               /*!< Created on the fly? */
00623    unsigned int locked:1;                  /*!< Is the conference locked? */
00624    pthread_t recordthread;                 /*!< thread for recording */
00625    ast_mutex_t recordthreadlock;           /*!< control threads trying to start recordthread */
00626    pthread_attr_t attr;                    /*!< thread attribute */
00627    char *recordingfilename;                /*!< Filename to record the Conference into */
00628    char *recordingformat;                  /*!< Format to record the Conference in */
00629    char pin[MAX_PIN];                      /*!< If protected by a PIN */
00630    char pinadmin[MAX_PIN];                 /*!< If protected by a admin PIN */
00631    char uniqueid[32];
00632    long endtime;                           /*!< When to end the conf if scheduled */
00633    const char *useropts;                   /*!< RealTime user flags */
00634    const char *adminopts;                  /*!< RealTime moderator flags */
00635    const char *bookid;                     /*!< RealTime conference id */
00636    struct ast_frame *transframe[32];
00637    struct ast_frame *origframe;
00638    struct ast_trans_pvt *transpath[32];
00639    struct ao2_container *usercontainer;
00640    AST_LIST_ENTRY(ast_conference) list;
00641    /* announce_thread related data */
00642    pthread_t announcethread;
00643    ast_mutex_t announcethreadlock;
00644    unsigned int announcethread_stop:1;
00645    ast_cond_t announcelist_addition;
00646    AST_LIST_HEAD_NOLOCK(, announce_listitem) announcelist;
00647    ast_mutex_t announcelistlock;
00648 };
00649 
00650 static AST_LIST_HEAD_STATIC(confs, ast_conference);
00651 
00652 static unsigned int conf_map[1024] = {0, };
00653 
00654 struct volume {
00655    int desired;                            /*!< Desired volume adjustment */
00656    int actual;                             /*!< Actual volume adjustment (for channels that can't adjust) */
00657 };
00658 
00659 /*! \brief The MeetMe User object */
00660 struct ast_conf_user {
00661    int user_no;                            /*!< User Number */
00662    int userflags;                          /*!< Flags as set in the conference */
00663    int adminflags;                         /*!< Flags set by the Admin */
00664    struct ast_channel *chan;               /*!< Connected channel */
00665    int talking;                            /*!< Is user talking */
00666    int dahdichannel;                         /*!< Is a DAHDI channel */
00667    char usrvalue[50];                      /*!< Custom User Value */
00668    char namerecloc[PATH_MAX];          /*!< Name Recorded file Location */
00669    time_t jointime;                        /*!< Time the user joined the conference */
00670    time_t kicktime;                        /*!< Time the user will be kicked from the conference */
00671    struct timeval start_time;              /*!< Time the user entered into the conference */
00672    long timelimit;                         /*!< Time limit for the user to be in the conference L(x:y:z) */
00673    long play_warning;                      /*!< Play a warning when 'y' ms are left */
00674    long warning_freq;                      /*!< Repeat the warning every 'z' ms */
00675    const char *warning_sound;              /*!< File to play as warning if 'y' is defined */
00676    const char *end_sound;                  /*!< File to play when time is up. */
00677    struct volume talk;
00678    struct volume listen;
00679    AST_LIST_ENTRY(ast_conf_user) list;
00680 };
00681 
00682 enum sla_which_trunk_refs {
00683    ALL_TRUNK_REFS,
00684    INACTIVE_TRUNK_REFS,
00685 };
00686 
00687 enum sla_trunk_state {
00688    SLA_TRUNK_STATE_IDLE,
00689    SLA_TRUNK_STATE_RINGING,
00690    SLA_TRUNK_STATE_UP,
00691    SLA_TRUNK_STATE_ONHOLD,
00692    SLA_TRUNK_STATE_ONHOLD_BYME,
00693 };
00694 
00695 enum sla_hold_access {
00696    /*! This means that any station can put it on hold, and any station
00697     * can retrieve the call from hold. */
00698    SLA_HOLD_OPEN,
00699    /*! This means that only the station that put the call on hold may
00700     * retrieve it from hold. */
00701    SLA_HOLD_PRIVATE,
00702 };
00703 
00704 struct sla_trunk_ref;
00705 
00706 struct sla_station {
00707    AST_RWLIST_ENTRY(sla_station) entry;
00708    AST_DECLARE_STRING_FIELDS(
00709       AST_STRING_FIELD(name); 
00710       AST_STRING_FIELD(device);  
00711       AST_STRING_FIELD(autocontext);   
00712    );
00713    AST_LIST_HEAD_NOLOCK(, sla_trunk_ref) trunks;
00714    struct ast_dial *dial;
00715    /*! Ring timeout for this station, for any trunk.  If a ring timeout
00716     *  is set for a specific trunk on this station, that will take
00717     *  priority over this value. */
00718    unsigned int ring_timeout;
00719    /*! Ring delay for this station, for any trunk.  If a ring delay
00720     *  is set for a specific trunk on this station, that will take
00721     *  priority over this value. */
00722    unsigned int ring_delay;
00723    /*! This option uses the values in the sla_hold_access enum and sets the
00724     * access control type for hold on this station. */
00725    unsigned int hold_access:1;
00726    /*! Use count for inside sla_station_exec */
00727    unsigned int ref_count;
00728 };
00729 
00730 struct sla_station_ref {
00731    AST_LIST_ENTRY(sla_station_ref) entry;
00732    struct sla_station *station;
00733 };
00734 
00735 struct sla_trunk {
00736    AST_RWLIST_ENTRY(sla_trunk) entry;
00737    AST_DECLARE_STRING_FIELDS(
00738       AST_STRING_FIELD(name);
00739       AST_STRING_FIELD(device);
00740       AST_STRING_FIELD(autocontext);   
00741    );
00742    AST_LIST_HEAD_NOLOCK(, sla_station_ref) stations;
00743    /*! Number of stations that use this trunk */
00744    unsigned int num_stations;
00745    /*! Number of stations currently on a call with this trunk */
00746    unsigned int active_stations;
00747    /*! Number of stations that have this trunk on hold. */
00748    unsigned int hold_stations;
00749    struct ast_channel *chan;
00750    unsigned int ring_timeout;
00751    /*! If set to 1, no station will be able to join an active call with
00752     *  this trunk. */
00753    unsigned int barge_disabled:1;
00754    /*! This option uses the values in the sla_hold_access enum and sets the
00755     * access control type for hold on this trunk. */
00756    unsigned int hold_access:1;
00757    /*! Whether this trunk is currently on hold, meaning that once a station
00758     *  connects to it, the trunk channel needs to have UNHOLD indicated to it. */
00759    unsigned int on_hold:1;
00760    /*! Use count for inside sla_trunk_exec */
00761    unsigned int ref_count;
00762 };
00763 
00764 struct sla_trunk_ref {
00765    AST_LIST_ENTRY(sla_trunk_ref) entry;
00766    struct sla_trunk *trunk;
00767    enum sla_trunk_state state;
00768    struct ast_channel *chan;
00769    /*! Ring timeout to use when this trunk is ringing on this specific
00770     *  station.  This takes higher priority than a ring timeout set at
00771     *  the station level. */
00772    unsigned int ring_timeout;
00773    /*! Ring delay to use when this trunk is ringing on this specific
00774     *  station.  This takes higher priority than a ring delay set at
00775     *  the station level. */
00776    unsigned int ring_delay;
00777 };
00778 
00779 static AST_RWLIST_HEAD_STATIC(sla_stations, sla_station);
00780 static AST_RWLIST_HEAD_STATIC(sla_trunks, sla_trunk);
00781 
00782 static const char sla_registrar[] = "SLA";
00783 
00784 /*! \brief Event types that can be queued up for the SLA thread */
00785 enum sla_event_type {
00786    /*! A station has put the call on hold */
00787    SLA_EVENT_HOLD,
00788    /*! The state of a dial has changed */
00789    SLA_EVENT_DIAL_STATE,
00790    /*! The state of a ringing trunk has changed */
00791    SLA_EVENT_RINGING_TRUNK,
00792    /*! A reload of configuration has been requested */
00793    SLA_EVENT_RELOAD,
00794    /*! Poke the SLA thread so it can check if it can perform a reload */
00795    SLA_EVENT_CHECK_RELOAD,
00796 };
00797 
00798 struct sla_event {
00799    enum sla_event_type type;
00800    struct sla_station *station;
00801    struct sla_trunk_ref *trunk_ref;
00802    AST_LIST_ENTRY(sla_event) entry;
00803 };
00804 
00805 /*! \brief A station that failed to be dialed 
00806  * \note Only used by the SLA thread. */
00807 struct sla_failed_station {
00808    struct sla_station *station;
00809    struct timeval last_try;
00810    AST_LIST_ENTRY(sla_failed_station) entry;
00811 };
00812 
00813 /*! \brief A trunk that is ringing */
00814 struct sla_ringing_trunk {
00815    struct sla_trunk *trunk;
00816    /*! The time that this trunk started ringing */
00817    struct timeval ring_begin;
00818    AST_LIST_HEAD_NOLOCK(, sla_station_ref) timed_out_stations;
00819    AST_LIST_ENTRY(sla_ringing_trunk) entry;
00820 };
00821 
00822 enum sla_station_hangup {
00823    SLA_STATION_HANGUP_NORMAL,
00824    SLA_STATION_HANGUP_TIMEOUT,
00825 };
00826 
00827 /*! \brief A station that is ringing */
00828 struct sla_ringing_station {
00829    struct sla_station *station;
00830    /*! The time that this station started ringing */
00831    struct timeval ring_begin;
00832    AST_LIST_ENTRY(sla_ringing_station) entry;
00833 };
00834 
00835 /*!
00836  * \brief A structure for data used by the sla thread
00837  */
00838 static struct {
00839    /*! The SLA thread ID */
00840    pthread_t thread;
00841    ast_cond_t cond;
00842    ast_mutex_t lock;
00843    AST_LIST_HEAD_NOLOCK(, sla_ringing_trunk) ringing_trunks;
00844    AST_LIST_HEAD_NOLOCK(, sla_ringing_station) ringing_stations;
00845    AST_LIST_HEAD_NOLOCK(, sla_failed_station) failed_stations;
00846    AST_LIST_HEAD_NOLOCK(, sla_event) event_q;
00847    unsigned int stop:1;
00848    /*! Attempt to handle CallerID, even though it is known not to work
00849     *  properly in some situations. */
00850    unsigned int attempt_callerid:1;
00851    /*! A reload has been requested */
00852    unsigned int reload:1;
00853 } sla = {
00854    .thread = AST_PTHREADT_NULL,
00855 };
00856 
00857 /*! The number of audio buffers to be allocated on pseudo channels
00858  *  when in a conference */
00859 static int audio_buffers;
00860 
00861 /*! Map 'volume' levels from -5 through +5 into
00862  *  decibel (dB) settings for channel drivers
00863  *  Note: these are not a straight linear-to-dB
00864  *  conversion... the numbers have been modified
00865  *  to give the user a better level of adjustability
00866  */
00867 static char const gain_map[] = {
00868    -15,
00869    -13,
00870    -10,
00871    -6,
00872    0,
00873    0,
00874    0,
00875    6,
00876    10,
00877    13,
00878    15,
00879 };
00880 
00881 
00882 static int admin_exec(struct ast_channel *chan, void *data);
00883 static void *recordthread(void *args);
00884 
00885 static char *istalking(int x)
00886 {
00887    if (x > 0)
00888       return "(talking)";
00889    else if (x < 0)
00890       return "(unmonitored)";
00891    else 
00892       return "(not talking)";
00893 }
00894 
00895 static int careful_write(int fd, unsigned char *data, int len, int block)
00896 {
00897    int res;
00898    int x;
00899 
00900    while (len) {
00901       if (block) {
00902          x = DAHDI_IOMUX_WRITE | DAHDI_IOMUX_SIGEVENT;
00903          res = ioctl(fd, DAHDI_IOMUX, &x);
00904       } else
00905          res = 0;
00906       if (res >= 0)
00907          res = write(fd, data, len);
00908       if (res < 1) {
00909          if (errno != EAGAIN) {
00910             ast_log(LOG_WARNING, "Failed to write audio data to conference: %s\n", strerror(errno));
00911             return -1;
00912          } else
00913             return 0;
00914       }
00915       len -= res;
00916       data += res;
00917    }
00918 
00919    return 0;
00920 }
00921 
00922 static int set_talk_volume(struct ast_conf_user *user, int volume)
00923 {
00924    char gain_adjust;
00925 
00926    /* attempt to make the adjustment in the channel driver;
00927       if successful, don't adjust in the frame reading routine
00928    */
00929    gain_adjust = gain_map[volume + 5];
00930 
00931    return ast_channel_setoption(user->chan, AST_OPTION_RXGAIN, &gain_adjust, sizeof(gain_adjust), 0);
00932 }
00933 
00934 static int set_listen_volume(struct ast_conf_user *user, int volume)
00935 {
00936    char gain_adjust;
00937 
00938    /* attempt to make the adjustment in the channel driver;
00939       if successful, don't adjust in the frame reading routine
00940    */
00941    gain_adjust = gain_map[volume + 5];
00942 
00943    return ast_channel_setoption(user->chan, AST_OPTION_TXGAIN, &gain_adjust, sizeof(gain_adjust), 0);
00944 }
00945 
00946 static void tweak_volume(struct volume *vol, enum volume_action action)
00947 {
00948    switch (action) {
00949    case VOL_UP:
00950       switch (vol->desired) { 
00951       case 5:
00952          break;
00953       case 0:
00954          vol->desired = 2;
00955          break;
00956       case -2:
00957          vol->desired = 0;
00958          break;
00959       default:
00960          vol->desired++;
00961          break;
00962       }
00963       break;
00964    case VOL_DOWN:
00965       switch (vol->desired) {
00966       case -5:
00967          break;
00968       case 2:
00969          vol->desired = 0;
00970          break;
00971       case 0:
00972          vol->desired = -2;
00973          break;
00974       default:
00975          vol->desired--;
00976          break;
00977       }
00978    }
00979 }
00980 
00981 static void tweak_talk_volume(struct ast_conf_user *user, enum volume_action action)
00982 {
00983    tweak_volume(&user->talk, action);
00984    /* attempt to make the adjustment in the channel driver;
00985       if successful, don't adjust in the frame reading routine
00986    */
00987    if (!set_talk_volume(user, user->talk.desired))
00988       user->talk.actual = 0;
00989    else
00990       user->talk.actual = user->talk.desired;
00991 }
00992 
00993 static void tweak_listen_volume(struct ast_conf_user *user, enum volume_action action)
00994 {
00995    tweak_volume(&user->listen, action);
00996    /* attempt to make the adjustment in the channel driver;
00997       if successful, don't adjust in the frame reading routine
00998    */
00999    if (!set_listen_volume(user, user->listen.desired))
01000       user->listen.actual = 0;
01001    else
01002       user->listen.actual = user->listen.desired;
01003 }
01004 
01005 static void reset_volumes(struct ast_conf_user *user)
01006 {
01007    signed char zero_volume = 0;
01008 
01009    ast_channel_setoption(user->chan, AST_OPTION_TXGAIN, &zero_volume, sizeof(zero_volume), 0);
01010    ast_channel_setoption(user->chan, AST_OPTION_RXGAIN, &zero_volume, sizeof(zero_volume), 0);
01011 }
01012 
01013 static void conf_play(struct ast_channel *chan, struct ast_conference *conf, enum entrance_sound sound)
01014 {
01015    unsigned char *data;
01016    int len;
01017    int res = -1;
01018 
01019    if (!ast_check_hangup(chan))
01020       res = ast_autoservice_start(chan);
01021 
01022    AST_LIST_LOCK(&confs);
01023 
01024    switch(sound) {
01025    case ENTER:
01026       data = enter;
01027       len = sizeof(enter);
01028       break;
01029    case LEAVE:
01030       data = leave;
01031       len = sizeof(leave);
01032       break;
01033    default:
01034       data = NULL;
01035       len = 0;
01036    }
01037    if (data) {
01038       careful_write(conf->fd, data, len, 1);
01039    }
01040 
01041    AST_LIST_UNLOCK(&confs);
01042 
01043    if (!res) 
01044       ast_autoservice_stop(chan);
01045 }
01046 
01047 static int user_no_cmp(void *obj, void *arg, int flags)
01048 {
01049    struct ast_conf_user *user = obj;
01050    int *user_no = arg;
01051 
01052    if (user->user_no == *user_no) {
01053       return (CMP_MATCH | CMP_STOP);
01054    }
01055 
01056    return 0;
01057 }
01058 
01059 static int user_max_cmp(void *obj, void *arg, int flags)
01060 {
01061    struct ast_conf_user *user = obj;
01062    int *max_no = arg;
01063 
01064    if (user->user_no > *max_no) {
01065       *max_no = user->user_no;
01066    }
01067 
01068    return 0;
01069 }
01070 
01071 /*!
01072  * \brief Find or create a conference
01073  *
01074  * \param confno The conference name/number
01075  * \param pin The regular user pin
01076  * \param pinadmin The admin pin
01077  * \param make Make the conf if it doesn't exist
01078  * \param dynamic Mark the newly created conference as dynamic
01079  * \param refcount How many references to mark on the conference
01080  * \param chan The asterisk channel
01081  *
01082  * \return A pointer to the conference struct, or NULL if it wasn't found and
01083  *         make or dynamic were not set.
01084  */
01085 static struct ast_conference *build_conf(char *confno, char *pin, char *pinadmin, int make, int dynamic, int refcount, const struct ast_channel *chan)
01086 {
01087    struct ast_conference *cnf;
01088    struct dahdi_confinfo dahdic = { 0, };
01089    int confno_int = 0;
01090 
01091    AST_LIST_LOCK(&confs);
01092 
01093    AST_LIST_TRAVERSE(&confs, cnf, list) {
01094       if (!strcmp(confno, cnf->confno)) 
01095          break;
01096    }
01097 
01098    if (cnf || (!make && !dynamic))
01099       goto cnfout;
01100 
01101    /* Make a new one */
01102    if (!(cnf = ast_calloc(1, sizeof(*cnf))) ||
01103       !(cnf->usercontainer = ao2_container_alloc(1, NULL, user_no_cmp))) {
01104       goto cnfout;
01105    }
01106 
01107    ast_mutex_init(&cnf->playlock);
01108    ast_mutex_init(&cnf->listenlock);
01109    cnf->recordthread = AST_PTHREADT_NULL;
01110    ast_mutex_init(&cnf->recordthreadlock);
01111    cnf->announcethread = AST_PTHREADT_NULL;
01112    ast_mutex_init(&cnf->announcethreadlock);
01113    ast_copy_string(cnf->confno, confno, sizeof(cnf->confno));
01114    ast_copy_string(cnf->pin, pin, sizeof(cnf->pin));
01115    ast_copy_string(cnf->pinadmin, pinadmin, sizeof(cnf->pinadmin));
01116    ast_copy_string(cnf->uniqueid, chan->uniqueid, sizeof(cnf->uniqueid));
01117 
01118    /* Setup a new dahdi conference */
01119    dahdic.confno = -1;
01120    dahdic.confmode = DAHDI_CONF_CONFANN | DAHDI_CONF_CONFANNMON;
01121    cnf->fd = open("/dev/dahdi/pseudo", O_RDWR);
01122    if (cnf->fd < 0 || ioctl(cnf->fd, DAHDI_SETCONF, &dahdic)) {
01123       ast_log(LOG_WARNING, "Unable to open pseudo device\n");
01124       if (cnf->fd >= 0)
01125          close(cnf->fd);
01126       ast_free(cnf);
01127       cnf = NULL;
01128       goto cnfout;
01129    }
01130 
01131    cnf->dahdiconf = dahdic.confno;
01132 
01133    /* Setup a new channel for playback of audio files */
01134    cnf->chan = ast_request("DAHDI", AST_FORMAT_SLINEAR, "pseudo", NULL);
01135    if (cnf->chan) {
01136       ast_set_read_format(cnf->chan, AST_FORMAT_SLINEAR);
01137       ast_set_write_format(cnf->chan, AST_FORMAT_SLINEAR);
01138       dahdic.chan = 0;
01139       dahdic.confno = cnf->dahdiconf;
01140       dahdic.confmode = DAHDI_CONF_CONFANN | DAHDI_CONF_CONFANNMON;
01141       if (ioctl(cnf->chan->fds[0], DAHDI_SETCONF, &dahdic)) {
01142          ast_log(LOG_WARNING, "Error setting conference\n");
01143          if (cnf->chan)
01144             ast_hangup(cnf->chan);
01145          else
01146             close(cnf->fd);
01147 
01148          ast_free(cnf);
01149          cnf = NULL;
01150          goto cnfout;
01151       }
01152    }
01153 
01154    /* Fill the conference struct */
01155    cnf->start = time(NULL);
01156    cnf->maxusers = 0x7fffffff;
01157    cnf->isdynamic = dynamic ? 1 : 0;
01158    ast_verb(3, "Created MeetMe conference %d for conference '%s'\n", cnf->dahdiconf, cnf->confno);
01159    AST_LIST_INSERT_HEAD(&confs, cnf, list);
01160 
01161    /* Reserve conference number in map */
01162    if ((sscanf(cnf->confno, "%30d", &confno_int) == 1) && (confno_int >= 0 && confno_int < 1024))
01163       conf_map[confno_int] = 1;
01164    
01165 cnfout:
01166    if (cnf)
01167       ast_atomic_fetchadd_int(&cnf->refcount, refcount);
01168 
01169    AST_LIST_UNLOCK(&confs);
01170 
01171    return cnf;
01172 }
01173 
01174 static char *complete_meetmecmd(const char *line, const char *word, int pos, int state)
01175 {
01176    static char *cmds[] = {"concise", "lock", "unlock", "mute", "unmute", "kick", "list", NULL};
01177 
01178    int len = strlen(word);
01179    int which = 0;
01180    struct ast_conference *cnf = NULL;
01181    struct ast_conf_user *usr = NULL;
01182    char *confno = NULL;
01183    char usrno[50] = "";
01184    char *myline, *ret = NULL;
01185    
01186    if (pos == 1) {      /* Command */
01187       return ast_cli_complete(word, cmds, state);
01188    } else if (pos == 2) {  /* Conference Number */
01189       AST_LIST_LOCK(&confs);
01190       AST_LIST_TRAVERSE(&confs, cnf, list) {
01191          if (!strncasecmp(word, cnf->confno, len) && ++which > state) {
01192             ret = cnf->confno;
01193             break;
01194          }
01195       }
01196       ret = ast_strdup(ret); /* dup before releasing the lock */
01197       AST_LIST_UNLOCK(&confs);
01198       return ret;
01199    } else if (pos == 3) {
01200       /* User Number || Conf Command option*/
01201       if (strstr(line, "mute") || strstr(line, "kick")) {
01202          if (state == 0 && (strstr(line, "kick") || strstr(line, "mute")) && !strncasecmp(word, "all", len))
01203             return ast_strdup("all");
01204          which++;
01205          AST_LIST_LOCK(&confs);
01206 
01207          /* TODO: Find the conf number from the cmdline (ignore spaces) <- test this and make it fail-safe! */
01208          myline = ast_strdupa(line);
01209          if (strsep(&myline, " ") && strsep(&myline, " ") && !confno) {
01210             while((confno = strsep(&myline, " ")) && (strcmp(confno, " ") == 0))
01211                ;
01212          }
01213          
01214          AST_LIST_TRAVERSE(&confs, cnf, list) {
01215             if (!strcmp(confno, cnf->confno))
01216                 break;
01217          }
01218 
01219          if (cnf) {
01220             struct ao2_iterator user_iter;
01221             user_iter = ao2_iterator_init(cnf->usercontainer, 0);
01222             /* Search for the user */
01223             while((usr = ao2_iterator_next(&user_iter))) {
01224                snprintf(usrno, sizeof(usrno), "%d", usr->user_no);
01225                if (!strncasecmp(word, usrno, len) && ++which > state) {
01226                   ao2_ref(usr, -1);
01227                   break;
01228                }
01229                ao2_ref(usr, -1);
01230             }
01231             ao2_iterator_destroy(&user_iter);
01232             AST_LIST_UNLOCK(&confs);
01233             return usr ? ast_strdup(usrno) : NULL;
01234          }
01235       }
01236    }
01237 
01238    return NULL;
01239 }
01240 
01241 static char *meetme_show_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01242 {
01243    /* Process the command */
01244    struct ast_conf_user *user;
01245    struct ast_conference *cnf;
01246    int hr, min, sec;
01247    int i = 0, total = 0;
01248    time_t now;
01249    struct ast_str *cmdline = NULL;
01250 #define MC_HEADER_FORMAT "%-14s %-14s %-10s %-8s  %-8s  %-6s\n"
01251 #define MC_DATA_FORMAT "%-12.12s   %4.4d        %4.4s       %02d:%02d:%02d  %-8s  %-6s\n"
01252 
01253    switch (cmd) {
01254    case CLI_INIT:
01255       e->command = "meetme list [concise]";
01256       e->usage =
01257          "Usage: meetme list [concise] <confno> \n"
01258          "       List all or a specific conference.\n";
01259       return NULL;
01260    case CLI_GENERATE:
01261       return complete_meetmecmd(a->line, a->word, a->pos, a->n);
01262    }
01263 
01264    /* Check for length so no buffer will overflow... */
01265    for (i = 0; i < a->argc; i++) {
01266       if (strlen(a->argv[i]) > 100)
01267          ast_cli(a->fd, "Invalid Arguments.\n");
01268    }
01269 
01270    /* Max confno length */
01271    if (!(cmdline = ast_str_create(MAX_CONFNUM))) {
01272       return CLI_FAILURE;
01273    }
01274 
01275    if (a->argc == 2 || (a->argc == 3 && !strcasecmp(a->argv[2], "concise"))) {
01276       /* List all the conferences */   
01277       int concise = (a->argc == 3 && !strcasecmp(a->argv[2], "concise"));
01278       now = time(NULL);
01279       AST_LIST_LOCK(&confs);
01280       if (AST_LIST_EMPTY(&confs)) {
01281          if (!concise) {
01282             ast_cli(a->fd, "No active MeetMe conferences.\n");
01283          }
01284          AST_LIST_UNLOCK(&confs);
01285          ast_free(cmdline);
01286          return CLI_SUCCESS;
01287       }
01288       if (!concise) {
01289          ast_cli(a->fd, MC_HEADER_FORMAT, "Conf Num", "Parties", "Marked", "Activity", "Creation", "Locked");
01290       }
01291       AST_LIST_TRAVERSE(&confs, cnf, list) {
01292          if (cnf->markedusers == 0) {
01293             ast_str_set(&cmdline, 0, "N/A ");
01294          } else {
01295             ast_str_set(&cmdline, 0, "%4.4d", cnf->markedusers);
01296          }
01297          hr = (now - cnf->start) / 3600;
01298          min = ((now - cnf->start) % 3600) / 60;
01299          sec = (now - cnf->start) % 60;
01300          if (!concise) {
01301             ast_cli(a->fd, MC_DATA_FORMAT, cnf->confno, cnf->users, ast_str_buffer(cmdline), hr, min, sec, cnf->isdynamic ? "Dynamic" : "Static", cnf->locked ? "Yes" : "No");
01302          } else {
01303             ast_cli(a->fd, "%s!%d!%d!%02d:%02d:%02d!%d!%d\n",
01304                cnf->confno,
01305                cnf->users,
01306                cnf->markedusers,
01307                hr, min, sec,
01308                cnf->isdynamic,
01309                cnf->locked);
01310          }
01311 
01312          total += cnf->users;
01313       }
01314       AST_LIST_UNLOCK(&confs);
01315       if (!concise) {
01316          ast_cli(a->fd, "* Total number of MeetMe users: %d\n", total);
01317       }
01318       ast_free(cmdline);
01319       return CLI_SUCCESS;
01320    } else if (strcmp(a->argv[1], "list") == 0) {
01321       struct ao2_iterator user_iter;
01322       int concise = (a->argc == 4 && (!strcasecmp(a->argv[3], "concise")));
01323       /* List all the users in a conference */
01324       if (AST_LIST_EMPTY(&confs)) {
01325          if (!concise) {
01326             ast_cli(a->fd, "No active MeetMe conferences.\n");
01327          }
01328          ast_free(cmdline);
01329          return CLI_SUCCESS;  
01330       }
01331       /* Find the right conference */
01332       AST_LIST_LOCK(&confs);
01333       AST_LIST_TRAVERSE(&confs, cnf, list) {
01334          if (strcmp(cnf->confno, a->argv[2]) == 0) {
01335             break;
01336          }
01337       }
01338       if (!cnf) {
01339          if (!concise)
01340             ast_cli(a->fd, "No such conference: %s.\n", a->argv[2]);
01341          AST_LIST_UNLOCK(&confs);
01342          ast_free(cmdline);
01343          return CLI_SUCCESS;
01344       }
01345       /* Show all the users */
01346       time(&now);
01347       user_iter = ao2_iterator_init(cnf->usercontainer, 0);
01348       while((user = ao2_iterator_next(&user_iter))) {
01349          hr = (now - user->jointime) / 3600;
01350          min = ((now - user->jointime) % 3600) / 60;
01351          sec = (now - user->jointime) % 60;
01352          if (!concise) {
01353             ast_cli(a->fd, "User #: %-2.2d %12.12s %-20.20s Channel: %s %s %s %s %s %s %02d:%02d:%02d\n",
01354                user->user_no,
01355                S_OR(user->chan->cid.cid_num, "<unknown>"),
01356                S_OR(user->chan->cid.cid_name, "<no name>"),
01357                user->chan->name,
01358                user->userflags & CONFFLAG_ADMIN ? "(Admin)" : "",
01359                user->userflags & CONFFLAG_MONITOR ? "(Listen only)" : "",
01360                user->adminflags & ADMINFLAG_MUTED ? "(Admin Muted)" : user->adminflags & ADMINFLAG_SELFMUTED ? "(Muted)" : "",
01361                user->adminflags & ADMINFLAG_T_REQUEST ? "(Request to Talk)" : "",
01362                istalking(user->talking), hr, min, sec); 
01363          } else {
01364             ast_cli(a->fd, "%d!%s!%s!%s!%s!%s!%s!%s!%d!%02d:%02d:%02d\n",
01365                user->user_no,
01366                S_OR(user->chan->cid.cid_num, ""),
01367                S_OR(user->chan->cid.cid_name, ""),
01368                user->chan->name,
01369                user->userflags  & CONFFLAG_ADMIN   ? "1" : "",
01370                user->userflags  & CONFFLAG_MONITOR ? "1" : "",
01371                user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED) ? "1" : "",
01372                user->adminflags & ADMINFLAG_T_REQUEST ? "1" : "",
01373                user->talking, hr, min, sec);
01374          }
01375          ao2_ref(user, -1);
01376       }
01377       ao2_iterator_destroy(&user_iter);
01378       if (!concise) {
01379          ast_cli(a->fd, "%d users in that conference.\n", cnf->users);
01380       }
01381       AST_LIST_UNLOCK(&confs);
01382       ast_free(cmdline);
01383       return CLI_SUCCESS;
01384    }
01385    if (a->argc < 2) {
01386       ast_free(cmdline);
01387       return CLI_SHOWUSAGE;
01388    }
01389 
01390    ast_debug(1, "Cmdline: %s\n", ast_str_buffer(cmdline));
01391 
01392    admin_exec(NULL, ast_str_buffer(cmdline));
01393    ast_free(cmdline);
01394 
01395    return CLI_SUCCESS;
01396 }
01397 
01398 
01399 static char *meetme_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01400 {
01401    /* Process the command */
01402    struct ast_str *cmdline = NULL;
01403    int i = 0;
01404 
01405    switch (cmd) {
01406    case CLI_INIT:
01407       e->command = "meetme {lock|unlock|mute|unmute|kick}";
01408       e->usage =
01409          "Usage: meetme (un)lock|(un)mute|kick <confno> <usernumber>\n"
01410          "       Executes a command for the conference or on a conferee\n";
01411       return NULL;
01412    case CLI_GENERATE:
01413       return complete_meetmecmd(a->line, a->word, a->pos, a->n);
01414    }
01415 
01416    if (a->argc > 8)
01417       ast_cli(a->fd, "Invalid Arguments.\n");
01418    /* Check for length so no buffer will overflow... */
01419    for (i = 0; i < a->argc; i++) {
01420       if (strlen(a->argv[i]) > 100)
01421          ast_cli(a->fd, "Invalid Arguments.\n");
01422    }
01423 
01424    /* Max confno length */
01425    if (!(cmdline = ast_str_create(MAX_CONFNUM))) {
01426       return CLI_FAILURE;
01427    }
01428 
01429    if (a->argc < 1) {
01430       ast_free(cmdline);
01431       return CLI_SHOWUSAGE;
01432    }
01433 
01434    ast_str_set(&cmdline, 0, "%s", a->argv[2]);  /* Argv 2: conference number */
01435    if (strstr(a->argv[1], "lock")) {
01436       if (strcmp(a->argv[1], "lock") == 0) {
01437          /* Lock */
01438          ast_str_append(&cmdline, 0, ",L");
01439       } else {
01440          /* Unlock */
01441          ast_str_append(&cmdline, 0, ",l");
01442       }
01443    } else if (strstr(a->argv[1], "mute")) { 
01444       if (a->argc < 4) {
01445          ast_free(cmdline);
01446          return CLI_SHOWUSAGE;
01447       }
01448       if (strcmp(a->argv[1], "mute") == 0) {
01449          /* Mute */
01450          if (strcmp(a->argv[3], "all") == 0) {
01451             ast_str_append(&cmdline, 0, ",N");
01452          } else {
01453             ast_str_append(&cmdline, 0, ",M,%s", a->argv[3]);  
01454          }
01455       } else {
01456          /* Unmute */
01457          if (strcmp(a->argv[3], "all") == 0) {
01458             ast_str_append(&cmdline, 0, ",n");
01459          } else {
01460             ast_str_append(&cmdline, 0, ",m,%s", a->argv[3]);
01461          }
01462       }
01463    } else if (strcmp(a->argv[1], "kick") == 0) {
01464       if (a->argc < 4) {
01465          ast_free(cmdline);
01466          return CLI_SHOWUSAGE;
01467       }
01468       if (strcmp(a->argv[3], "all") == 0) {
01469          /* Kick all */
01470          ast_str_append(&cmdline, 0, ",K");
01471       } else {
01472          /* Kick a single user */
01473          ast_str_append(&cmdline, 0, ",k,%s", a->argv[3]);
01474       }
01475    } else {
01476       ast_free(cmdline);
01477       return CLI_SHOWUSAGE;
01478    }
01479 
01480    ast_debug(1, "Cmdline: %s\n", ast_str_buffer(cmdline));
01481 
01482    admin_exec(NULL, ast_str_buffer(cmdline));
01483    ast_free(cmdline);
01484 
01485    return CLI_SUCCESS;
01486 }
01487 
01488 static const char *sla_hold_str(unsigned int hold_access)
01489 {
01490    const char *hold = "Unknown";
01491 
01492    switch (hold_access) {
01493    case SLA_HOLD_OPEN:
01494       hold = "Open";
01495       break;
01496    case SLA_HOLD_PRIVATE:
01497       hold = "Private";
01498    default:
01499       break;
01500    }
01501 
01502    return hold;
01503 }
01504 
01505 static char *sla_show_trunks(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01506 {
01507    const struct sla_trunk *trunk;
01508 
01509    switch (cmd) {
01510    case CLI_INIT:
01511       e->command = "sla show trunks";
01512       e->usage =
01513          "Usage: sla show trunks\n"
01514          "       This will list all trunks defined in sla.conf\n";
01515       return NULL;
01516    case CLI_GENERATE:
01517       return NULL;
01518    }
01519 
01520    ast_cli(a->fd, "\n"
01521                "=============================================================\n"
01522                "=== Configured SLA Trunks ===================================\n"
01523                "=============================================================\n"
01524                "===\n");
01525    AST_RWLIST_RDLOCK(&sla_trunks);
01526    AST_RWLIST_TRAVERSE(&sla_trunks, trunk, entry) {
01527       struct sla_station_ref *station_ref;
01528       char ring_timeout[16] = "(none)";
01529       if (trunk->ring_timeout)
01530          snprintf(ring_timeout, sizeof(ring_timeout), "%u Seconds", trunk->ring_timeout);
01531       ast_cli(a->fd, "=== ---------------------------------------------------------\n"
01532                   "=== Trunk Name:       %s\n"
01533                   "=== ==> Device:       %s\n"
01534                   "=== ==> AutoContext:  %s\n"
01535                   "=== ==> RingTimeout:  %s\n"
01536                   "=== ==> BargeAllowed: %s\n"
01537                   "=== ==> HoldAccess:   %s\n"
01538                   "=== ==> Stations ...\n",
01539                   trunk->name, trunk->device, 
01540                   S_OR(trunk->autocontext, "(none)"), 
01541                   ring_timeout,
01542                   trunk->barge_disabled ? "No" : "Yes",
01543                   sla_hold_str(trunk->hold_access));
01544       AST_RWLIST_RDLOCK(&sla_stations);
01545       AST_LIST_TRAVERSE(&trunk->stations, station_ref, entry)
01546          ast_cli(a->fd, "===    ==> Station name: %s\n", station_ref->station->name);
01547       AST_RWLIST_UNLOCK(&sla_stations);
01548       ast_cli(a->fd, "=== ---------------------------------------------------------\n===\n");
01549    }
01550    AST_RWLIST_UNLOCK(&sla_trunks);
01551    ast_cli(a->fd, "=============================================================\n\n");
01552 
01553    return CLI_SUCCESS;
01554 }
01555 
01556 static const char *trunkstate2str(enum sla_trunk_state state)
01557 {
01558 #define S(e) case e: return # e;
01559    switch (state) {
01560    S(SLA_TRUNK_STATE_IDLE)
01561    S(SLA_TRUNK_STATE_RINGING)
01562    S(SLA_TRUNK_STATE_UP)
01563    S(SLA_TRUNK_STATE_ONHOLD)
01564    S(SLA_TRUNK_STATE_ONHOLD_BYME)
01565    }
01566    return "Uknown State";
01567 #undef S
01568 }
01569 
01570 static char *sla_show_stations(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01571 {
01572    const struct sla_station *station;
01573 
01574    switch (cmd) {
01575    case CLI_INIT:
01576       e->command = "sla show stations";
01577       e->usage =
01578          "Usage: sla show stations\n"
01579          "       This will list all stations defined in sla.conf\n";
01580       return NULL;
01581    case CLI_GENERATE:
01582       return NULL;
01583    }
01584 
01585    ast_cli(a->fd, "\n" 
01586                "=============================================================\n"
01587                "=== Configured SLA Stations =================================\n"
01588                "=============================================================\n"
01589                "===\n");
01590    AST_RWLIST_RDLOCK(&sla_stations);
01591    AST_RWLIST_TRAVERSE(&sla_stations, station, entry) {
01592       struct sla_trunk_ref *trunk_ref;
01593       char ring_timeout[16] = "(none)";
01594       char ring_delay[16] = "(none)";
01595       if (station->ring_timeout) {
01596          snprintf(ring_timeout, sizeof(ring_timeout), 
01597             "%u", station->ring_timeout);
01598       }
01599       if (station->ring_delay) {
01600          snprintf(ring_delay, sizeof(ring_delay), 
01601             "%u", station->ring_delay);
01602       }
01603       ast_cli(a->fd, "=== ---------------------------------------------------------\n"
01604                   "=== Station Name:    %s\n"
01605                   "=== ==> Device:      %s\n"
01606                   "=== ==> AutoContext: %s\n"
01607                   "=== ==> RingTimeout: %s\n"
01608                   "=== ==> RingDelay:   %s\n"
01609                   "=== ==> HoldAccess:  %s\n"
01610                   "=== ==> Trunks ...\n",
01611                   station->name, station->device,
01612                   S_OR(station->autocontext, "(none)"), 
01613                   ring_timeout, ring_delay,
01614                   sla_hold_str(station->hold_access));
01615       AST_RWLIST_RDLOCK(&sla_trunks);
01616       AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
01617          if (trunk_ref->ring_timeout) {
01618             snprintf(ring_timeout, sizeof(ring_timeout),
01619                "%u", trunk_ref->ring_timeout);
01620          } else
01621             strcpy(ring_timeout, "(none)");
01622          if (trunk_ref->ring_delay) {
01623             snprintf(ring_delay, sizeof(ring_delay),
01624                "%u", trunk_ref->ring_delay);
01625          } else
01626             strcpy(ring_delay, "(none)");
01627             ast_cli(a->fd, "===    ==> Trunk Name: %s\n"
01628                      "===       ==> State:       %s\n"
01629                      "===       ==> RingTimeout: %s\n"
01630                      "===       ==> RingDelay:   %s\n",
01631                      trunk_ref->trunk->name,
01632                      trunkstate2str(trunk_ref->state),
01633                      ring_timeout, ring_delay);
01634       }
01635       AST_RWLIST_UNLOCK(&sla_trunks);
01636       ast_cli(a->fd, "=== ---------------------------------------------------------\n"
01637                   "===\n");
01638    }
01639    AST_RWLIST_UNLOCK(&sla_stations);
01640    ast_cli(a->fd, "============================================================\n"
01641                "\n");
01642 
01643    return CLI_SUCCESS;
01644 }
01645 
01646 static struct ast_cli_entry cli_meetme[] = {
01647    AST_CLI_DEFINE(meetme_cmd, "Execute a command on a conference or conferee"),
01648    AST_CLI_DEFINE(meetme_show_cmd, "List all or one conference"),
01649    AST_CLI_DEFINE(sla_show_trunks, "Show SLA Trunks"),
01650    AST_CLI_DEFINE(sla_show_stations, "Show SLA Stations"),
01651 };
01652 
01653 static void conf_flush(int fd, struct ast_channel *chan)
01654 {
01655    int x;
01656 
01657    /* read any frames that may be waiting on the channel
01658       and throw them away
01659    */
01660    if (chan) {
01661       struct ast_frame *f;
01662 
01663       /* when no frames are available, this will wait
01664          for 1 millisecond maximum
01665       */
01666       while (ast_waitfor(chan, 1)) {
01667          f = ast_read(chan);
01668          if (f)
01669             ast_frfree(f);
01670          else /* channel was hung up or something else happened */
01671             break;
01672       }
01673    }
01674 
01675    /* flush any data sitting in the pseudo channel */
01676    x = DAHDI_FLUSH_ALL;
01677    if (ioctl(fd, DAHDI_FLUSH, &x))
01678       ast_log(LOG_WARNING, "Error flushing channel\n");
01679 
01680 }
01681 
01682 /* Remove the conference from the list and free it.
01683    We assume that this was called while holding conflock. */
01684 static int conf_free(struct ast_conference *conf)
01685 {
01686    int x;
01687    struct announce_listitem *item;
01688    
01689    AST_LIST_REMOVE(&confs, conf, list);
01690    manager_event(EVENT_FLAG_CALL, "MeetmeEnd", "Meetme: %s\r\n", conf->confno);
01691 
01692    if (conf->recording == MEETME_RECORD_ACTIVE) {
01693       conf->recording = MEETME_RECORD_TERMINATE;
01694       AST_LIST_UNLOCK(&confs);
01695       while (1) {
01696          usleep(1);
01697          AST_LIST_LOCK(&confs);
01698          if (conf->recording == MEETME_RECORD_OFF)
01699             break;
01700          AST_LIST_UNLOCK(&confs);
01701       }
01702    }
01703 
01704    for (x = 0; x < AST_FRAME_BITS; x++) {
01705       if (conf->transframe[x])
01706          ast_frfree(conf->transframe[x]);
01707       if (conf->transpath[x])
01708          ast_translator_free_path(conf->transpath[x]);
01709    }
01710    if (conf->announcethread != AST_PTHREADT_NULL) {
01711       ast_mutex_lock(&conf->announcelistlock);
01712       conf->announcethread_stop = 1;
01713       ast_softhangup(conf->chan, AST_SOFTHANGUP_EXPLICIT);
01714       ast_cond_signal(&conf->announcelist_addition);
01715       ast_mutex_unlock(&conf->announcelistlock);
01716       pthread_join(conf->announcethread, NULL);
01717    
01718       while ((item = AST_LIST_REMOVE_HEAD(&conf->announcelist, entry))) {
01719          ast_filedelete(item->namerecloc, NULL);
01720          ao2_ref(item, -1);
01721       }
01722       ast_mutex_destroy(&conf->announcelistlock);
01723    }
01724    if (conf->origframe)
01725       ast_frfree(conf->origframe);
01726    if (conf->lchan)
01727       ast_hangup(conf->lchan);
01728    if (conf->chan)
01729       ast_hangup(conf->chan);
01730    if (conf->fd >= 0)
01731       close(conf->fd);
01732    if (conf->recordingfilename) {
01733       ast_free(conf->recordingfilename);
01734    }
01735    if (conf->recordingformat) {
01736       ast_free(conf->recordingformat);
01737    }
01738    if (conf->usercontainer) {
01739       ao2_ref(conf->usercontainer, -1);
01740    }
01741    ast_mutex_destroy(&conf->playlock);
01742    ast_mutex_destroy(&conf->listenlock);
01743    ast_mutex_destroy(&conf->recordthreadlock);
01744    ast_mutex_destroy(&conf->announcethreadlock);
01745    ast_free(conf);
01746 
01747    return 0;
01748 }
01749 
01750 static void conf_queue_dtmf(const struct ast_conference *conf,
01751    const struct ast_conf_user *sender, struct ast_frame *f)
01752 {
01753    struct ast_conf_user *user;
01754    struct ao2_iterator user_iter;
01755 
01756    user_iter = ao2_iterator_init(conf->usercontainer, 0);
01757    while ((user = ao2_iterator_next(&user_iter))) {
01758       if (user == sender) {
01759          ao2_ref(user, -1);
01760          continue;
01761       }
01762       if (ast_write(user->chan, f) < 0)
01763          ast_log(LOG_WARNING, "Error writing frame to channel %s\n", user->chan->name);
01764       ao2_ref(user, -1);
01765    }
01766    ao2_iterator_destroy(&user_iter);
01767 }
01768 
01769 static void sla_queue_event_full(enum sla_event_type type, 
01770    struct sla_trunk_ref *trunk_ref, struct sla_station *station, int lock)
01771 {
01772    struct sla_event *event;
01773 
01774    if (sla.thread == AST_PTHREADT_NULL) {
01775       return;
01776    }
01777 
01778    if (!(event = ast_calloc(1, sizeof(*event))))
01779       return;
01780 
01781    event->type = type;
01782    event->trunk_ref = trunk_ref;
01783    event->station = station;
01784 
01785    if (!lock) {
01786       AST_LIST_INSERT_TAIL(&sla.event_q, event, entry);
01787       return;
01788    }
01789 
01790    ast_mutex_lock(&sla.lock);
01791    AST_LIST_INSERT_TAIL(&sla.event_q, event, entry);
01792    ast_cond_signal(&sla.cond);
01793    ast_mutex_unlock(&sla.lock);
01794 }
01795 
01796 static void sla_queue_event_nolock(enum sla_event_type type)
01797 {
01798    sla_queue_event_full(type, NULL, NULL, 0);
01799 }
01800 
01801 static void sla_queue_event(enum sla_event_type type)
01802 {
01803    sla_queue_event_full(type, NULL, NULL, 1);
01804 }
01805 
01806 /*! \brief Queue a SLA event from the conference */
01807 static void sla_queue_event_conf(enum sla_event_type type, struct ast_channel *chan,
01808    struct ast_conference *conf)
01809 {
01810    struct sla_station *station;
01811    struct sla_trunk_ref *trunk_ref = NULL;
01812    char *trunk_name;
01813 
01814    trunk_name = ast_strdupa(conf->confno);
01815    strsep(&trunk_name, "_");
01816    if (ast_strlen_zero(trunk_name)) {
01817       ast_log(LOG_ERROR, "Invalid conference name for SLA - '%s'!\n", conf->confno);
01818       return;
01819    }
01820 
01821    AST_RWLIST_RDLOCK(&sla_stations);
01822    AST_RWLIST_TRAVERSE(&sla_stations, station, entry) {
01823       AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
01824          if (trunk_ref->chan == chan && !strcmp(trunk_ref->trunk->name, trunk_name))
01825             break;
01826       }
01827       if (trunk_ref)
01828          break;
01829    }
01830    AST_RWLIST_UNLOCK(&sla_stations);
01831 
01832    if (!trunk_ref) {
01833       ast_debug(1, "Trunk not found for event!\n");
01834       return;
01835    }
01836 
01837    sla_queue_event_full(type, trunk_ref, station, 1);
01838 }
01839 
01840 /* Decrement reference counts, as incremented by find_conf() */
01841 static int dispose_conf(struct ast_conference *conf)
01842 {
01843    int res = 0;
01844    int confno_int = 0;
01845 
01846    AST_LIST_LOCK(&confs);
01847    if (ast_atomic_dec_and_test(&conf->refcount)) {
01848       /* Take the conference room number out of an inuse state */
01849       if ((sscanf(conf->confno, "%4d", &confno_int) == 1) && (confno_int >= 0 && confno_int < 1024)) {
01850          conf_map[confno_int] = 0;
01851       }
01852       conf_free(conf);
01853       res = 1;
01854    }
01855    AST_LIST_UNLOCK(&confs);
01856 
01857    return res;
01858 }
01859 
01860 static int rt_extend_conf(char *confno)
01861 {
01862    char currenttime[32];
01863    char endtime[32];
01864    struct timeval now;
01865    struct ast_tm tm;
01866    struct ast_variable *var, *orig_var;
01867    char bookid[51];
01868 
01869    if (!extendby) {
01870       return 0;
01871    }
01872 
01873    now = ast_tvnow();
01874 
01875    ast_localtime(&now, &tm, NULL);
01876    ast_strftime(currenttime, sizeof(currenttime), DATE_FORMAT, &tm);
01877 
01878    var = ast_load_realtime("meetme", "confno",
01879       confno, "startTime<= ", currenttime,
01880       "endtime>= ", currenttime, NULL);
01881 
01882    orig_var = var;
01883 
01884    /* Identify the specific RealTime conference */
01885    while (var) {
01886       if (!strcasecmp(var->name, "bookid")) {
01887          ast_copy_string(bookid, var->value, sizeof(bookid));
01888       }
01889       if (!strcasecmp(var->name, "endtime")) {
01890          ast_copy_string(endtime, var->value, sizeof(endtime));
01891       }
01892 
01893       var = var->next;
01894    }
01895    ast_variables_destroy(orig_var);
01896 
01897    ast_strptime(endtime, DATE_FORMAT, &tm);
01898    now = ast_mktime(&tm, NULL);
01899 
01900    now.tv_sec += extendby;
01901 
01902    ast_localtime(&now, &tm, NULL);
01903    ast_strftime(currenttime, sizeof(currenttime), DATE_FORMAT, &tm);
01904    strcat(currenttime, "0"); /* Seconds needs to be 00 */
01905 
01906    var = ast_load_realtime("meetme", "confno",
01907       confno, "startTime<= ", currenttime,
01908       "endtime>= ", currenttime, NULL);
01909 
01910    /* If there is no conflict with extending the conference, update the DB */
01911    if (!var) {
01912       ast_debug(3, "Trying to update the endtime of Conference %s to %s\n", confno, currenttime);
01913       ast_update_realtime("meetme", "bookid", bookid, "endtime", currenttime, NULL);
01914       return 0;
01915 
01916    }
01917 
01918    ast_variables_destroy(var);
01919    return -1;
01920 }
01921 
01922 static void conf_start_moh(struct ast_channel *chan, const char *musicclass)
01923 {
01924    char *original_moh;
01925 
01926    ast_channel_lock(chan);
01927    original_moh = ast_strdupa(chan->musicclass);
01928    ast_string_field_set(chan, musicclass, musicclass);
01929    ast_channel_unlock(chan);
01930 
01931    ast_moh_start(chan, original_moh, NULL);
01932 
01933    ast_channel_lock(chan);
01934    ast_string_field_set(chan, musicclass, original_moh);
01935    ast_channel_unlock(chan);
01936 }
01937 
01938 static const char *get_announce_filename(enum announcetypes type)
01939 {
01940    switch (type) {
01941    case CONF_HASLEFT:
01942       return "conf-hasleft";
01943       break;
01944    case CONF_HASJOIN:
01945       return "conf-hasjoin";
01946       break;
01947    default:
01948       return "";
01949    }
01950 }
01951 
01952 static void *announce_thread(void *data)
01953 {
01954    struct announce_listitem *current;
01955    struct ast_conference *conf = data;
01956    int res;
01957    char filename[PATH_MAX] = "";
01958    AST_LIST_HEAD_NOLOCK(, announce_listitem) local_list;
01959    AST_LIST_HEAD_INIT_NOLOCK(&local_list);
01960 
01961    while (!conf->announcethread_stop) {
01962       ast_mutex_lock(&conf->announcelistlock);
01963       if (conf->announcethread_stop) {
01964          ast_mutex_unlock(&conf->announcelistlock);
01965          break;
01966       }
01967       if (AST_LIST_EMPTY(&conf->announcelist))
01968          ast_cond_wait(&conf->announcelist_addition, &conf->announcelistlock);
01969 
01970       AST_LIST_APPEND_LIST(&local_list, &conf->announcelist, entry);
01971       AST_LIST_HEAD_INIT_NOLOCK(&conf->announcelist);
01972 
01973       ast_mutex_unlock(&conf->announcelistlock);
01974       if (conf->announcethread_stop) {
01975          break;
01976       }
01977 
01978       for (res = 1; !conf->announcethread_stop && (current = AST_LIST_REMOVE_HEAD(&local_list, entry)); ao2_ref(current, -1)) {
01979          ast_log(LOG_DEBUG, "About to play %s\n", current->namerecloc);
01980          if (!ast_fileexists(current->namerecloc, NULL, NULL))
01981             continue;
01982          if ((current->confchan) && (current->confusers > 1) && !ast_check_hangup(current->confchan)) {
01983             if (!ast_streamfile(current->confchan, current->namerecloc, current->language))
01984                res = ast_waitstream(current->confchan, "");
01985             if (!res) {
01986                ast_copy_string(filename, get_announce_filename(current->announcetype), sizeof(filename));
01987                if (!ast_streamfile(current->confchan, filename, current->language))
01988                   ast_waitstream(current->confchan, "");
01989             }
01990          }
01991          if (current->announcetype == CONF_HASLEFT) {
01992             ast_filedelete(current->namerecloc, NULL);
01993          }
01994       }
01995    }
01996 
01997    /* thread marked to stop, clean up */
01998    while ((current = AST_LIST_REMOVE_HEAD(&local_list, entry))) {
01999       ast_filedelete(current->namerecloc, NULL);
02000       ao2_ref(current, -1);
02001    }
02002    return NULL;
02003 }
02004 
02005 static int can_write(struct ast_channel *chan, int confflags)
02006 {
02007    if (!(confflags & CONFFLAG_NO_AUDIO_UNTIL_UP)) {
02008       return 1;
02009    }
02010 
02011    return (chan->_state == AST_STATE_UP);
02012 }
02013 
02014 static void send_talking_event(struct ast_channel *chan, struct ast_conference *conf, struct ast_conf_user *user, int talking)
02015 {
02016    manager_event(EVENT_FLAG_CALL, "MeetmeTalking",
02017          "Channel: %s\r\n"
02018          "Uniqueid: %s\r\n"
02019          "Meetme: %s\r\n"
02020          "Usernum: %d\r\n"
02021          "Status: %s\r\n",
02022          chan->name, chan->uniqueid, conf->confno, user->user_no, talking ? "on" : "off");
02023 }
02024 
02025 static void set_user_talking(struct ast_channel *chan, struct ast_conference *conf, struct ast_conf_user *user, int talking, int monitor)
02026 {
02027    int last_talking = user->talking;
02028    if (last_talking == talking)
02029       return;
02030 
02031    user->talking = talking;
02032 
02033    if (monitor) {
02034       /* Check if talking state changed. Take care of -1 which means unmonitored */
02035       int was_talking = (last_talking > 0);
02036       int now_talking = (talking > 0);
02037       if (was_talking != now_talking) {
02038          send_talking_event(chan, conf, user, now_talking);
02039       }
02040    }
02041 }
02042 
02043 static int conf_run(struct ast_channel *chan, struct ast_conference *conf, int confflags, char *optargs[])
02044 {
02045    struct ast_conf_user *user = NULL;
02046    struct ast_conf_user *usr = NULL;
02047    int fd;
02048    struct dahdi_confinfo dahdic, dahdic_empty;
02049    struct ast_frame *f;
02050    struct ast_channel *c;
02051    struct ast_frame fr;
02052    int outfd;
02053    int ms;
02054    int nfds;
02055    int res;
02056    int retrydahdi;
02057    int origfd;
02058    int musiconhold = 0, mohtempstopped = 0;
02059    int firstpass = 0;
02060    int lastmarked = 0;
02061    int currentmarked = 0;
02062    int ret = -1;
02063    int x;
02064    int menu_active = 0;
02065    int talkreq_manager = 0;
02066    int using_pseudo = 0;
02067    int duration = 20;
02068    int hr, min, sec;
02069    int sent_event = 0;
02070    int checked = 0;
02071    int announcement_played = 0;
02072    struct timeval now;
02073    struct ast_dsp *dsp = NULL;
02074    struct ast_app *agi_app;
02075    char *agifile;
02076    const char *agifiledefault = "conf-background.agi", *tmpvar;
02077    char meetmesecs[30] = "";
02078    char exitcontext[AST_MAX_CONTEXT] = "";
02079    char recordingtmp[AST_MAX_EXTENSION] = "";
02080    char members[10] = "";
02081    int dtmf, opt_waitmarked_timeout = 0;
02082    time_t timeout = 0;
02083    struct dahdi_bufferinfo bi;
02084    char __buf[CONF_SIZE + AST_FRIENDLY_OFFSET];
02085    char *buf = __buf + AST_FRIENDLY_OFFSET;
02086    char *exitkeys = NULL;
02087    unsigned int calldurationlimit = 0;
02088    long timelimit = 0;
02089    long play_warning = 0;
02090    long warning_freq = 0;
02091    const char *warning_sound = NULL;
02092    const char *end_sound = NULL;
02093    char *parse;   
02094    long time_left_ms = 0;
02095    struct timeval nexteventts = { 0, };
02096    int to;
02097    int setusercount = 0;
02098    int confsilence = 0, totalsilence = 0;
02099 
02100    if (!(user = ao2_alloc(sizeof(*user), NULL))) {
02101       return ret;
02102    }
02103 
02104    /* Possible timeout waiting for marked user */
02105    if ((confflags & CONFFLAG_WAITMARKED) &&
02106       !ast_strlen_zero(optargs[OPT_ARG_WAITMARKED]) &&
02107       (sscanf(optargs[OPT_ARG_WAITMARKED], "%30d", &opt_waitmarked_timeout) == 1) &&
02108       (opt_waitmarked_timeout > 0)) {
02109       timeout = time(NULL) + opt_waitmarked_timeout;
02110    }
02111       
02112    if ((confflags & CONFFLAG_DURATION_STOP) && !ast_strlen_zero(optargs[OPT_ARG_DURATION_STOP])) {
02113       calldurationlimit = atoi(optargs[OPT_ARG_DURATION_STOP]);
02114       ast_verb(3, "Setting call duration limit to %d seconds.\n", calldurationlimit);
02115    }
02116    
02117    if ((confflags & CONFFLAG_DURATION_LIMIT) && !ast_strlen_zero(optargs[OPT_ARG_DURATION_LIMIT])) {
02118       char *limit_str, *warning_str, *warnfreq_str;
02119       const char *var;
02120  
02121       parse = optargs[OPT_ARG_DURATION_LIMIT];
02122       limit_str = strsep(&parse, ":");
02123       warning_str = strsep(&parse, ":");
02124       warnfreq_str = parse;
02125  
02126       timelimit = atol(limit_str);
02127       if (warning_str)
02128          play_warning = atol(warning_str);
02129       if (warnfreq_str)
02130          warning_freq = atol(warnfreq_str);
02131  
02132       if (!timelimit) {
02133          timelimit = play_warning = warning_freq = 0;
02134          warning_sound = NULL;
02135       } else if (play_warning > timelimit) {       
02136          if (!warning_freq) {
02137             play_warning = 0;
02138          } else {
02139             while (play_warning > timelimit)
02140                play_warning -= warning_freq;
02141             if (play_warning < 1)
02142                play_warning = warning_freq = 0;
02143          }
02144       }
02145       
02146       ast_channel_lock(chan);
02147       if ((var = pbx_builtin_getvar_helper(chan, "CONF_LIMIT_WARNING_FILE"))) {
02148          var = ast_strdupa(var);
02149       }
02150       ast_channel_unlock(chan);
02151 
02152       warning_sound = var ? var : "timeleft";
02153       
02154       ast_channel_lock(chan);
02155       if ((var = pbx_builtin_getvar_helper(chan, "CONF_LIMIT_TIMEOUT_FILE"))) {
02156          var = ast_strdupa(var);
02157       }
02158       ast_channel_unlock(chan);
02159       
02160       end_sound = var ? var : NULL;
02161          
02162       /* undo effect of S(x) in case they are both used */
02163       calldurationlimit = 0;
02164       /* more efficient do it like S(x) does since no advanced opts */
02165       if (!play_warning && !end_sound && timelimit) { 
02166          calldurationlimit = timelimit / 1000;
02167          timelimit = play_warning = warning_freq = 0;
02168       } else {
02169          ast_debug(2, "Limit Data for this call:\n");
02170          ast_debug(2, "- timelimit     = %ld\n", timelimit);
02171          ast_debug(2, "- play_warning  = %ld\n", play_warning);
02172          ast_debug(2, "- warning_freq  = %ld\n", warning_freq);
02173          ast_debug(2, "- warning_sound = %s\n", warning_sound ? warning_sound : "UNDEF");
02174          ast_debug(2, "- end_sound     = %s\n", end_sound ? end_sound : "UNDEF");
02175       }
02176    }
02177 
02178    /* Get exit keys */
02179    if ((confflags & CONFFLAG_KEYEXIT)) {
02180       if (!ast_strlen_zero(optargs[OPT_ARG_EXITKEYS]))
02181          exitkeys = ast_strdupa(optargs[OPT_ARG_EXITKEYS]);
02182       else
02183          exitkeys = ast_strdupa("#"); /* Default */
02184    }
02185    
02186    if (confflags & CONFFLAG_RECORDCONF) {
02187       if (!conf->recordingfilename) {
02188          const char *var;
02189          ast_channel_lock(chan);
02190          if ((var = pbx_builtin_getvar_helper(chan, "MEETME_RECORDINGFILE"))) {
02191             conf->recordingfilename = ast_strdup(var);
02192          }
02193          if ((var = pbx_builtin_getvar_helper(chan, "MEETME_RECORDINGFORMAT"))) {
02194             conf->recordingformat = ast_strdup(var);
02195          }
02196          ast_channel_unlock(chan);
02197          if (!conf->recordingfilename) {
02198             snprintf(recordingtmp, sizeof(recordingtmp), "meetme-conf-rec-%s-%s", conf->confno, chan->uniqueid);
02199             conf->recordingfilename = ast_strdup(recordingtmp);
02200          }
02201          if (!conf->recordingformat) {
02202             conf->recordingformat = ast_strdup("wav");
02203          }
02204          ast_verb(4, "Starting recording of MeetMe Conference %s into file %s.%s.\n",
02205                 conf->confno, conf->recordingfilename, conf->recordingformat);
02206       }
02207    }
02208 
02209    ast_mutex_lock(&conf->recordthreadlock);
02210    if ((conf->recordthread == AST_PTHREADT_NULL) && (confflags & CONFFLAG_RECORDCONF) && ((conf->lchan = ast_request("DAHDI", AST_FORMAT_SLINEAR, "pseudo", NULL)))) {
02211       ast_set_read_format(conf->lchan, AST_FORMAT_SLINEAR);
02212       ast_set_write_format(conf->lchan, AST_FORMAT_SLINEAR);
02213       dahdic.chan = 0;
02214       dahdic.confno = conf->dahdiconf;
02215       dahdic.confmode = DAHDI_CONF_CONFANN | DAHDI_CONF_CONFANNMON;
02216       if (ioctl(conf->lchan->fds[0], DAHDI_SETCONF, &dahdic)) {
02217          ast_log(LOG_WARNING, "Error starting listen channel\n");
02218          ast_hangup(conf->lchan);
02219          conf->lchan = NULL;
02220       } else {
02221          ast_pthread_create_detached_background(&conf->recordthread, NULL, recordthread, conf);
02222       }
02223    }
02224    ast_mutex_unlock(&conf->recordthreadlock);
02225 
02226    ast_mutex_lock(&conf->announcethreadlock);
02227    if ((conf->announcethread == AST_PTHREADT_NULL) && !(confflags & CONFFLAG_QUIET) && ((confflags & CONFFLAG_INTROUSER) || (confflags & CONFFLAG_INTROUSERNOREVIEW))) {
02228       ast_mutex_init(&conf->announcelistlock);
02229       AST_LIST_HEAD_INIT_NOLOCK(&conf->announcelist);
02230       ast_pthread_create_background(&conf->announcethread, NULL, announce_thread, conf);
02231    }
02232    ast_mutex_unlock(&conf->announcethreadlock);
02233 
02234    time(&user->jointime);
02235    
02236    user->timelimit = timelimit;
02237    user->play_warning = play_warning;
02238    user->warning_freq = warning_freq;
02239    user->warning_sound = warning_sound;
02240    user->end_sound = end_sound;  
02241    
02242    if (calldurationlimit > 0) {
02243       time(&user->kicktime);
02244       user->kicktime = user->kicktime + calldurationlimit;
02245    }
02246    
02247    if (ast_tvzero(user->start_time))
02248       user->start_time = ast_tvnow();
02249    time_left_ms = user->timelimit;
02250    
02251    if (user->timelimit) {
02252       nexteventts = ast_tvadd(user->start_time, ast_samp2tv(user->timelimit, 1000));
02253       nexteventts = ast_tvsub(nexteventts, ast_samp2tv(user->play_warning, 1000));
02254    }
02255 
02256    if (conf->locked && (!(confflags & CONFFLAG_ADMIN))) {
02257       /* Sorry, but this conference is locked! */  
02258       if (!ast_streamfile(chan, "conf-locked", chan->language))
02259          ast_waitstream(chan, "");
02260       goto outrun;
02261    }
02262 
02263       ast_mutex_lock(&conf->playlock);
02264 
02265    if (rt_schedule && conf->maxusers) {
02266       if (conf->users >= conf->maxusers) {
02267          /* Sorry, but this confernce has reached the participant limit! */   
02268          if (!ast_streamfile(chan, "conf-full", chan->language))
02269             ast_waitstream(chan, "");
02270          ast_mutex_unlock(&conf->playlock);
02271          goto outrun;
02272       }
02273    }
02274 
02275    ao2_lock(conf->usercontainer);
02276    ao2_callback(conf->usercontainer, OBJ_NODATA, user_max_cmp, &user->user_no);
02277    user->user_no++;
02278    ao2_link(conf->usercontainer, user);
02279    ao2_unlock(conf->usercontainer);
02280 
02281    user->chan = chan;
02282    user->userflags = confflags;
02283    user->adminflags = (confflags & CONFFLAG_STARTMUTED) ? ADMINFLAG_SELFMUTED : 0;
02284    user->talking = -1;
02285 
02286    ast_mutex_unlock(&conf->playlock);
02287 
02288    if (!(confflags & CONFFLAG_QUIET) && ((confflags & CONFFLAG_INTROUSER) || (confflags & CONFFLAG_INTROUSERNOREVIEW))) {
02289       char destdir[PATH_MAX];
02290 
02291       snprintf(destdir, sizeof(destdir), "%s/meetme", ast_config_AST_SPOOL_DIR);
02292 
02293       if (ast_mkdir(destdir, 0777) != 0) {
02294          ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", destdir, strerror(errno));
02295          goto outrun;
02296       }
02297 
02298       snprintf(user->namerecloc, sizeof(user->namerecloc),
02299           "%s/meetme-username-%s-%d", destdir,
02300           conf->confno, user->user_no);
02301       if (confflags & CONFFLAG_INTROUSERNOREVIEW)
02302          res = ast_play_and_record(chan, "vm-rec-name", user->namerecloc, 10, "sln", &duration, ast_dsp_get_threshold_from_settings(THRESHOLD_SILENCE), 0, NULL);
02303       else
02304          res = ast_record_review(chan, "vm-rec-name", user->namerecloc, 10, "sln", &duration, NULL);
02305       if (res == -1)
02306          goto outrun;
02307    }
02308 
02309    ast_mutex_lock(&conf->playlock);
02310 
02311    if (confflags & CONFFLAG_MARKEDUSER)
02312       conf->markedusers++;
02313    conf->users++;
02314    if (rt_log_members) {
02315       /* Update table */
02316       snprintf(members, sizeof(members), "%d", conf->users);
02317       ast_realtime_require_field("meetme",
02318          "confno", strlen(conf->confno) > 7 ? RQ_UINTEGER4 : strlen(conf->confno) > 4 ? RQ_UINTEGER3 : RQ_UINTEGER2, strlen(conf->confno),
02319          "members", RQ_UINTEGER1, strlen(members),
02320          NULL);
02321       ast_update_realtime("meetme", "confno", conf->confno, "members", members, NULL);
02322    }
02323    setusercount = 1;
02324 
02325    /* This device changed state now - if this is the first user */
02326    if (conf->users == 1)
02327       ast_devstate_changed(AST_DEVICE_INUSE, "meetme:%s", conf->confno);
02328 
02329    ast_mutex_unlock(&conf->playlock);
02330 
02331    /* return the unique ID of the conference */
02332    pbx_builtin_setvar_helper(chan, "MEETMEUNIQUEID", conf->uniqueid);
02333 
02334    if (confflags & CONFFLAG_EXIT_CONTEXT) {
02335       ast_channel_lock(chan);
02336       if ((tmpvar = pbx_builtin_getvar_helper(chan, "MEETME_EXIT_CONTEXT"))) {
02337          ast_copy_string(exitcontext, tmpvar, sizeof(exitcontext));
02338       } else if (!ast_strlen_zero(chan->macrocontext)) {
02339          ast_copy_string(exitcontext, chan->macrocontext, sizeof(exitcontext));
02340       } else {
02341          ast_copy_string(exitcontext, chan->context, sizeof(exitcontext));
02342       }
02343       ast_channel_unlock(chan);
02344    }
02345 
02346    if (!(confflags & (CONFFLAG_QUIET | CONFFLAG_NOONLYPERSON))) {
02347       if (conf->users == 1 && !(confflags & CONFFLAG_WAITMARKED))
02348          if (!ast_streamfile(chan, "conf-onlyperson", chan->language))
02349             ast_waitstream(chan, "");
02350       if ((confflags & CONFFLAG_WAITMARKED) && conf->markedusers == 0)
02351          if (!ast_streamfile(chan, "conf-waitforleader", chan->language))
02352             ast_waitstream(chan, "");
02353    }
02354 
02355    if (!(confflags & CONFFLAG_QUIET) && (confflags & CONFFLAG_ANNOUNCEUSERCOUNT) && conf->users > 1) {
02356       int keepplaying = 1;
02357 
02358       if (conf->users == 2) { 
02359          if (!ast_streamfile(chan, "conf-onlyone", chan->language)) {
02360             res = ast_waitstream(chan, AST_DIGIT_ANY);
02361             ast_stopstream(chan);
02362             if (res > 0)
02363                keepplaying = 0;
02364             else if (res == -1)
02365                goto outrun;
02366          }
02367       } else { 
02368          if (!ast_streamfile(chan, "conf-thereare", chan->language)) {
02369             res = ast_waitstream(chan, AST_DIGIT_ANY);
02370             ast_stopstream(chan);
02371             if (res > 0)
02372                keepplaying = 0;
02373             else if (res == -1)
02374                goto outrun;
02375          }
02376          if (keepplaying) {
02377             res = ast_say_number(chan, conf->users - 1, AST_DIGIT_ANY, chan->language, (char *) NULL);
02378             if (res > 0)
02379                keepplaying = 0;
02380             else if (res == -1)
02381                goto outrun;
02382          }
02383          if (keepplaying && !ast_streamfile(chan, "conf-otherinparty", chan->language)) {
02384             res = ast_waitstream(chan, AST_DIGIT_ANY);
02385             ast_stopstream(chan);
02386             if (res > 0)
02387                keepplaying = 0;
02388             else if (res == -1) 
02389                goto outrun;
02390          }
02391       }
02392    }
02393 
02394    if (!(confflags & CONFFLAG_NO_AUDIO_UNTIL_UP)) {
02395       /* We're leaving this alone until the state gets changed to up */
02396       ast_indicate(chan, -1);
02397    }
02398 
02399    if (ast_set_write_format(chan, AST_FORMAT_SLINEAR) < 0) {
02400       ast_log(LOG_WARNING, "Unable to set '%s' to write linear mode\n", chan->name);
02401       goto outrun;
02402    }
02403 
02404    if (ast_set_read_format(chan, AST_FORMAT_SLINEAR) < 0) {
02405       ast_log(LOG_WARNING, "Unable to set '%s' to read linear mode\n", chan->name);
02406       goto outrun;
02407    }
02408 
02409    retrydahdi = (strcasecmp(chan->tech->type, "DAHDI") || (chan->audiohooks || chan->monitor) ? 1 : 0);
02410    user->dahdichannel = !retrydahdi;
02411 
02412  dahdiretry:
02413    origfd = chan->fds[0];
02414    if (retrydahdi) {
02415       /* open pseudo in non-blocking mode */
02416       fd = open("/dev/dahdi/pseudo", O_RDWR | O_NONBLOCK);
02417       if (fd < 0) {
02418          ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
02419          goto outrun;
02420       }
02421       using_pseudo = 1;
02422       /* Setup buffering information */
02423       memset(&bi, 0, sizeof(bi));
02424       bi.bufsize = CONF_SIZE / 2;
02425       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
02426       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
02427       bi.numbufs = audio_buffers;
02428       if (ioctl(fd, DAHDI_SET_BUFINFO, &bi)) {
02429          ast_log(LOG_WARNING, "Unable to set buffering information: %s\n", strerror(errno));
02430          close(fd);
02431          goto outrun;
02432       }
02433       x = 1;
02434       if (ioctl(fd, DAHDI_SETLINEAR, &x)) {
02435          ast_log(LOG_WARNING, "Unable to set linear mode: %s\n", strerror(errno));
02436          close(fd);
02437          goto outrun;
02438       }
02439       nfds = 1;
02440    } else {
02441       /* XXX Make sure we're not running on a pseudo channel XXX */
02442       fd = chan->fds[0];
02443       nfds = 0;
02444    }
02445    memset(&dahdic, 0, sizeof(dahdic));
02446    memset(&dahdic_empty, 0, sizeof(dahdic_empty));
02447    /* Check to see if we're in a conference... */
02448    dahdic.chan = 0;  
02449    if (ioctl(fd, DAHDI_GETCONF, &dahdic)) {
02450       ast_log(LOG_WARNING, "Error getting conference\n");
02451       close(fd);
02452       goto outrun;
02453    }
02454    if (dahdic.confmode) {
02455       /* Whoa, already in a conference...  Retry... */
02456       if (!retrydahdi) {
02457          ast_debug(1, "DAHDI channel is in a conference already, retrying with pseudo\n");
02458          retrydahdi = 1;
02459          goto dahdiretry;
02460       }
02461    }
02462    memset(&dahdic, 0, sizeof(dahdic));
02463    /* Add us to the conference */
02464    dahdic.chan = 0;  
02465    dahdic.confno = conf->dahdiconf;
02466 
02467    if (!(confflags & CONFFLAG_QUIET) && ((confflags & CONFFLAG_INTROUSER) || (confflags & CONFFLAG_INTROUSERNOREVIEW)) && conf->users > 1) {
02468       struct announce_listitem *item;
02469       if (!(item = ao2_alloc(sizeof(*item), NULL)))
02470          return -1;
02471       ast_copy_string(item->namerecloc, user->namerecloc, sizeof(item->namerecloc));
02472       ast_copy_string(item->language, chan->language, sizeof(item->language));
02473       item->confchan = conf->chan;
02474       item->confusers = conf->users;
02475       item->announcetype = CONF_HASJOIN;
02476       ast_mutex_lock(&conf->announcelistlock);
02477       ao2_ref(item, +1); /* add one more so we can determine when announce_thread is done playing it */
02478       AST_LIST_INSERT_TAIL(&conf->announcelist, item, entry);
02479       ast_cond_signal(&conf->announcelist_addition);
02480       ast_mutex_unlock(&conf->announcelistlock);
02481 
02482       while (!ast_check_hangup(conf->chan) && ao2_ref(item, 0) == 2 && !ast_safe_sleep(chan, 1000)) {
02483          ;
02484       }
02485       ao2_ref(item, -1);
02486    }
02487 
02488    if (confflags & CONFFLAG_WAITMARKED && !conf->markedusers)
02489       dahdic.confmode = DAHDI_CONF_CONF;
02490    else if (confflags & CONFFLAG_MONITOR)
02491       dahdic.confmode = DAHDI_CONF_CONFMON | DAHDI_CONF_LISTENER;
02492    else if (confflags & CONFFLAG_TALKER)
02493       dahdic.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER;
02494    else 
02495       dahdic.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
02496 
02497    if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
02498       ast_log(LOG_WARNING, "Error setting conference\n");
02499       close(fd);
02500       goto outrun;
02501    }
02502    ast_debug(1, "Placed channel %s in DAHDI conf %d\n", chan->name, conf->dahdiconf);
02503 
02504    if (!sent_event) {
02505       manager_event(EVENT_FLAG_CALL, "MeetmeJoin", 
02506                  "Channel: %s\r\n"
02507                  "Uniqueid: %s\r\n"
02508             "Meetme: %s\r\n"
02509             "Usernum: %d\r\n"
02510             "CallerIDnum: %s\r\n"
02511                   "CallerIDname: %s\r\n",
02512                   chan->name, chan->uniqueid, conf->confno, 
02513             user->user_no,
02514             S_OR(user->chan->cid.cid_num, "<unknown>"),
02515             S_OR(user->chan->cid.cid_name, "<unknown>")
02516             );
02517       sent_event = 1;
02518    }
02519 
02520    if (!firstpass && !(confflags & CONFFLAG_MONITOR) && !(confflags & CONFFLAG_ADMIN)) {
02521       firstpass = 1;
02522       if (!(confflags & CONFFLAG_QUIET))
02523          if (!(confflags & CONFFLAG_WAITMARKED) || ((confflags & CONFFLAG_MARKEDUSER) && (conf->markedusers >= 1)))
02524             conf_play(chan, conf, ENTER);
02525    }
02526 
02527    conf_flush(fd, chan);
02528 
02529    if (!(dsp = ast_dsp_new())) {
02530       ast_log(LOG_WARNING, "Unable to allocate DSP!\n");
02531       res = -1;
02532    }
02533 
02534    if (confflags & CONFFLAG_AGI) {
02535       /* Get name of AGI file to run from $(MEETME_AGI_BACKGROUND)
02536          or use default filename of conf-background.agi */
02537 
02538       ast_channel_lock(chan);
02539       if ((tmpvar = pbx_builtin_getvar_helper(chan, "MEETME_AGI_BACKGROUND"))) {
02540          agifile = ast_strdupa(tmpvar);
02541       } else {
02542          agifile = ast_strdupa(agifiledefault);
02543       }
02544       ast_channel_unlock(chan);
02545       
02546       if (user->dahdichannel) {
02547          /*  Set CONFMUTE mode on DAHDI channel to mute DTMF tones */
02548          x = 1;
02549          ast_channel_setoption(chan, AST_OPTION_TONE_VERIFY, &x, sizeof(char), 0);
02550       }
02551       /* Find a pointer to the agi app and execute the script */
02552       agi_app = pbx_findapp("agi");
02553       if (agi_app) {
02554          ret = pbx_exec(chan, agi_app, agifile);
02555       } else {
02556          ast_log(LOG_WARNING, "Could not find application (agi)\n");
02557          ret = -2;
02558       }
02559       if (user->dahdichannel) {
02560          /*  Remove CONFMUTE mode on DAHDI channel */
02561          x = 0;
02562          ast_channel_setoption(chan, AST_OPTION_TONE_VERIFY, &x, sizeof(char), 0);
02563       }
02564    } else {
02565       if (user->dahdichannel && (confflags & CONFFLAG_STARMENU)) {
02566          /*  Set CONFMUTE mode on DAHDI channel to mute DTMF tones when the menu is enabled */
02567          x = 1;
02568          ast_channel_setoption(chan, AST_OPTION_TONE_VERIFY, &x, sizeof(char), 0);
02569       }  
02570       for (;;) {
02571          int menu_was_active = 0;
02572 
02573          outfd = -1;
02574          ms = -1;
02575          now = ast_tvnow();
02576 
02577          if (rt_schedule && conf->endtime) {
02578             char currenttime[32];
02579             long localendtime = 0;
02580             int extended = 0;
02581             struct ast_tm tm;
02582             struct ast_variable *var, *origvar;
02583             struct timeval tmp;
02584 
02585             if (now.tv_sec % 60 == 0) {
02586                if (!checked) {
02587                   ast_localtime(&now, &tm, NULL);
02588                   ast_strftime(currenttime, sizeof(currenttime), DATE_FORMAT, &tm);
02589                   var = origvar = ast_load_realtime("meetme", "confno",
02590                      conf->confno, "starttime <=", currenttime,
02591                       "endtime >=", currenttime, NULL);
02592 
02593                   for ( ; var; var = var->next) {
02594                      if (!strcasecmp(var->name, "endtime")) {
02595                         struct ast_tm endtime_tm;
02596                         ast_strptime(var->value, "%Y-%m-%d %H:%M:%S", &endtime_tm);
02597                         tmp = ast_mktime(&endtime_tm, NULL);
02598                         localendtime = tmp.tv_sec;
02599                      }
02600                   }
02601                   ast_variables_destroy(origvar);
02602 
02603                   /* A conference can be extended from the
02604                      Admin/User menu or by an external source */
02605                   if (localendtime > conf->endtime){
02606                      conf->endtime = localendtime;
02607                      extended = 1;
02608                   }
02609 
02610                   if (conf->endtime && (now.tv_sec >= conf->endtime)) {
02611                      ast_verbose("Quitting time...\n");
02612                      goto outrun;
02613                   }
02614 
02615                   if (!announcement_played && conf->endalert) {
02616                      if (now.tv_sec + conf->endalert >= conf->endtime) {
02617                         if (!ast_streamfile(chan, "conf-will-end-in", chan->language))
02618                            ast_waitstream(chan, "");
02619                         ast_say_digits(chan, (conf->endtime - now.tv_sec) / 60, "", chan->language);
02620                         if (!ast_streamfile(chan, "minutes", chan->language))
02621                            ast_waitstream(chan, "");
02622                         announcement_played = 1;
02623                      }
02624                   }
02625 
02626                   if (extended) {
02627                      announcement_played = 0;
02628                   }
02629 
02630                   checked = 1;
02631                }
02632             } else {
02633                checked = 0;
02634             }
02635          }
02636 
02637          if (user->kicktime && (user->kicktime <= now.tv_sec)) {
02638             break;
02639          }
02640   
02641          to = -1;
02642          if (user->timelimit) {
02643             int minutes = 0, seconds = 0, remain = 0;
02644  
02645             to = ast_tvdiff_ms(nexteventts, now);
02646             if (to < 0) {
02647                to = 0;
02648             }
02649             time_left_ms = user->timelimit - ast_tvdiff_ms(now, user->start_time);
02650             if (time_left_ms < to) {
02651                to = time_left_ms;
02652             }
02653    
02654             if (time_left_ms <= 0) {
02655                if (user->end_sound) {                 
02656                   res = ast_streamfile(chan, user->end_sound, chan->language);
02657                   res = ast_waitstream(chan, "");
02658                }
02659                break;
02660             }
02661             
02662             if (!to) {
02663                if (time_left_ms >= 5000) {                  
02664                   
02665                   remain = (time_left_ms + 500) / 1000;
02666                   if (remain / 60 >= 1) {
02667                      minutes = remain / 60;
02668                      seconds = remain % 60;
02669                   } else {
02670                      seconds = remain;
02671                   }
02672                   
02673                   /* force the time left to round up if appropriate */
02674                   if (user->warning_sound && user->play_warning) {
02675                      if (!strcmp(user->warning_sound, "timeleft")) {
02676                         
02677                         res = ast_streamfile(chan, "vm-youhave", chan->language);
02678                         res = ast_waitstream(chan, "");
02679                         if (minutes) {
02680                            res = ast_say_number(chan, minutes, AST_DIGIT_ANY, chan->language, (char *) NULL);
02681                            res = ast_streamfile(chan, "queue-minutes", chan->language);
02682                            res = ast_waitstream(chan, "");
02683                         }
02684                         if (seconds) {
02685                            res = ast_say_number(chan, seconds, AST_DIGIT_ANY, chan->language, (char *) NULL);
02686                            res = ast_streamfile(chan, "queue-seconds", chan->language);
02687                            res = ast_waitstream(chan, "");
02688                         }
02689                      } else {
02690                         res = ast_streamfile(chan, user->warning_sound, chan->language);
02691                         res = ast_waitstream(chan, "");
02692                      }
02693                   }
02694                }
02695                if (user->warning_freq) {
02696                   nexteventts = ast_tvadd(nexteventts, ast_samp2tv(user->warning_freq, 1000));
02697                } else {
02698                   nexteventts = ast_tvadd(user->start_time, ast_samp2tv(user->timelimit, 1000));
02699                }
02700             }
02701          }
02702 
02703          now = ast_tvnow();
02704          if (timeout && now.tv_sec >= timeout) {
02705             break;
02706          }
02707 
02708          /* if we have just exited from the menu, and the user had a channel-driver
02709             volume adjustment, restore it
02710          */
02711          if (!menu_active && menu_was_active && user->listen.desired && !user->listen.actual) {
02712             set_talk_volume(user, user->listen.desired);
02713          }
02714 
02715          menu_was_active = menu_active;
02716 
02717          currentmarked = conf->markedusers;
02718          if (!(confflags & CONFFLAG_QUIET) &&
02719              (confflags & CONFFLAG_MARKEDUSER) &&
02720              (confflags & CONFFLAG_WAITMARKED) &&
02721              lastmarked == 0) {
02722             if (currentmarked == 1 && conf->users > 1) {
02723                ast_say_number(chan, conf->users - 1, AST_DIGIT_ANY, chan->language, (char *) NULL);
02724                if (conf->users - 1 == 1) {
02725                   if (!ast_streamfile(chan, "conf-userwilljoin", chan->language)) {
02726                      ast_waitstream(chan, "");
02727                   }
02728                } else {
02729                   if (!ast_streamfile(chan, "conf-userswilljoin", chan->language)) {
02730                      ast_waitstream(chan, "");
02731                   }
02732                }
02733             }
02734             if (conf->users == 1 && ! (confflags & CONFFLAG_MARKEDUSER)) {
02735                if (!ast_streamfile(chan, "conf-onlyperson", chan->language)) {
02736                   ast_waitstream(chan, "");
02737                }
02738             }
02739          }
02740 
02741          /* Update the struct with the actual confflags */
02742          user->userflags = confflags;
02743 
02744          if (confflags & CONFFLAG_WAITMARKED) {
02745             if (currentmarked == 0) {
02746                if (lastmarked != 0) {
02747                   if (!(confflags & CONFFLAG_QUIET)) {
02748                      if (!ast_streamfile(chan, "conf-leaderhasleft", chan->language)) {
02749                         ast_waitstream(chan, "");
02750                      }
02751                   }
02752                   if (confflags & CONFFLAG_MARKEDEXIT) {
02753                      if (confflags & CONFFLAG_KICK_CONTINUE) {
02754                         ret = 0;
02755                      }
02756                      break;
02757                   } else {
02758                      dahdic.confmode = DAHDI_CONF_CONF;
02759                      if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
02760                         ast_log(LOG_WARNING, "Error setting conference\n");
02761                         close(fd);
02762                         goto outrun;
02763                      }
02764                   }
02765                }
02766                if (!musiconhold && (confflags & CONFFLAG_MOH)) {
02767                   conf_start_moh(chan, optargs[OPT_ARG_MOH_CLASS]);
02768                   musiconhold = 1;
02769                }
02770             } else if (currentmarked >= 1 && lastmarked == 0) {
02771                /* Marked user entered, so cancel timeout */
02772                timeout = 0;
02773                if (confflags & CONFFLAG_MONITOR) {
02774                   dahdic.confmode = DAHDI_CONF_CONFMON | DAHDI_CONF_LISTENER;
02775                } else if (confflags & CONFFLAG_TALKER) {
02776                   dahdic.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER;
02777                } else {
02778                   dahdic.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
02779                }
02780                if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
02781                   ast_log(LOG_WARNING, "Error setting conference\n");
02782                   close(fd);
02783                   goto outrun;
02784                }
02785                if (musiconhold && (confflags & CONFFLAG_MOH)) {
02786                   ast_moh_stop(chan);
02787                   musiconhold = 0;
02788                }
02789                if (!(confflags & CONFFLAG_QUIET) && !(confflags & CONFFLAG_MARKEDUSER)) {
02790                   if (!ast_streamfile(chan, "conf-placeintoconf", chan->language)) {
02791                      ast_waitstream(chan, "");
02792                   }
02793                   conf_play(chan, conf, ENTER);
02794                }
02795             }
02796          }
02797 
02798          /* trying to add moh for single person conf */
02799          if ((confflags & CONFFLAG_MOH) && !(confflags & CONFFLAG_WAITMARKED)) {
02800             if (conf->users == 1) {
02801                if (!musiconhold) {
02802                   conf_start_moh(chan, optargs[OPT_ARG_MOH_CLASS]);
02803                   musiconhold = 1;
02804                } 
02805             } else {
02806                if (musiconhold) {
02807                   ast_moh_stop(chan);
02808                   musiconhold = 0;
02809                }
02810             }
02811          }
02812          
02813          /* Leave if the last marked user left */
02814          if (currentmarked == 0 && lastmarked != 0 && (confflags & CONFFLAG_MARKEDEXIT)) {
02815             if (confflags & CONFFLAG_KICK_CONTINUE) {
02816                ret = 0;
02817             } else {
02818                ret = -1;
02819             }
02820             break;
02821          }
02822    
02823          /* Check if my modes have changed */
02824 
02825          /* If I should be muted but am still talker, mute me */
02826          if ((user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) && (dahdic.confmode & DAHDI_CONF_TALKER)) {
02827             dahdic.confmode ^= DAHDI_CONF_TALKER;
02828             if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
02829                ast_log(LOG_WARNING, "Error setting conference - Un/Mute \n");
02830                ret = -1;
02831                break;
02832             }
02833 
02834             /* Indicate user is not talking anymore - change him to unmonitored state */
02835             if ((confflags & (CONFFLAG_MONITORTALKER | CONFFLAG_OPTIMIZETALKER))) {
02836                set_user_talking(chan, conf, user, -1, confflags & CONFFLAG_MONITORTALKER);
02837             }
02838 
02839             manager_event(EVENT_FLAG_CALL, "MeetmeMute", 
02840                   "Channel: %s\r\n"
02841                   "Uniqueid: %s\r\n"
02842                   "Meetme: %s\r\n"
02843                   "Usernum: %i\r\n"
02844                   "Status: on\r\n",
02845                   chan->name, chan->uniqueid, conf->confno, user->user_no);
02846          }
02847 
02848          /* If I should be un-muted but am not talker, un-mute me */
02849          if (!(user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) && !(confflags & CONFFLAG_MONITOR) && !(dahdic.confmode & DAHDI_CONF_TALKER)) {
02850             dahdic.confmode |= DAHDI_CONF_TALKER;
02851             if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
02852                ast_log(LOG_WARNING, "Error setting conference - Un/Mute \n");
02853                ret = -1;
02854                break;
02855             }
02856 
02857             manager_event(EVENT_FLAG_CALL, "MeetmeMute", 
02858                   "Channel: %s\r\n"
02859                   "Uniqueid: %s\r\n"
02860                   "Meetme: %s\r\n"
02861                   "Usernum: %i\r\n"
02862                   "Status: off\r\n",
02863                   chan->name, chan->uniqueid, conf->confno, user->user_no);
02864          }
02865          
02866          if ((user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) && 
02867             (user->adminflags & ADMINFLAG_T_REQUEST) && !(talkreq_manager)) {
02868             talkreq_manager = 1;
02869 
02870             manager_event(EVENT_FLAG_CALL, "MeetmeTalkRequest", 
02871                      "Channel: %s\r\n"
02872                            "Uniqueid: %s\r\n"
02873                            "Meetme: %s\r\n"
02874                            "Usernum: %i\r\n"
02875                            "Status: on\r\n",
02876                            chan->name, chan->uniqueid, conf->confno, user->user_no);
02877          }
02878 
02879          
02880          if (!(user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) && 
02881             !(user->adminflags & ADMINFLAG_T_REQUEST) && (talkreq_manager)) {
02882             talkreq_manager = 0;
02883             manager_event(EVENT_FLAG_CALL, "MeetmeTalkRequest", 
02884                      "Channel: %s\r\n"
02885                            "Uniqueid: %s\r\n"
02886                            "Meetme: %s\r\n"
02887                            "Usernum: %i\r\n"
02888                            "Status: off\r\n",
02889                           chan->name, chan->uniqueid, conf->confno, user->user_no);
02890          }
02891          
02892          /* If I have been kicked, exit the conference */
02893          if (user->adminflags & ADMINFLAG_KICKME) {
02894             /* You have been kicked. */
02895             if (!(confflags & CONFFLAG_QUIET) && 
02896                !ast_streamfile(chan, "conf-kicked", chan->language)) {
02897                ast_waitstream(chan, "");
02898             }
02899             ret = 0;
02900             break;
02901          }
02902 
02903          /* Perform an extra hangup check just in case */
02904          if (ast_check_hangup(chan)) {
02905             break;
02906          }
02907 
02908          c = ast_waitfor_nandfds(&chan, 1, &fd, nfds, NULL, &outfd, &ms);
02909 
02910          if (c) {
02911             char dtmfstr[2] = "";
02912 
02913             if (c->fds[0] != origfd || (user->dahdichannel && (c->audiohooks || c->monitor))) {
02914                if (using_pseudo) {
02915                   /* Kill old pseudo */
02916                   close(fd);
02917                   using_pseudo = 0;
02918                }
02919                ast_debug(1, "Ooh, something swapped out under us, starting over\n");
02920                retrydahdi = (strcasecmp(c->tech->type, "DAHDI") || (c->audiohooks || c->monitor) ? 1 : 0);
02921                user->dahdichannel = !retrydahdi;
02922                goto dahdiretry;
02923             }
02924             if ((confflags & CONFFLAG_MONITOR) || (user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED))) {
02925                f = ast_read_noaudio(c);
02926             } else {
02927                f = ast_read(c);
02928             }
02929             if (!f) {
02930                break;
02931             }
02932             if (f->frametype == AST_FRAME_DTMF) {
02933                dtmfstr[0] = f->subclass;
02934                dtmfstr[1] = '\0';
02935             }
02936 
02937             if ((f->frametype == AST_FRAME_VOICE) && (f->subclass == AST_FORMAT_SLINEAR)) {
02938                if (user->talk.actual) {
02939                   ast_frame_adjust_volume(f, user->talk.actual);
02940                }
02941 
02942                if (confflags & (CONFFLAG_OPTIMIZETALKER | CONFFLAG_MONITORTALKER)) {
02943                   if (user->talking == -1) {
02944                      user->talking = 0;
02945                   }
02946 
02947                   res = ast_dsp_silence(dsp, f, &totalsilence);
02948                   if (totalsilence < MEETME_DELAYDETECTTALK) {
02949                      set_user_talking(chan, conf, user, 1, confflags & CONFFLAG_MONITORTALKER);
02950                   }
02951                   if (totalsilence > MEETME_DELAYDETECTENDTALK) {
02952                      set_user_talking(chan, conf, user, 0, confflags & CONFFLAG_MONITORTALKER);
02953                   }
02954                }
02955                if (using_pseudo) {
02956                   /* Absolutely do _not_ use careful_write here...
02957                      it is important that we read data from the channel
02958                      as fast as it arrives, and feed it into the conference.
02959                      The buffering in the pseudo channel will take care of any
02960                      timing differences, unless they are so drastic as to lose
02961                      audio frames (in which case carefully writing would only
02962                      have delayed the audio even further).
02963                   */
02964                   /* As it turns out, we do want to use careful write.  We just
02965                      don't want to block, but we do want to at least *try*
02966                      to write out all the samples.
02967                    */
02968                   if (user->talking || !(confflags & CONFFLAG_OPTIMIZETALKER)) {
02969                      careful_write(fd, f->data.ptr, f->datalen, 0);
02970                   }
02971                }
02972             } else if (((f->frametype == AST_FRAME_DTMF) && (f->subclass == '*') && (confflags & CONFFLAG_STARMENU)) || ((f->frametype == AST_FRAME_DTMF) && menu_active)) {
02973                if (confflags & CONFFLAG_PASS_DTMF) {
02974                   conf_queue_dtmf(conf, user, f);
02975                }
02976                if (ioctl(fd, DAHDI_SETCONF, &dahdic_empty)) {
02977                   ast_log(LOG_WARNING, "Error setting conference\n");
02978                   close(fd);
02979                   ast_frfree(f);
02980                   goto outrun;
02981                }
02982 
02983                /* if we are entering the menu, and the user has a channel-driver
02984                   volume adjustment, clear it
02985                */
02986                if (!menu_active && user->talk.desired && !user->talk.actual) {
02987                   set_talk_volume(user, 0);
02988                }
02989 
02990                if (musiconhold) {
02991                      ast_moh_stop(chan);
02992                }
02993                if ((confflags & CONFFLAG_ADMIN)) {
02994                   /* Admin menu */
02995                   if (!menu_active) {
02996                      menu_active = 1;
02997                      /* Record this sound! */
02998                      if (!ast_streamfile(chan, "conf-adminmenu-162", chan->language)) {
02999                         dtmf = ast_waitstream(chan, AST_DIGIT_ANY);
03000                         ast_stopstream(chan);
03001                      } else {
03002                         dtmf = 0;
03003                      }
03004                   } else {
03005                      dtmf = f->subclass;
03006                   }
03007                   if (dtmf) {
03008                      switch(dtmf) {
03009                      case '1': /* Un/Mute */
03010                         menu_active = 0;
03011 
03012                         /* for admin, change both admin and use flags */
03013                         if (user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) {
03014                            user->adminflags &= ~(ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED);
03015                         } else {
03016                            user->adminflags |= (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED);
03017                         }
03018 
03019                         if ((confflags & CONFFLAG_MONITOR) || (user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED))) {
03020                            if (!ast_streamfile(chan, "conf-muted", chan->language)) {
03021                               ast_waitstream(chan, "");
03022                            }
03023                         } else {
03024                            if (!ast_streamfile(chan, "conf-unmuted", chan->language)) {
03025                               ast_waitstream(chan, "");
03026                            }
03027                         }
03028                         break;
03029                      case '2': /* Un/Lock the Conference */
03030                         menu_active = 0;
03031                         if (conf->locked) {
03032                            conf->locked = 0;
03033                            if (!ast_streamfile(chan, "conf-unlockednow", chan->language)) {
03034                               ast_waitstream(chan, "");
03035                            }
03036                         } else {
03037                            conf->locked = 1;
03038                            if (!ast_streamfile(chan, "conf-lockednow", chan->language)) {
03039                               ast_waitstream(chan, "");
03040                            }
03041                         }
03042                         break;
03043                      case '3': /* Eject last user */
03044                      {
03045                         int max_no = 0;
03046                         menu_active = 0;
03047                         ao2_callback(conf->usercontainer, OBJ_NODATA, user_max_cmp, &max_no);
03048                         usr = ao2_find(conf->usercontainer, &max_no, 0);
03049                         if ((usr->chan->name == chan->name)||(usr->userflags & CONFFLAG_ADMIN)) {
03050                            if(!ast_streamfile(chan, "conf-errormenu", chan->language))
03051                               ast_waitstream(chan, "");
03052                         } else {
03053                            usr->adminflags |= ADMINFLAG_KICKME;
03054                         }
03055                         ao2_ref(user, -1);
03056                         ast_stopstream(chan);
03057                         break;
03058                      }
03059                      case '4':
03060                         tweak_listen_volume(user, VOL_DOWN);
03061                         break;
03062                      case '5':
03063                         /* Extend RT conference */
03064                         if (rt_schedule) {
03065                            if (!rt_extend_conf(conf->confno)) {
03066                               if (!ast_streamfile(chan, "conf-extended", chan->language)) {
03067                                  ast_waitstream(chan, "");
03068                               }
03069                            } else {
03070                               if (!ast_streamfile(chan, "conf-nonextended", chan->language)) {
03071                                  ast_waitstream(chan, "");
03072                               }
03073                            }
03074                            ast_stopstream(chan);
03075                         }
03076                         menu_active = 0;
03077                         break;
03078                      case '6':
03079                         tweak_listen_volume(user, VOL_UP);
03080                         break;
03081                      case '7':
03082                         tweak_talk_volume(user, VOL_DOWN);
03083                         break;
03084                      case '8':
03085                         menu_active = 0;
03086                         break;
03087                      case '9':
03088                         tweak_talk_volume(user, VOL_UP);
03089                         break;
03090                      default:
03091                         menu_active = 0;
03092                         /* Play an error message! */
03093                         if (!ast_streamfile(chan, "conf-errormenu", chan->language)) {
03094                            ast_waitstream(chan, "");
03095                         }
03096                         break;
03097                      }
03098                   }
03099                } else {
03100                   /* User menu */
03101                   if (!menu_active) {
03102                      menu_active = 1;
03103                      if (!ast_streamfile(chan, "conf-usermenu-162", chan->language)) {
03104                         dtmf = ast_waitstream(chan, AST_DIGIT_ANY);
03105                         ast_stopstream(chan);
03106                      } else {
03107                         dtmf = 0;
03108                      }
03109                   } else {
03110                      dtmf = f->subclass;
03111                   }
03112                   if (dtmf) {
03113                      switch (dtmf) {
03114                      case '1': /* Un/Mute */
03115                         menu_active = 0;
03116 
03117                         /* user can only toggle the self-muted state */
03118                         user->adminflags ^= ADMINFLAG_SELFMUTED;
03119 
03120                         /* they can't override the admin mute state */
03121                         if ((confflags & CONFFLAG_MONITOR) || (user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED))) {
03122                            if (!ast_streamfile(chan, "conf-muted", chan->language)) {
03123                               ast_waitstream(chan, "");
03124                            }
03125                         } else {
03126                            if (!ast_streamfile(chan, "conf-unmuted", chan->language)) {
03127                               ast_waitstream(chan, "");
03128                            }
03129                         }
03130                         break;
03131                      case '2':
03132                         menu_active = 0;
03133                         if (user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) {
03134                            user->adminflags |= ADMINFLAG_T_REQUEST;
03135                         }
03136                            
03137                         if (user->adminflags & ADMINFLAG_T_REQUEST) {
03138                            if (!ast_streamfile(chan, "beep", chan->language)) {
03139                               ast_waitstream(chan, "");
03140                            }
03141                         }
03142                         break;
03143                      case '4':
03144                         tweak_listen_volume(user, VOL_DOWN);
03145                         break;
03146                      case '5':
03147                         /* Extend RT conference */
03148                         if (rt_schedule) {
03149                            rt_extend_conf(conf->confno);
03150                         }
03151                         menu_active = 0;
03152                         break;
03153                      case '6':
03154                         tweak_listen_volume(user, VOL_UP);
03155                         break;
03156                      case '7':
03157                         tweak_talk_volume(user, VOL_DOWN);
03158                         break;
03159                      case '8':
03160                         menu_active = 0;
03161                         break;
03162                      case '9':
03163                         tweak_talk_volume(user, VOL_UP);
03164                         break;
03165                      default:
03166                         menu_active = 0;
03167                         if (!ast_streamfile(chan, "conf-errormenu", chan->language)) {
03168                            ast_waitstream(chan, "");
03169                         }
03170                         break;
03171                      }
03172                   }
03173                }
03174                if (musiconhold) {
03175                   conf_start_moh(chan, optargs[OPT_ARG_MOH_CLASS]);
03176                }
03177 
03178                if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
03179                   ast_log(LOG_WARNING, "Error setting conference\n");
03180                   close(fd);
03181                   ast_frfree(f);
03182                   goto outrun;
03183                }
03184 
03185                conf_flush(fd, chan);
03186             /* Since this option could absorb DTMF meant for the previous (menu), we have to check this one last */
03187             } else if ((f->frametype == AST_FRAME_DTMF) && (confflags & CONFFLAG_EXIT_CONTEXT) && ast_exists_extension(chan, exitcontext, dtmfstr, 1, "")) {
03188                if (confflags & CONFFLAG_PASS_DTMF) {
03189                   conf_queue_dtmf(conf, user, f);
03190                }
03191 
03192                if (!ast_goto_if_exists(chan, exitcontext, dtmfstr, 1)) {
03193                   ast_debug(1, "Got DTMF %c, goto context %s\n", dtmfstr[0], exitcontext);
03194                   ret = 0;
03195                   ast_frfree(f);
03196                   break;
03197                } else {
03198                   ast_debug(2, "Exit by single digit did not work in meetme. Extension %s does not exist in context %s\n", dtmfstr, exitcontext);
03199                }
03200             } else if ((f->frametype == AST_FRAME_DTMF) && (confflags & CONFFLAG_KEYEXIT) && (strchr(exitkeys, f->subclass))) {
03201                pbx_builtin_setvar_helper(chan, "MEETME_EXIT_KEY", dtmfstr);
03202                   
03203                if (confflags & CONFFLAG_PASS_DTMF) {
03204                   conf_queue_dtmf(conf, user, f);
03205                }
03206                ret = 0;
03207                ast_frfree(f);
03208                break;
03209             } else if ((f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END)
03210                && confflags & CONFFLAG_PASS_DTMF) {
03211                conf_queue_dtmf(conf, user, f);
03212             } else if ((confflags & CONFFLAG_SLA_STATION) && f->frametype == AST_FRAME_CONTROL) {
03213                switch (f->subclass) {
03214                case AST_CONTROL_HOLD:
03215                   sla_queue_event_conf(SLA_EVENT_HOLD, chan, conf);
03216                   break;
03217                default:
03218                   break;
03219                }
03220             } else if (f->frametype == AST_FRAME_NULL) {
03221                /* Ignore NULL frames. It is perfectly normal to get these if the person is muted. */
03222             } else if (f->frametype == AST_FRAME_CONTROL) {
03223                switch (f->subclass) {
03224                case AST_CONTROL_BUSY:
03225                case AST_CONTROL_CONGESTION:
03226                   ast_frfree(f);
03227                   goto outrun;
03228                   break;
03229                default:
03230                   ast_debug(1, 
03231                      "Got ignored control frame on channel %s, f->frametype=%d,f->subclass=%d\n",
03232                      chan->name, f->frametype, f->subclass);
03233                }
03234             } else {
03235                ast_debug(1, 
03236                   "Got unrecognized frame on channel %s, f->frametype=%d,f->subclass=%d\n",
03237                   chan->name, f->frametype, f->subclass);
03238             }
03239             ast_frfree(f);
03240          } else if (outfd > -1) {
03241             res = read(outfd, buf, CONF_SIZE);
03242             if (res > 0) {
03243                memset(&fr, 0, sizeof(fr));
03244                fr.frametype = AST_FRAME_VOICE;
03245                fr.subclass = AST_FORMAT_SLINEAR;
03246                fr.datalen = res;
03247                fr.samples = res / 2;
03248                fr.data.ptr = buf;
03249                fr.offset = AST_FRIENDLY_OFFSET;
03250                if (!user->listen.actual &&
03251                   ((confflags & CONFFLAG_MONITOR) ||
03252                    (user->adminflags & (ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED)) ||
03253                    (!user->talking && (confflags & CONFFLAG_OPTIMIZETALKER))
03254                    )) {
03255                   int idx;
03256                   for (idx = 0; idx < AST_FRAME_BITS; idx++) {
03257                      if (chan->rawwriteformat & (1 << idx)) {
03258                         break;
03259                      }
03260                   }
03261                   if (idx >= AST_FRAME_BITS) {
03262                      goto bailoutandtrynormal;
03263                   }
03264                   ast_mutex_lock(&conf->listenlock);
03265                   if (!conf->transframe[idx]) {
03266                      if (conf->origframe) {
03267                         if (musiconhold && !ast_dsp_silence(dsp, conf->origframe, &confsilence) && confsilence < MEETME_DELAYDETECTTALK) {
03268                            ast_moh_stop(chan);
03269                            mohtempstopped = 1;
03270                         }
03271                         if (!conf->transpath[idx]) {
03272                            conf->transpath[idx] = ast_translator_build_path((1 << idx), AST_FORMAT_SLINEAR);
03273                         }
03274                         if (conf->transpath[idx]) {
03275                            conf->transframe[idx] = ast_translate(conf->transpath[idx], conf->origframe, 0);
03276                            if (!conf->transframe[idx]) {
03277                               conf->transframe[idx] = &ast_null_frame;
03278                            }
03279                         }
03280                      }
03281                   }
03282                   if (conf->transframe[idx]) {
03283                      if ((conf->transframe[idx]->frametype != AST_FRAME_NULL) &&
03284                          can_write(chan, confflags)) {
03285                         struct ast_frame *cur;
03286                         /* the translator may have returned a list of frames, so
03287                            write each one onto the channel
03288                         */
03289                         for (cur = conf->transframe[idx]; cur; cur = AST_LIST_NEXT(cur, frame_list)) {
03290                            if (ast_write(chan, cur)) {
03291                               ast_log(LOG_WARNING, "Unable to write frame to channel %s\n", chan->name);
03292                               break;
03293                            }
03294                         }
03295                         if (musiconhold && mohtempstopped && confsilence > MEETME_DELAYDETECTENDTALK) {
03296                            mohtempstopped = 0;
03297                            ast_moh_start(chan, NULL, NULL);
03298                         }
03299                      }
03300                   } else {
03301                      ast_mutex_unlock(&conf->listenlock);
03302                      goto bailoutandtrynormal;
03303                   }
03304                   ast_mutex_unlock(&conf->listenlock);
03305                } else {
03306 bailoutandtrynormal:
03307                   if (musiconhold && !ast_dsp_silence(dsp, &fr, &confsilence) && confsilence < MEETME_DELAYDETECTTALK) {
03308                      ast_moh_stop(chan);
03309                      mohtempstopped = 1;
03310                   }
03311                   if (user->listen.actual) {
03312                      ast_frame_adjust_volume(&fr, user->listen.actual);
03313                   }
03314                   if (can_write(chan, confflags) && ast_write(chan, &fr) < 0) {
03315                      ast_log(LOG_WARNING, "Unable to write frame to channel %s\n", chan->name);
03316                   }
03317                   if (musiconhold && mohtempstopped && confsilence > MEETME_DELAYDETECTENDTALK) {
03318                      mohtempstopped = 0;
03319                      ast_moh_start(chan, NULL, NULL);
03320                   }
03321                }
03322             } else {
03323                ast_log(LOG_WARNING, "Failed to read frame: %s\n", strerror(errno));
03324             }
03325          }
03326          lastmarked = currentmarked;
03327       }
03328    }
03329 
03330    if (musiconhold) {
03331       ast_moh_stop(chan);
03332    }
03333    
03334    if (using_pseudo) {
03335       close(fd);
03336    } else {
03337       /* Take out of conference */
03338       dahdic.chan = 0;  
03339       dahdic.confno = 0;
03340       dahdic.confmode = 0;
03341       if (ioctl(fd, DAHDI_SETCONF, &dahdic)) {
03342          ast_log(LOG_WARNING, "Error setting conference\n");
03343       }
03344    }
03345 
03346    reset_volumes(user);
03347 
03348    if (!(confflags & CONFFLAG_QUIET) && !(confflags & CONFFLAG_MONITOR) && !(confflags & CONFFLAG_ADMIN)) {
03349       conf_play(chan, conf, LEAVE);
03350    }
03351 
03352    if (!(confflags & CONFFLAG_QUIET) && ((confflags & CONFFLAG_INTROUSER) || (confflags & CONFFLAG_INTROUSERNOREVIEW)) && conf->users > 1) {
03353       struct announce_listitem *item;
03354       if (!(item = ao2_alloc(sizeof(*item), NULL)))
03355          return -1;
03356       ast_copy_string(item->namerecloc, user->namerecloc, sizeof(item->namerecloc));
03357       ast_copy_string(item->language, chan->language, sizeof(item->language));
03358       item->confchan = conf->chan;
03359       item->confusers = conf->users;
03360       item->announcetype = CONF_HASLEFT;
03361       ast_mutex_lock(&conf->announcelistlock);
03362       AST_LIST_INSERT_TAIL(&conf->announcelist, item, entry);
03363       ast_cond_signal(&conf->announcelist_addition);
03364       ast_mutex_unlock(&conf->announcelistlock);
03365    } else if (!(confflags & CONFFLAG_QUIET) && ((confflags & CONFFLAG_INTROUSER) || (confflags & CONFFLAG_INTROUSERNOREVIEW)) && conf->users == 1) {
03366       /* Last person is leaving, so no reason to try and announce, but should delete the name recording */
03367       ast_filedelete(user->namerecloc, NULL);
03368    }
03369 
03370  outrun:
03371    AST_LIST_LOCK(&confs);
03372 
03373    if (dsp) {
03374       ast_dsp_free(dsp);
03375    }
03376    
03377    if (!user->user_no) {
03378       ao2_ref(user, -1);
03379    } else { /* Only cleanup users who really joined! */
03380       now = ast_tvnow();
03381       hr = (now.tv_sec - user->jointime) / 3600;
03382       min = ((now.tv_sec - user->jointime) % 3600) / 60;
03383       sec = (now.tv_sec - user->jointime) % 60;
03384 
03385       if (sent_event) {
03386          manager_event(EVENT_FLAG_CALL, "MeetmeLeave",
03387                   "Channel: %s\r\n"
03388                   "Uniqueid: %s\r\n"
03389                   "Meetme: %s\r\n"
03390                   "Usernum: %d\r\n"
03391                   "CallerIDNum: %s\r\n"
03392                   "CallerIDName: %s\r\n"
03393                   "Duration: %ld\r\n",
03394                   chan->name, chan->uniqueid, conf->confno, 
03395                   user->user_no,
03396                   S_OR(user->chan->cid.cid_num, "<unknown>"),
03397                   S_OR(user->chan->cid.cid_name, "<unknown>"),
03398                   (long)(now.tv_sec - user->jointime));
03399       }
03400 
03401       if (setusercount) {
03402          conf->users--;
03403          if (rt_log_members) {
03404             /* Update table */
03405             snprintf(members, sizeof(members), "%d", conf->users);
03406             ast_realtime_require_field("meetme",
03407                "confno", strlen(conf->confno) > 7 ? RQ_UINTEGER4 : strlen(conf->confno) > 4 ? RQ_UINTEGER3 : RQ_UINTEGER2, strlen(conf->confno),
03408                "members", RQ_UINTEGER1, strlen(members),
03409                NULL);
03410             ast_update_realtime("meetme", "confno", conf->confno, "members", members, NULL);
03411          }
03412          if (confflags & CONFFLAG_MARKEDUSER) {
03413             conf->markedusers--;
03414          }
03415       }
03416       /* Remove ourselves from the container */
03417       ao2_unlink(conf->usercontainer, user); 
03418 
03419       /* Change any states */
03420       if (!conf->users) {
03421          ast_devstate_changed(AST_DEVICE_NOT_INUSE, "meetme:%s", conf->confno);
03422       }
03423 
03424       /* Return the number of seconds the user was in the conf */
03425       snprintf(meetmesecs, sizeof(meetmesecs), "%d", (int) (time(NULL) - user->jointime));
03426       pbx_builtin_setvar_helper(chan, "MEETMESECS", meetmesecs);
03427 
03428       /* Return the RealTime bookid for CDR linking */
03429       if (rt_schedule) {
03430          pbx_builtin_setvar_helper(chan, "MEETMEBOOKID", conf->bookid);
03431       }
03432    }
03433    AST_LIST_UNLOCK(&confs);
03434 
03435    return ret;
03436 }
03437 
03438 static struct ast_conference *find_conf_realtime(struct ast_channel *chan, char *confno, int make, int dynamic,
03439             char *dynamic_pin, size_t pin_buf_len, int refcount, struct ast_flags *confflags, int *too_early, char **optargs)
03440 {
03441    struct ast_variable *var, *origvar;
03442    struct ast_conference *cnf;
03443 
03444    *too_early = 0;
03445 
03446    /* Check first in the conference list */
03447    AST_LIST_LOCK(&confs);
03448    AST_LIST_TRAVERSE(&confs, cnf, list) {
03449       if (!strcmp(confno, cnf->confno)) {
03450          break;
03451       }
03452    }
03453    if (cnf) {
03454       cnf->refcount += refcount;
03455    }
03456    AST_LIST_UNLOCK(&confs);
03457 
03458    if (!cnf) {
03459       char *pin = NULL, *pinadmin = NULL; /* For temp use */
03460       int maxusers = 0;
03461       struct timeval now;
03462       char recordingfilename[256] = "";
03463       char recordingformat[11] = "";
03464       char currenttime[19] = "";
03465       char eatime[19] = "";
03466       char bookid[51] = "";
03467       char recordingtmp[AST_MAX_EXTENSION] = "";
03468       char useropts[OPTIONS_LEN + 1]; /* Used for RealTime conferences */
03469       char adminopts[OPTIONS_LEN + 1];
03470       struct ast_tm tm, etm;
03471       struct timeval endtime = { .tv_sec = 0 };
03472       const char *var2;
03473 
03474       if (rt_schedule) {
03475          now = ast_tvnow();
03476 
03477          ast_localtime(&now, &tm, NULL);
03478          ast_strftime(currenttime, sizeof(currenttime), DATE_FORMAT, &tm);
03479 
03480          ast_debug(1, "Looking for conference %s that starts after %s\n", confno, eatime);
03481 
03482          var = ast_load_realtime("meetme", "confno",
03483             confno, "starttime <= ", currenttime, "endtime >= ",
03484             currenttime, NULL);
03485 
03486          if (!var && fuzzystart) {
03487             now = ast_tvnow();
03488             now.tv_sec += fuzzystart;
03489 
03490             ast_localtime(&now, &tm, NULL);
03491             ast_strftime(currenttime, sizeof(currenttime), DATE_FORMAT, &tm);
03492             var = ast_load_realtime("meetme", "confno",
03493                confno, "starttime <= ", currenttime, "endtime >= ",
03494                currenttime, NULL);
03495          }
03496 
03497          if (!var && earlyalert) {
03498             now = ast_tvnow();
03499             now.tv_sec += earlyalert;
03500             ast_localtime(&now, &etm, NULL);
03501             ast_strftime(eatime, sizeof(eatime), DATE_FORMAT, &etm);
03502             var = ast_load_realtime("meetme", "confno",
03503                confno, "starttime <= ", eatime, "endtime >= ",
03504                currenttime, NULL);
03505             if (var) {
03506                *too_early = 1;
03507             }
03508          }
03509 
03510       } else {
03511           var = ast_load_realtime("meetme", "confno", confno, NULL);
03512       }
03513 
03514       if (!var) {
03515          return NULL;
03516       }
03517 
03518       if (rt_schedule && *too_early) {
03519          /* Announce that the caller is early and exit */
03520          if (!ast_streamfile(chan, "conf-has-not-started", chan->language)) {
03521             ast_waitstream(chan, "");
03522          }
03523          ast_variables_destroy(var);
03524          return NULL;
03525       }
03526 
03527       for (origvar = var; var; var = var->next) {
03528          if (!strcasecmp(var->name, "pin")) {
03529             pin = ast_strdupa(var->value);
03530          } else if (!strcasecmp(var->name, "adminpin")) {
03531             pinadmin = ast_strdupa(var->value);
03532          } else if (!strcasecmp(var->name, "bookId")) {
03533             ast_copy_string(bookid, var->value, sizeof(bookid));
03534          } else if (!strcasecmp(var->name, "opts")) {
03535             ast_copy_string(useropts, var->value, sizeof(char[OPTIONS_LEN + 1]));
03536          } else if (!strcasecmp(var->name, "maxusers")) {
03537             maxusers = atoi(var->value);
03538          } else if (!strcasecmp(var->name, "adminopts")) {
03539             ast_copy_string(adminopts, var->value, sizeof(char[OPTIONS_LEN + 1]));
03540          } else if (!strcasecmp(var->name, "recordingfilename")) {
03541             ast_copy_string(recordingfilename, var->value, sizeof(recordingfilename));
03542          } else if (!strcasecmp(var->name, "recordingformat")) {
03543             ast_copy_string(recordingformat, var->value, sizeof(recordingformat));
03544          } else if (!strcasecmp(var->name, "endtime")) {
03545             struct ast_tm endtime_tm;
03546             ast_strptime(var->value, "%Y-%m-%d %H:%M:%S", &endtime_tm);
03547             endtime = ast_mktime(&endtime_tm, NULL);
03548          }
03549       }
03550 
03551       ast_variables_destroy(origvar);
03552 
03553       cnf = build_conf(confno, pin ? pin : "", pinadmin ? pinadmin : "", make, dynamic, refcount, chan);
03554 
03555       if (cnf) {
03556          struct ast_flags tmp_flags;
03557 
03558          cnf->maxusers = maxusers;
03559          cnf->endalert = endalert;
03560          cnf->endtime = endtime.tv_sec;
03561          cnf->useropts = ast_strdup(useropts);
03562          cnf->adminopts = ast_strdup(adminopts);
03563          cnf->bookid = ast_strdup(bookid);
03564          cnf->recordingfilename = ast_strdup(recordingfilename);
03565          cnf->recordingformat = ast_strdup(recordingformat);
03566 
03567          /* Parse the other options into confflags -- need to do this in two
03568           * steps, because the parse_options routine zeroes the buffer. */
03569          ast_app_parse_options(meetme_opts, &tmp_flags, optargs, useropts);
03570          ast_copy_flags(confflags, &tmp_flags, tmp_flags.flags);
03571 
03572          if (strchr(cnf->useropts, 'r')) {
03573             if (ast_strlen_zero(recordingfilename)) { /* If the recordingfilename in the database is empty, use the channel definition or use the default. */
03574                ast_channel_lock(chan);
03575                if ((var2 = pbx_builtin_getvar_helper(chan, "MEETME_RECORDINGFILE"))) {
03576                   ast_free(cnf->recordingfilename);
03577                   cnf->recordingfilename = ast_strdup(var2);
03578                }
03579                ast_channel_unlock(chan);
03580                if (ast_strlen_zero(cnf->recordingfilename)) {
03581                   snprintf(recordingtmp, sizeof(recordingtmp), "meetme-conf-rec-%s-%s", cnf->confno, chan->uniqueid);
03582                   ast_free(cnf->recordingfilename);
03583                   cnf->recordingfilename = ast_strdup(recordingtmp);
03584                }
03585             }
03586             if (ast_strlen_zero(cnf->recordingformat)) {/* If the recording format is empty, use the wav as default */
03587                ast_channel_lock(chan);
03588                if ((var2 = pbx_builtin_getvar_helper(chan, "MEETME_RECORDINGFORMAT"))) {
03589                   ast_free(cnf->recordingformat);
03590                   cnf->recordingformat = ast_strdup(var2);
03591                }
03592                ast_channel_unlock(chan);
03593                if (ast_strlen_zero(cnf->recordingformat)) {
03594                   ast_free(cnf->recordingformat);
03595                   cnf->recordingformat = ast_strdup("wav");
03596                }
03597             }
03598             ast_verb(4, "Starting recording of MeetMe Conference %s into file %s.%s.\n", cnf->confno, cnf->recordingfilename, cnf->recordingformat);
03599          }
03600       }
03601    }
03602 
03603    if (cnf) {
03604       if (confflags && !cnf->chan &&
03605           !ast_test_flag(confflags, CONFFLAG_QUIET) &&
03606           ast_test_flag(confflags, CONFFLAG_INTROUSER | CONFFLAG_INTROUSERNOREVIEW)) {
03607          ast_log(LOG_WARNING, "No DAHDI channel available for conference, user introduction disabled (is chan_dahdi loaded?)\n");
03608          ast_clear_flag(confflags, CONFFLAG_INTROUSER | CONFFLAG_INTROUSERNOREVIEW);
03609       }
03610 
03611       if (confflags && !cnf->chan &&
03612           ast_test_flag(confflags, CONFFLAG_RECORDCONF)) {
03613          ast_log(LOG_WARNING, "No DAHDI channel available for conference, conference recording disabled (is chan_dahdi loaded?)\n");
03614          ast_clear_flag(confflags, CONFFLAG_RECORDCONF);
03615       }
03616    }
03617 
03618    return cnf;
03619 }
03620 
03621 
03622 static struct ast_conference *find_conf(struct ast_channel *chan, char *confno, int make, int dynamic,
03623                char *dynamic_pin, size_t pin_buf_len, int refcount, struct ast_flags *confflags)
03624 {
03625    struct ast_config *cfg;
03626    struct ast_variable *var;
03627    struct ast_flags config_flags = { 0 };
03628    struct ast_conference *cnf;
03629 
03630    AST_DECLARE_APP_ARGS(args,
03631       AST_APP_ARG(confno);
03632       AST_APP_ARG(pin);
03633       AST_APP_ARG(pinadmin);
03634    );
03635 
03636    /* Check first in the conference list */
03637    ast_debug(1, "The requested confno is '%s'?\n", confno);
03638    AST_LIST_LOCK(&confs);
03639    AST_LIST_TRAVERSE(&confs, cnf, list) {
03640       ast_debug(3, "Does conf %s match %s?\n", confno, cnf->confno);
03641       if (!strcmp(confno, cnf->confno)) 
03642          break;
03643    }
03644    if (cnf) {
03645       cnf->refcount += refcount;
03646    }
03647    AST_LIST_UNLOCK(&confs);
03648 
03649    if (!cnf) {
03650       if (dynamic) {
03651          /* No need to parse meetme.conf */
03652          ast_debug(1, "Building dynamic conference '%s'\n", confno);
03653          if (dynamic_pin) {
03654             if (dynamic_pin[0] == 'q') {
03655                /* Query the user to enter a PIN */
03656                if (ast_app_getdata(chan, "conf-getpin", dynamic_pin, pin_buf_len - 1, 0) < 0)
03657                   return NULL;
03658             }
03659             cnf = build_conf(confno, dynamic_pin, "", make, dynamic, refcount, chan);
03660          } else {
03661             cnf = build_conf(confno, "", "", make, dynamic, refcount, chan);
03662          }
03663       } else {
03664          /* Check the config */
03665          cfg = ast_config_load(CONFIG_FILE_NAME, config_flags);
03666          if (!cfg) {
03667             ast_log(LOG_WARNING, "No %s file :(\n", CONFIG_FILE_NAME);
03668             return NULL;
03669          } else if (cfg == CONFIG_STATUS_FILEINVALID) {
03670             ast_log(LOG_ERROR, "Config file " CONFIG_FILE_NAME " is in an invalid format.  Aborting.\n");
03671             return NULL;
03672          }
03673 
03674          for (var = ast_variable_browse(cfg, "rooms"); var; var = var->next) {
03675             char parse[MAX_SETTINGS];
03676 
03677             if (strcasecmp(var->name, "conf"))
03678                continue;
03679 
03680             ast_copy_string(parse, var->value, sizeof(parse));
03681 
03682             AST_STANDARD_APP_ARGS(args, parse);
03683             ast_debug(3, "Will conf %s match %s?\n", confno, args.confno);
03684             if (!strcasecmp(args.confno, confno)) {
03685                /* Bingo it's a valid conference */
03686                cnf = build_conf(args.confno,
03687                      S_OR(args.pin, ""),
03688                      S_OR(args.pinadmin, ""),
03689                      make, dynamic, refcount, chan);
03690                break;
03691             }
03692          }
03693          if (!var) {
03694             ast_debug(1, "%s isn't a valid conference\n", confno);
03695          }
03696          ast_config_destroy(cfg);
03697       }
03698    } else if (dynamic_pin) {
03699       /* Correct for the user selecting 'D' instead of 'd' to have
03700          someone join into a conference that has already been created
03701          with a pin. */
03702       if (dynamic_pin[0] == 'q') {
03703          dynamic_pin[0] = '\0';
03704       }
03705    }
03706 
03707    if (cnf) {
03708       if (confflags && !cnf->chan &&
03709           !ast_test_flag(confflags, CONFFLAG_QUIET) &&
03710           ast_test_flag(confflags, CONFFLAG_INTROUSER | CONFFLAG_INTROUSERNOREVIEW)) {
03711          ast_log(LOG_WARNING, "No DAHDI channel available for conference, user introduction disabled (is chan_dahdi loaded?)\n");
03712          ast_clear_flag(confflags, CONFFLAG_INTROUSER | CONFFLAG_INTROUSERNOREVIEW);
03713       }
03714       
03715       if (confflags && !cnf->chan &&
03716           ast_test_flag(confflags, CONFFLAG_RECORDCONF)) {
03717          ast_log(LOG_WARNING, "No DAHDI channel available for conference, conference recording disabled (is chan_dahdi loaded?)\n");
03718          ast_clear_flag(confflags, CONFFLAG_RECORDCONF);
03719       }
03720    }
03721 
03722    return cnf;
03723 }
03724 
03725 /*! \brief The MeetmeCount application */
03726 static int count_exec(struct ast_channel *chan, void *data)
03727 {
03728    int res = 0;
03729    struct ast_conference *conf;
03730    int count;
03731    char *localdata;
03732    char val[80] = "0"; 
03733    AST_DECLARE_APP_ARGS(args,
03734       AST_APP_ARG(confno);
03735       AST_APP_ARG(varname);
03736    );
03737 
03738    if (ast_strlen_zero(data)) {
03739       ast_log(LOG_WARNING, "MeetMeCount requires an argument (conference number)\n");
03740       return -1;
03741    }
03742    
03743    if (!(localdata = ast_strdupa(data)))
03744       return -1;
03745 
03746    AST_STANDARD_APP_ARGS(args, localdata);
03747    
03748    conf = find_conf(chan, args.confno, 0, 0, NULL, 0, 1, NULL);
03749 
03750    if (conf) {
03751       count = conf->users;
03752       dispose_conf(conf);
03753       conf = NULL;
03754    } else
03755       count = 0;
03756 
03757    if (!ast_strlen_zero(args.varname)) {
03758       /* have var so load it and exit */
03759       snprintf(val, sizeof(val), "%d", count);
03760       pbx_builtin_setvar_helper(chan, args.varname, val);
03761    } else {
03762       if (chan->_state != AST_STATE_UP) {
03763          ast_answer(chan);
03764       }
03765       res = ast_say_number(chan, count, "", chan->language, (char *) NULL); /* Needs gender */
03766    }
03767 
03768    return res;
03769 }
03770 
03771 /*! \brief The meetme() application */
03772 static int conf_exec(struct ast_channel *chan, void *data)
03773 {
03774    int res = -1;
03775    char confno[MAX_CONFNUM] = "";
03776    int allowretry = 0;
03777    int retrycnt = 0;
03778    struct ast_conference *cnf = NULL;
03779    struct ast_flags confflags = {0}, config_flags = { 0 };
03780    int dynamic = 0;
03781    int empty = 0, empty_no_pin = 0;
03782    int always_prompt = 0;
03783    char *notdata, *info, the_pin[MAX_PIN] = "";
03784    AST_DECLARE_APP_ARGS(args,
03785       AST_APP_ARG(confno);
03786       AST_APP_ARG(options);
03787       AST_APP_ARG(pin);
03788    );
03789    char *optargs[OPT_ARG_ARRAY_SIZE] = { NULL, };
03790 
03791    if (ast_strlen_zero(data)) {
03792       allowretry = 1;
03793       notdata = "";
03794    } else {
03795       notdata = data;
03796    }
03797    
03798    if (chan->_state != AST_STATE_UP)
03799       ast_answer(chan);
03800 
03801    info = ast_strdupa(notdata);
03802 
03803    AST_STANDARD_APP_ARGS(args, info);  
03804 
03805    if (args.confno) {
03806       ast_copy_string(confno, args.confno, sizeof(confno));
03807       if (ast_strlen_zero(confno)) {
03808          allowretry = 1;
03809       }
03810    }
03811    
03812    if (args.pin)
03813       ast_copy_string(the_pin, args.pin, sizeof(the_pin));
03814 
03815    if (args.options) {
03816       ast_app_parse_options(meetme_opts, &confflags, optargs, args.options);
03817       dynamic = ast_test_flag(&confflags, CONFFLAG_DYNAMIC | CONFFLAG_DYNAMICPIN);
03818       if (ast_test_flag(&confflags, CONFFLAG_DYNAMICPIN) && ast_strlen_zero(args.pin))
03819          strcpy(the_pin, "q");
03820 
03821       empty = ast_test_flag(&confflags, CONFFLAG_EMPTY | CONFFLAG_EMPTYNOPIN);
03822       empty_no_pin = ast_test_flag(&confflags, CONFFLAG_EMPTYNOPIN);
03823       always_prompt = ast_test_flag(&confflags, CONFFLAG_ALWAYSPROMPT | CONFFLAG_DYNAMICPIN);
03824    }
03825 
03826    do {
03827       if (retrycnt > 3)
03828          allowretry = 0;
03829       if (empty) {
03830          int i;
03831          struct ast_config *cfg;
03832          struct ast_variable *var;
03833          int confno_int;
03834 
03835          /* We only need to load the config file for static and empty_no_pin (otherwise we don't care) */
03836          if ((empty_no_pin) || (!dynamic)) {
03837             cfg = ast_config_load(CONFIG_FILE_NAME, config_flags);
03838             if (cfg && cfg != CONFIG_STATUS_FILEINVALID) {
03839                var = ast_variable_browse(cfg, "rooms");
03840                while (var) {
03841                   char parse[MAX_SETTINGS], *stringp = parse, *confno_tmp;
03842                   if (!strcasecmp(var->name, "conf")) {
03843                      int found = 0;
03844                      ast_copy_string(parse, var->value, sizeof(parse));
03845                      confno_tmp = strsep(&stringp, "|,");
03846                      if (!dynamic) {
03847                         /* For static:  run through the list and see if this conference is empty */
03848                         AST_LIST_LOCK(&confs);
03849                         AST_LIST_TRAVERSE(&confs, cnf, list) {
03850                            if (!strcmp(confno_tmp, cnf->confno)) {
03851                               /* The conference exists, therefore it's not empty */
03852                               found = 1;
03853                               break;
03854                            }
03855                         }
03856                         AST_LIST_UNLOCK(&confs);
03857                         if (!found) {
03858                            /* At this point, we have a confno_tmp (static conference) that is empty */
03859                            if ((empty_no_pin && ast_strlen_zero(stringp)) || (!empty_no_pin)) {
03860                               /* Case 1:  empty_no_pin and pin is nonexistent (NULL)
03861                                * Case 2:  empty_no_pin and pin is blank (but not NULL)
03862                                * Case 3:  not empty_no_pin
03863                                */
03864                               ast_copy_string(confno, confno_tmp, sizeof(confno));
03865                               break;
03866                            }
03867                         }
03868                      }
03869                   }
03870                   var = var->next;
03871                }
03872                ast_config_destroy(cfg);
03873             }
03874 
03875             if (ast_strlen_zero(confno) && (cfg = ast_load_realtime_multientry("meetme", "confno LIKE", "%", SENTINEL))) {
03876                const char *catg;
03877                for (catg = ast_category_browse(cfg, NULL); catg; catg = ast_category_browse(cfg, catg)) {
03878                   const char *confno_tmp = ast_variable_retrieve(cfg, catg, "confno");
03879                   const char *pin_tmp = ast_variable_retrieve(cfg, catg, "pin");
03880                   if (ast_strlen_zero(confno_tmp)) {
03881                      continue;
03882                   }
03883                   if (!dynamic) {
03884                      int found = 0;
03885                      /* For static:  run through the list and see if this conference is empty */
03886                      AST_LIST_LOCK(&confs);
03887                      AST_LIST_TRAVERSE(&confs, cnf, list) {
03888                         if (!strcmp(confno_tmp, cnf->confno)) {
03889                            /* The conference exists, therefore it's not empty */
03890                            found = 1;
03891                            break;
03892                         }
03893                      }
03894                      AST_LIST_UNLOCK(&confs);
03895                      if (!found) {
03896                         /* At this point, we have a confno_tmp (realtime conference) that is empty */
03897                         if ((empty_no_pin && ast_strlen_zero(pin_tmp)) || (!empty_no_pin)) {
03898                            /* Case 1:  empty_no_pin and pin is nonexistent (NULL)
03899                             * Case 2:  empty_no_pin and pin is blank (but not NULL)
03900                             * Case 3:  not empty_no_pin
03901                             */
03902                            ast_copy_string(confno, confno_tmp, sizeof(confno));
03903                            break;
03904                         }
03905                      }
03906                   }
03907                }
03908                ast_config_destroy(cfg);
03909             }
03910          }
03911 
03912          /* Select first conference number not in use */
03913          if (ast_strlen_zero(confno) && dynamic) {
03914             AST_LIST_LOCK(&confs);
03915             for (i = 0; i < ARRAY_LEN(conf_map); i++) {
03916                if (!conf_map[i]) {
03917                   snprintf(confno, sizeof(confno), "%d", i);
03918                   conf_map[i] = 1;
03919                   break;
03920                }
03921             }
03922             AST_LIST_UNLOCK(&confs);
03923          }
03924 
03925          /* Not found? */
03926          if (ast_strlen_zero(confno)) {
03927             res = ast_streamfile(chan, "conf-noempty", chan->language);
03928             if (!res)
03929                ast_waitstream(chan, "");
03930          } else {
03931             if (sscanf(confno, "%30d", &confno_int) == 1) {
03932                if (!ast_test_flag(&confflags, CONFFLAG_QUIET)) {
03933                   res = ast_streamfile(chan, "conf-enteringno", chan->language);
03934                   if (!res) {
03935                      ast_waitstream(chan, "");
03936                      res = ast_say_digits(chan, confno_int, "", chan->language);
03937                   }
03938                }
03939             } else {
03940                ast_log(LOG_ERROR, "Could not scan confno '%s'\n", confno);
03941             }
03942          }
03943       }
03944 
03945       while (allowretry && (ast_strlen_zero(confno)) && (++retrycnt < 4)) {
03946          /* Prompt user for conference number */
03947          res = ast_app_getdata(chan, "conf-getconfno", confno, sizeof(confno) - 1, 0);
03948          if (res < 0) {
03949             /* Don't try to validate when we catch an error */
03950             confno[0] = '\0';
03951             allowretry = 0;
03952             break;
03953          }
03954       }
03955       if (!ast_strlen_zero(confno)) {
03956          /* Check the validity of the conference */
03957          cnf = find_conf(chan, confno, 1, dynamic, the_pin, 
03958             sizeof(the_pin), 1, &confflags);
03959          if (!cnf) {
03960             int too_early = 0;
03961 
03962             cnf = find_conf_realtime(chan, confno, 1, dynamic, 
03963                the_pin, sizeof(the_pin), 1, &confflags, &too_early, optargs);
03964             if (rt_schedule && too_early)
03965                allowretry = 0;
03966          }
03967 
03968          if (!cnf) {
03969             if (allowretry) {
03970                confno[0] = '\0';
03971                res = ast_streamfile(chan, "conf-invalid", chan->language);
03972                if (!res)
03973                   ast_waitstream(chan, "");
03974                res = -1;
03975             }
03976          } else {
03977             if (((!ast_strlen_zero(cnf->pin) &&
03978                 !ast_test_flag(&confflags, CONFFLAG_ADMIN)) ||
03979                 !ast_strlen_zero(cnf->pinadmin)) &&
03980                 (!(cnf->users == 0 && cnf->isdynamic))) {
03981                char pin[MAX_PIN] = "";
03982                int j;
03983 
03984                /* Allow the pin to be retried up to 3 times */
03985                for (j = 0; j < 3; j++) {
03986                   if (*the_pin && (always_prompt == 0)) {
03987                      ast_copy_string(pin, the_pin, sizeof(pin));
03988                      res = 0;
03989                   } else {
03990                      /* Prompt user for pin if pin is required */
03991                      res = ast_app_getdata(chan, "conf-getpin", pin + strlen(pin), sizeof(pin) - 1 - strlen(pin), 0);
03992                   }
03993                   if (res >= 0) {
03994                      if (!strcasecmp(pin, cnf->pin) ||
03995                          (!ast_strlen_zero(cnf->pinadmin) &&
03996                           !strcasecmp(pin, cnf->pinadmin))) {
03997                         /* Pin correct */
03998                         allowretry = 0;
03999                         if (!ast_strlen_zero(cnf->pinadmin) && !strcasecmp(pin, cnf->pinadmin)) {
04000                            if (!ast_strlen_zero(cnf->adminopts)) {
04001                               char *opts = ast_strdupa(cnf->adminopts);
04002                               ast_app_parse_options(meetme_opts, &confflags, optargs, opts);
04003                            }
04004                         } else {
04005                            if (!ast_strlen_zero(cnf->useropts)) {
04006                               char *opts = ast_strdupa(cnf->useropts);
04007                               ast_app_parse_options(meetme_opts, &confflags, optargs, opts);
04008                            }
04009                         }
04010                         /* Run the conference */
04011                         ast_verb(4, "Starting recording of MeetMe Conference %s into file %s.%s.\n", cnf->confno, cnf->recordingfilename, cnf->recordingformat);
04012                         res = conf_run(chan, cnf, confflags.flags, optargs);
04013                         break;
04014                      } else {
04015                         /* Pin invalid */
04016                         if (!ast_streamfile(chan, "conf-invalidpin", chan->language)) {
04017                            res = ast_waitstream(chan, AST_DIGIT_ANY);
04018                            ast_stopstream(chan);
04019                         } else {
04020                            ast_log(LOG_WARNING, "Couldn't play invalid pin msg!\n");
04021                            break;
04022                         }
04023                         if (res < 0)
04024                            break;
04025                         pin[0] = res;
04026                         pin[1] = '\0';
04027                         res = -1;
04028                         if (allowretry)
04029                            confno[0] = '\0';
04030                      }
04031                   } else {
04032                      /* failed when getting the pin */
04033                      res = -1;
04034                      allowretry = 0;
04035                      /* see if we need to get rid of the conference */
04036                      break;
04037                   }
04038 
04039                   /* Don't retry pin with a static pin */
04040                   if (*the_pin && (always_prompt == 0)) {
04041                      break;
04042                   }
04043                }
04044             } else {
04045                /* No pin required */
04046                allowretry = 0;
04047 
04048                /* For RealTime conferences without a pin 
04049                 * should still support loading options
04050                 */
04051                if (!ast_strlen_zero(cnf->useropts)) {
04052                   char *opts = ast_strdupa(cnf->useropts);
04053                   ast_app_parse_options(meetme_opts, &confflags, optargs, opts);
04054                }
04055 
04056                /* Run the conference */
04057                res = conf_run(chan, cnf, confflags.flags, optargs);
04058             }
04059             dispose_conf(cnf);
04060             cnf = NULL;
04061          }
04062       }
04063    } while (allowretry);
04064 
04065    if (cnf)
04066       dispose_conf(cnf);
04067    
04068    return res;
04069 }
04070 
04071 static struct ast_conf_user *find_user(struct ast_conference *conf, char *callerident) 
04072 {
04073    struct ast_conf_user *user = NULL;
04074    int cid;
04075    
04076    sscanf(callerident, "%30i", &cid);
04077    if (conf && callerident) {
04078       user = ao2_find(conf->usercontainer, &cid, 0);
04079       /* reference decremented later in admin_exec */
04080       return user;
04081    }
04082    return NULL;
04083 }
04084 
04085 static int user_set_kickme_cb(void *obj, void *unused, int flags)
04086 {
04087    struct ast_conf_user *user = obj;
04088    user->adminflags |= ADMINFLAG_KICKME;
04089    return 0;
04090 }
04091 
04092 static int user_set_muted_cb(void *obj, void *unused, int flags)
04093 {
04094    struct ast_conf_user *user = obj;
04095    if (!(user->userflags & CONFFLAG_ADMIN)) {
04096       user->adminflags |= ADMINFLAG_MUTED;
04097    }
04098    return 0;
04099 }
04100 
04101 static int user_set_unmuted_cb(void *obj, void *unused, int flags)
04102 {
04103    struct ast_conf_user *user = obj;
04104    user->adminflags &= ~(ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED);
04105    return 0;
04106 }
04107 
04108 static int user_listen_volup_cb(void *obj, void *unused, int flags)
04109 {
04110    struct ast_conf_user *user = obj;
04111    tweak_listen_volume(user, VOL_UP);
04112    return 0;
04113 }
04114 
04115 static int user_listen_voldown_cb(void *obj, void *unused, int flags)
04116 {
04117    struct ast_conf_user *user = obj;
04118    tweak_listen_volume(user, VOL_DOWN);
04119    return 0;
04120 }
04121 
04122 static int user_talk_volup_cb(void *obj, void *unused, int flags)
04123 {
04124    struct ast_conf_user *user = obj;
04125    tweak_talk_volume(user, VOL_UP);
04126    return 0;
04127 }
04128 
04129 static int user_talk_voldown_cb(void *obj, void *unused, int flags)
04130 {
04131    struct ast_conf_user *user = obj;
04132    tweak_talk_volume(user, VOL_DOWN);
04133    return 0;
04134 }
04135 
04136 static int user_reset_vol_cb(void *obj, void *unused, int flags)
04137 {
04138    struct ast_conf_user *user = obj;
04139    reset_volumes(user);
04140    return 0;
04141 }
04142 
04143 static int user_chan_cb(void *obj, void *args, int flags)
04144 {
04145    struct ast_conf_user *user = obj;
04146    const char *channel = args;
04147 
04148    if (!strcmp(user->chan->name, channel)) {
04149       return (CMP_MATCH | CMP_STOP);
04150    }
04151 
04152    return 0;
04153 }
04154 
04155 /*! \brief The MeetMeadmin application */
04156 /* MeetMeAdmin(confno, command, caller) */
04157 static int admin_exec(struct ast_channel *chan, void *data) {
04158    char *params;
04159    struct ast_conference *cnf;
04160    struct ast_conf_user *user = NULL;
04161    AST_DECLARE_APP_ARGS(args,
04162       AST_APP_ARG(confno);
04163       AST_APP_ARG(command);
04164       AST_APP_ARG(user);
04165    );
04166    int res = 0;
04167 
04168    if (ast_strlen_zero(data)) {
04169       ast_log(LOG_WARNING, "MeetMeAdmin requires an argument!\n");
04170       pbx_builtin_setvar_helper(chan, "MEETMEADMINSTATUS", "NOPARSE");
04171       return -1;
04172    }
04173 
04174    params = ast_strdupa(data);
04175    AST_STANDARD_APP_ARGS(args, params);
04176 
04177    if (!args.command) {
04178       ast_log(LOG_WARNING, "MeetmeAdmin requires a command!\n");
04179       pbx_builtin_setvar_helper(chan, "MEETMEADMINSTATUS", "NOPARSE");
04180       return -1;
04181    }
04182 
04183    AST_LIST_LOCK(&confs);
04184    AST_LIST_TRAVERSE(&confs, cnf, list) {
04185       if (!strcmp(cnf->confno, args.confno))
04186          break;
04187    }
04188 
04189    if (!cnf) {
04190       ast_log(LOG_WARNING, "Conference number '%s' not found!\n", args.confno);
04191       AST_LIST_UNLOCK(&confs);
04192       pbx_builtin_setvar_helper(chan, "MEETMEADMINSTATUS", "NOTFOUND");
04193       return 0;
04194    }
04195 
04196    ast_atomic_fetchadd_int(&cnf->refcount, 1);
04197 
04198    if (args.user) {
04199       user = find_user(cnf, args.user);
04200       if (!user) {
04201          ast_log(LOG_NOTICE, "Specified User not found!\n");
04202          res = -2;
04203          goto usernotfound;
04204       }
04205    }
04206 
04207    switch (*args.command) {
04208    case 76: /* L: Lock */ 
04209       cnf->locked = 1;
04210       break;
04211    case 108: /* l: Unlock */ 
04212       cnf->locked = 0;
04213       break;
04214    case 75: /* K: kick all users */
04215       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_set_kickme_cb, NULL);
04216       break;
04217    case 101: /* e: Eject last user*/
04218    {
04219       int max_no = 0;
04220       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_max_cmp, &max_no);
04221       user = ao2_find(cnf->usercontainer, &max_no, 0);
04222       if (!(user->userflags & CONFFLAG_ADMIN))
04223          user->adminflags |= ADMINFLAG_KICKME;
04224       else {
04225          res = -1;
04226          ast_log(LOG_NOTICE, "Not kicking last user, is an Admin!\n");
04227       }
04228       ao2_ref(user, -1);
04229       break;
04230    }
04231    case 77: /* M: Mute */ 
04232       if (user) {
04233          user->adminflags |= ADMINFLAG_MUTED;
04234       } else {
04235          res = -2;
04236          ast_log(LOG_NOTICE, "Specified User not found!\n");
04237       }
04238       break;
04239    case 78: /* N: Mute all (non-admin) users */
04240       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_set_muted_cb, NULL);
04241       break;               
04242    case 109: /* m: Unmute */ 
04243       user->adminflags &= ~(ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED | ADMINFLAG_T_REQUEST);
04244       break;
04245    case 110: /* n: Unmute all users */
04246       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_set_unmuted_cb, NULL);
04247       break;
04248    case 107: /* k: Kick user */ 
04249       user->adminflags |= ADMINFLAG_KICKME;
04250       break;
04251    case 118: /* v: Lower all users listen volume */
04252       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_listen_voldown_cb, NULL);
04253       break;
04254    case 86: /* V: Raise all users listen volume */
04255       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_listen_volup_cb, NULL);
04256       break;
04257    case 115: /* s: Lower all users speaking volume */
04258       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_talk_voldown_cb, NULL);
04259       break;
04260    case 83: /* S: Raise all users speaking volume */
04261       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_talk_volup_cb, NULL);
04262       break;
04263    case 82: /* R: Reset all volume levels */
04264       ao2_callback(cnf->usercontainer, OBJ_NODATA, user_reset_vol_cb, NULL);
04265       break;
04266    case 114: /* r: Reset user's volume level */
04267       reset_volumes(user);
04268       break;
04269    case 85: /* U: Raise user's listen volume */
04270       tweak_listen_volume(user, VOL_UP);
04271       break;
04272    case 117: /* u: Lower user's listen volume */
04273       tweak_listen_volume(user, VOL_DOWN);
04274       break;
04275    case 84: /* T: Raise user's talk volume */
04276       tweak_talk_volume(user, VOL_UP);
04277       break;
04278    case 116: /* t: Lower user's talk volume */
04279       tweak_talk_volume(user, VOL_DOWN);
04280       break;
04281    case 'E': /* E: Extend conference */
04282       if (rt_extend_conf(args.confno)) {
04283          res = -1;
04284       }
04285       break;
04286    }
04287 
04288    if (args.user) {
04289       /* decrement reference from find_user */
04290       ao2_ref(user, -1);
04291    }
04292 usernotfound:
04293    AST_LIST_UNLOCK(&confs);
04294 
04295    dispose_conf(cnf);
04296    pbx_builtin_setvar_helper(chan, "MEETMEADMINSTATUS", res == -2 ? "NOTFOUND" : res ? "FAILED" : "OK");
04297 
04298    return 0;
04299 }
04300 
04301 /*--- channel_admin_exec: The MeetMeChannelAdmin application */
04302 /* MeetMeChannelAdmin(channel, command) */
04303 static int channel_admin_exec(struct ast_channel *chan, void *data) {
04304    char *params;
04305    struct ast_conference *conf = NULL;
04306    struct ast_conf_user *user = NULL;
04307    AST_DECLARE_APP_ARGS(args,
04308       AST_APP_ARG(channel);
04309       AST_APP_ARG(command);
04310    );
04311 
04312    if (ast_strlen_zero(data)) {
04313       ast_log(LOG_WARNING, "MeetMeChannelAdmin requires two arguments!\n");
04314       return -1;
04315    }
04316    
04317    params = ast_strdupa(data);
04318    AST_STANDARD_APP_ARGS(args, params);
04319 
04320    if (!args.channel) {
04321       ast_log(LOG_WARNING, "MeetMeChannelAdmin requires a channel name!\n");
04322       return -1;
04323    }
04324 
04325    if (!args.command) {
04326       ast_log(LOG_WARNING, "MeetMeChannelAdmin requires a command!\n");
04327       return -1;
04328    }
04329 
04330    AST_LIST_LOCK(&confs);
04331    AST_LIST_TRAVERSE(&confs, conf, list) {
04332       if ((user = ao2_callback(conf->usercontainer, 0, user_chan_cb, args.channel))) {
04333          break;
04334       }
04335    }
04336    
04337    if (!user) {
04338       ast_log(LOG_NOTICE, "Specified user (%s) not found\n", args.channel);
04339       AST_LIST_UNLOCK(&confs);
04340       return 0;
04341    }
04342    
04343    /* perform the specified action */
04344    switch (*args.command) {
04345       case 77: /* M: Mute */ 
04346          user->adminflags |= ADMINFLAG_MUTED;
04347          break;
04348       case 109: /* m: Unmute */ 
04349          user->adminflags &= ~ADMINFLAG_MUTED;
04350          break;
04351       case 107: /* k: Kick user */ 
04352          user->adminflags |= ADMINFLAG_KICKME;
04353          break;
04354       default: /* unknown command */
04355          ast_log(LOG_WARNING, "Unknown MeetMeChannelAdmin command '%s'\n", args.command);
04356          break;
04357    }
04358    ao2_ref(user, -1);
04359    AST_LIST_UNLOCK(&confs);
04360    
04361    return 0;
04362 }
04363 
04364 static int meetmemute(struct mansession *s, const struct message *m, int mute)
04365 {
04366    struct ast_conference *conf;
04367    struct ast_conf_user *user;
04368    const char *confid = astman_get_header(m, "Meetme");
04369    char *userid = ast_strdupa(astman_get_header(m, "Usernum"));
04370    int userno;
04371 
04372    if (ast_strlen_zero(confid)) {
04373       astman_send_error(s, m, "Meetme conference not specified");
04374       return 0;
04375    }
04376 
04377    if (ast_strlen_zero(userid)) {
04378       astman_send_error(s, m, "Meetme user number not specified");
04379       return 0;
04380    }
04381 
04382    userno = strtoul(userid, &userid, 10);
04383 
04384    if (*userid) {
04385       astman_send_error(s, m, "Invalid user number");
04386       return 0;
04387    }
04388 
04389    /* Look in the conference list */
04390    AST_LIST_LOCK(&confs);
04391    AST_LIST_TRAVERSE(&confs, conf, list) {
04392       if (!strcmp(confid, conf->confno))
04393          break;
04394    }
04395 
04396    if (!conf) {
04397       AST_LIST_UNLOCK(&confs);
04398       astman_send_error(s, m, "Meetme conference does not exist");
04399       return 0;
04400    }
04401 
04402    user = ao2_find(conf->usercontainer, &userno, 0);
04403 
04404    if (!user) {
04405       AST_LIST_UNLOCK(&confs);
04406       astman_send_error(s, m, "User number not found");
04407       return 0;
04408    }
04409 
04410    if (mute)
04411       user->adminflags |= ADMINFLAG_MUTED;   /* request user muting */
04412    else
04413       user->adminflags &= ~(ADMINFLAG_MUTED | ADMINFLAG_SELFMUTED | ADMINFLAG_T_REQUEST); /* request user unmuting */
04414 
04415    AST_LIST_UNLOCK(&confs);
04416 
04417    ast_log(LOG_NOTICE, "Requested to %smute conf %s user %d userchan %s uniqueid %s\n", mute ? "" : "un", conf->confno, user->user_no, user->chan->name, user->chan->uniqueid);
04418 
04419    ao2_ref(user, -1);
04420    astman_send_ack(s, m, mute ? "User muted" : "User unmuted");
04421    return 0;
04422 }
04423 
04424 static int action_meetmemute(struct mansession *s, const struct message *m)
04425 {
04426    return meetmemute(s, m, 1);
04427 }
04428 
04429 static int action_meetmeunmute(struct mansession *s, const struct message *m)
04430 {
04431    return meetmemute(s, m, 0);
04432 }
04433 
04434 static char mandescr_meetmelist[] =
04435 "Description: Lists all users in a particular MeetMe conference.\n"
04436 "MeetmeList will follow as separate events, followed by a final event called\n"
04437 "MeetmeListComplete.\n"
04438 "Variables:\n"
04439 "    *ActionId: <id>\n"
04440 "    *Conference: <confno>\n";
04441 
04442 static int action_meetmelist(struct mansession *s, const struct message *m)
04443 {
04444    const char *actionid = astman_get_header(m, "ActionID");
04445    const char *conference = astman_get_header(m, "Conference");
04446    char idText[80] = "";
04447    struct ast_conference *cnf;
04448    struct ast_conf_user *user;
04449    struct ao2_iterator user_iter;
04450    int total = 0;
04451 
04452    if (!ast_strlen_zero(actionid))
04453       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", actionid);
04454 
04455    if (AST_LIST_EMPTY(&confs)) {
04456       astman_send_error(s, m, "No active conferences.");
04457       return 0;
04458    }
04459 
04460    astman_send_listack(s, m, "Meetme user list will follow", "start");
04461 
04462    /* Find the right conference */
04463    AST_LIST_LOCK(&confs);
04464    AST_LIST_TRAVERSE(&confs, cnf, list) {
04465       user_iter = ao2_iterator_init(cnf->usercontainer, 0);
04466       /* If we ask for one particular, and this isn't it, skip it */
04467       if (!ast_strlen_zero(conference) && strcmp(cnf->confno, conference))
04468          continue;
04469 
04470       /* Show all the users */
04471       while ((user = ao2_iterator_next(&user_iter))) {
04472          total++;
04473          astman_append(s,
04474          "Event: MeetmeList\r\n"
04475          "%s"
04476          "Conference: %s\r\n"
04477          "UserNumber: %d\r\n"
04478          "CallerIDNum: %s\r\n"
04479          "CallerIDName: %s\r\n"
04480          "Channel: %s\r\n"
04481          "Admin: %s\r\n"
04482          "Role: %s\r\n"
04483          "MarkedUser: %s\r\n"
04484          "Muted: %s\r\n"
04485          "Talking: %s\r\n"
04486          "\r\n",
04487          idText,
04488          cnf->confno,
04489          user->user_no,
04490          S_OR(user->chan->cid.cid_num, "<unknown>"),
04491          S_OR(user->chan->cid.cid_name, "<no name>"),
04492          user->chan->name,
04493          user->userflags & CONFFLAG_ADMIN ? "Yes" : "No",
04494          user->userflags & CONFFLAG_MONITOR ? "Listen only" : user->userflags & CONFFLAG_TALKER ? "Talk only" : "Talk and listen",
04495          user->userflags & CONFFLAG_MARKEDUSER ? "Yes" : "No",
04496          user->adminflags & ADMINFLAG_MUTED ? "By admin" : user->adminflags & ADMINFLAG_SELFMUTED ? "By self" : "No",
04497          user->talking > 0 ? "Yes" : user->talking == 0 ? "No" : "Not monitored");
04498          ao2_ref(user, -1); 
04499       }
04500       ao2_iterator_destroy(&user_iter);
04501    }
04502    AST_LIST_UNLOCK(&confs);
04503    /* Send final confirmation */
04504    astman_append(s,
04505    "Event: MeetmeListComplete\r\n"
04506    "EventList: Complete\r\n"
04507    "ListItems: %d\r\n"
04508    "%s"
04509    "\r\n", total, idText);
04510    return 0;
04511 }
04512 
04513 static void *recordthread(void *args)
04514 {
04515    struct ast_conference *cnf = args;
04516    struct ast_frame *f = NULL;
04517    int flags;
04518    struct ast_filestream *s = NULL;
04519    int res = 0;
04520    int x;
04521    const char *oldrecordingfilename = NULL;
04522 
04523    if (!cnf || !cnf->lchan) {
04524       pthread_exit(0);
04525    }
04526 
04527    ast_stopstream(cnf->lchan);
04528    flags = O_CREAT | O_TRUNC | O_WRONLY;
04529 
04530 
04531    cnf->recording = MEETME_RECORD_ACTIVE;
04532    while (ast_waitfor(cnf->lchan, -1) > -1) {
04533       if (cnf->recording == MEETME_RECORD_TERMINATE) {
04534          AST_LIST_LOCK(&confs);
04535          AST_LIST_UNLOCK(&confs);
04536          break;
04537       }
04538       if (!s && cnf->recordingfilename && (cnf->recordingfilename != oldrecordingfilename)) {
04539          s = ast_writefile(cnf->recordingfilename, cnf->recordingformat, NULL, flags, 0, AST_FILE_MODE);
04540          oldrecordingfilename = cnf->recordingfilename;
04541       }
04542       
04543       f = ast_read(cnf->lchan);
04544       if (!f) {
04545          res = -1;
04546          break;
04547       }
04548       if (f->frametype == AST_FRAME_VOICE) {
04549          ast_mutex_lock(&cnf->listenlock);
04550          for (x = 0; x < AST_FRAME_BITS; x++) {
04551             /* Free any translations that have occured */
04552             if (cnf->transframe[x]) {
04553                ast_frfree(cnf->transframe[x]);
04554                cnf->transframe[x] = NULL;
04555             }
04556          }
04557          if (cnf->origframe)
04558             ast_frfree(cnf->origframe);
04559          cnf->origframe = ast_frdup(f);
04560          ast_mutex_unlock(&cnf->listenlock);
04561          if (s)
04562             res = ast_writestream(s, f);
04563          if (res) {
04564             ast_frfree(f);
04565             break;
04566          }
04567       }
04568       ast_frfree(f);
04569    }
04570    cnf->recording = MEETME_RECORD_OFF;
04571    if (s)
04572       ast_closestream(s);
04573    
04574    pthread_exit(0);
04575 }
04576 
04577 /*! \brief Callback for devicestate providers */
04578 static enum ast_device_state meetmestate(const char *data)
04579 {
04580    struct ast_conference *conf;
04581 
04582    /* Find conference */
04583    AST_LIST_LOCK(&confs);
04584    AST_LIST_TRAVERSE(&confs, conf, list) {
04585       if (!strcmp(data, conf->confno))
04586          break;
04587    }
04588    AST_LIST_UNLOCK(&confs);
04589    if (!conf)
04590       return AST_DEVICE_INVALID;
04591 
04592 
04593    /* SKREP to fill */
04594    if (!conf->users)
04595       return AST_DEVICE_NOT_INUSE;
04596 
04597    return AST_DEVICE_INUSE;
04598 }
04599 
04600 static void load_config_meetme(void)
04601 {
04602    struct ast_config *cfg;
04603    struct ast_flags config_flags = { 0 };
04604    const char *val;
04605 
04606    if (!(cfg = ast_config_load(CONFIG_FILE_NAME, config_flags))) {
04607       return;
04608    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
04609       ast_log(LOG_ERROR, "Config file " CONFIG_FILE_NAME " is in an invalid format.  Aborting.\n");
04610       return;
04611    }
04612 
04613    audio_buffers = DEFAULT_AUDIO_BUFFERS;
04614 
04615    /*  Scheduling support is off by default */
04616    rt_schedule = 0;
04617    fuzzystart = 0;
04618    earlyalert = 0;
04619    endalert = 0;
04620    extendby = 0;
04621 
04622    /*  Logging of participants defaults to ON for compatibility reasons */
04623    rt_log_members = 1;  
04624 
04625    if ((val = ast_variable_retrieve(cfg, "general", "audiobuffers"))) {
04626       if ((sscanf(val, "%30d", &audio_buffers) != 1)) {
04627          ast_log(LOG_WARNING, "audiobuffers setting must be a number, not '%s'\n", val);
04628          audio_buffers = DEFAULT_AUDIO_BUFFERS;
04629       } else if ((audio_buffers < DAHDI_DEFAULT_NUM_BUFS) || (audio_buffers > DAHDI_MAX_NUM_BUFS)) {
04630          ast_log(LOG_WARNING, "audiobuffers setting must be between %d and %d\n",
04631             DAHDI_DEFAULT_NUM_BUFS, DAHDI_MAX_NUM_BUFS);
04632          audio_buffers = DEFAULT_AUDIO_BUFFERS;
04633       }
04634       if (audio_buffers != DEFAULT_AUDIO_BUFFERS)
04635          ast_log(LOG_NOTICE, "Audio buffers per channel set to %d\n", audio_buffers);
04636    }
04637 
04638    if ((val = ast_variable_retrieve(cfg, "general", "schedule")))
04639       rt_schedule = ast_true(val);
04640    if ((val = ast_variable_retrieve(cfg, "general", "logmembercount")))
04641       rt_log_members = ast_true(val);
04642    if ((val = ast_variable_retrieve(cfg, "general", "fuzzystart"))) {
04643       if ((sscanf(val, "%30d", &fuzzystart) != 1)) {
04644          ast_log(LOG_WARNING, "fuzzystart must be a number, not '%s'\n", val);
04645          fuzzystart = 0;
04646       } 
04647    }
04648    if ((val = ast_variable_retrieve(cfg, "general", "earlyalert"))) {
04649       if ((sscanf(val, "%30d", &earlyalert) != 1)) {
04650          ast_log(LOG_WARNING, "earlyalert must be a number, not '%s'\n", val);
04651          earlyalert = 0;
04652       } 
04653    }
04654    if ((val = ast_variable_retrieve(cfg, "general", "endalert"))) {
04655       if ((sscanf(val, "%30d", &endalert) != 1)) {
04656          ast_log(LOG_WARNING, "endalert must be a number, not '%s'\n", val);
04657          endalert = 0;
04658       } 
04659    }
04660    if ((val = ast_variable_retrieve(cfg, "general", "extendby"))) {
04661       if ((sscanf(val, "%30d", &extendby) != 1)) {
04662          ast_log(LOG_WARNING, "extendby must be a number, not '%s'\n", val);
04663          extendby = 0;
04664       } 
04665    }
04666 
04667    ast_config_destroy(cfg);
04668 }
04669 
04670 /*! \brief Find an SLA trunk by name
04671  * \note This must be called with the sla_trunks container locked
04672  */
04673 static struct sla_trunk *sla_find_trunk(const char *name)
04674 {
04675    struct sla_trunk *trunk = NULL;
04676 
04677    AST_RWLIST_TRAVERSE(&sla_trunks, trunk, entry) {
04678       if (!strcasecmp(trunk->name, name))
04679          break;
04680    }
04681 
04682    return trunk;
04683 }
04684 
04685 /*! \brief Find an SLA station by name
04686  * \note This must be called with the sla_stations container locked
04687  */
04688 static struct sla_station *sla_find_station(const char *name)
04689 {
04690    struct sla_station *station = NULL;
04691 
04692    AST_RWLIST_TRAVERSE(&sla_stations, station, entry) {
04693       if (!strcasecmp(station->name, name))
04694          break;
04695    }
04696 
04697    return station;
04698 }
04699 
04700 static int sla_check_station_hold_access(const struct sla_trunk *trunk,
04701    const struct sla_station *station)
04702 {
04703    struct sla_station_ref *station_ref;
04704    struct sla_trunk_ref *trunk_ref;
04705 
04706    /* For each station that has this call on hold, check for private hold. */
04707    AST_LIST_TRAVERSE(&trunk->stations, station_ref, entry) {
04708       AST_LIST_TRAVERSE(&station_ref->station->trunks, trunk_ref, entry) {
04709          if (trunk_ref->trunk != trunk || station_ref->station == station)
04710             continue;
04711          if (trunk_ref->state == SLA_TRUNK_STATE_ONHOLD_BYME &&
04712             station_ref->station->hold_access == SLA_HOLD_PRIVATE)
04713             return 1;
04714          return 0;
04715       }
04716    }
04717 
04718    return 0;
04719 }
04720 
04721 /*! \brief Find a trunk reference on a station by name
04722  * \param station the station
04723  * \param name the trunk's name
04724  * \return a pointer to the station's trunk reference.  If the trunk
04725  *         is not found, it is not idle and barge is disabled, or if
04726  *         it is on hold and private hold is set, then NULL will be returned.
04727  */
04728 static struct sla_trunk_ref *sla_find_trunk_ref_byname(const struct sla_station *station,
04729    const char *name)
04730 {
04731    struct sla_trunk_ref *trunk_ref = NULL;
04732 
04733    AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
04734       if (strcasecmp(trunk_ref->trunk->name, name))
04735          continue;
04736 
04737       if ( (trunk_ref->trunk->barge_disabled 
04738          && trunk_ref->state == SLA_TRUNK_STATE_UP) ||
04739          (trunk_ref->trunk->hold_stations 
04740          && trunk_ref->trunk->hold_access == SLA_HOLD_PRIVATE
04741          && trunk_ref->state != SLA_TRUNK_STATE_ONHOLD_BYME) ||
04742          sla_check_station_hold_access(trunk_ref->trunk, station) ) 
04743       {
04744          trunk_ref = NULL;
04745       }
04746 
04747       break;
04748    }
04749 
04750    return trunk_ref;
04751 }
04752 
04753 static struct sla_station_ref *sla_create_station_ref(struct sla_station *station)
04754 {
04755    struct sla_station_ref *station_ref;
04756 
04757    if (!(station_ref = ast_calloc(1, sizeof(*station_ref))))
04758       return NULL;
04759 
04760    station_ref->station = station;
04761 
04762    return station_ref;
04763 }
04764 
04765 static struct sla_ringing_station *sla_create_ringing_station(struct sla_station *station)
04766 {
04767    struct sla_ringing_station *ringing_station;
04768 
04769    if (!(ringing_station = ast_calloc(1, sizeof(*ringing_station))))
04770       return NULL;
04771 
04772    ringing_station->station = station;
04773    ringing_station->ring_begin = ast_tvnow();
04774 
04775    return ringing_station;
04776 }
04777 
04778 static enum ast_device_state sla_state_to_devstate(enum sla_trunk_state state)
04779 {
04780    switch (state) {
04781    case SLA_TRUNK_STATE_IDLE:
04782       return AST_DEVICE_NOT_INUSE;
04783    case SLA_TRUNK_STATE_RINGING:
04784       return AST_DEVICE_RINGING;
04785    case SLA_TRUNK_STATE_UP:
04786       return AST_DEVICE_INUSE;
04787    case SLA_TRUNK_STATE_ONHOLD:
04788    case SLA_TRUNK_STATE_ONHOLD_BYME:
04789       return AST_DEVICE_ONHOLD;
04790    }
04791 
04792    return AST_DEVICE_UNKNOWN;
04793 }
04794 
04795 static void sla_change_trunk_state(const struct sla_trunk *trunk, enum sla_trunk_state state, 
04796    enum sla_which_trunk_refs inactive_only, const struct sla_trunk_ref *exclude)
04797 {
04798    struct sla_station *station;
04799    struct sla_trunk_ref *trunk_ref;
04800 
04801    AST_LIST_TRAVERSE(&sla_stations, station, entry) {
04802       AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
04803          if (trunk_ref->trunk != trunk || (inactive_only ? trunk_ref->chan : 0)
04804             || trunk_ref == exclude)
04805             continue;
04806          trunk_ref->state = state;
04807          ast_devstate_changed(sla_state_to_devstate(state), 
04808             "SLA:%s_%s", station->name, trunk->name);
04809          break;
04810       }
04811    }
04812 }
04813 
04814 struct run_station_args {
04815    struct sla_station *station;
04816    struct sla_trunk_ref *trunk_ref;
04817    ast_mutex_t *cond_lock;
04818    ast_cond_t *cond;
04819 };
04820 
04821 static void answer_trunk_chan(struct ast_channel *chan)
04822 {
04823    ast_answer(chan);
04824    ast_indicate(chan, -1);
04825 }
04826 
04827 static void *run_station(void *data)
04828 {
04829    struct sla_station *station;
04830    struct sla_trunk_ref *trunk_ref;
04831    struct ast_str *conf_name = ast_str_create(16);
04832    struct ast_flags conf_flags = { 0 };
04833    struct ast_conference *conf;
04834 
04835    {
04836       struct run_station_args *args = data;
04837       station = args->station;
04838       trunk_ref = args->trunk_ref;
04839       ast_mutex_lock(args->cond_lock);
04840       ast_cond_signal(args->cond);
04841       ast_mutex_unlock(args->cond_lock);
04842       /* args is no longer valid here. */
04843    }
04844 
04845    ast_atomic_fetchadd_int((int *) &trunk_ref->trunk->active_stations, 1);
04846    ast_str_set(&conf_name, 0, "SLA_%s", trunk_ref->trunk->name);
04847    ast_set_flag(&conf_flags, 
04848       CONFFLAG_QUIET | CONFFLAG_MARKEDEXIT | CONFFLAG_PASS_DTMF | CONFFLAG_SLA_STATION);
04849    answer_trunk_chan(trunk_ref->chan);
04850    conf = build_conf(ast_str_buffer(conf_name), "", "", 0, 0, 1, trunk_ref->chan);
04851    if (conf) {
04852       conf_run(trunk_ref->chan, conf, conf_flags.flags, NULL);
04853       dispose_conf(conf);
04854       conf = NULL;
04855    }
04856    trunk_ref->chan = NULL;
04857    if (ast_atomic_dec_and_test((int *) &trunk_ref->trunk->active_stations) &&
04858       trunk_ref->state != SLA_TRUNK_STATE_ONHOLD_BYME) {
04859       ast_str_append(&conf_name, 0, ",K");
04860       admin_exec(NULL, ast_str_buffer(conf_name));
04861       trunk_ref->trunk->hold_stations = 0;
04862       sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
04863    }
04864 
04865    ast_dial_join(station->dial);
04866    ast_dial_destroy(station->dial);
04867    station->dial = NULL;
04868    ast_free(conf_name);
04869 
04870    return NULL;
04871 }
04872 
04873 static void sla_stop_ringing_trunk(struct sla_ringing_trunk *ringing_trunk)
04874 {
04875    char buf[80];
04876    struct sla_station_ref *station_ref;
04877 
04878    snprintf(buf, sizeof(buf), "SLA_%s,K", ringing_trunk->trunk->name);
04879    admin_exec(NULL, buf);
04880    sla_change_trunk_state(ringing_trunk->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
04881 
04882    while ((station_ref = AST_LIST_REMOVE_HEAD(&ringing_trunk->timed_out_stations, entry)))
04883       ast_free(station_ref);
04884 
04885    ast_free(ringing_trunk);
04886 }
04887 
04888 static void sla_stop_ringing_station(struct sla_ringing_station *ringing_station,
04889    enum sla_station_hangup hangup)
04890 {
04891    struct sla_ringing_trunk *ringing_trunk;
04892    struct sla_trunk_ref *trunk_ref;
04893    struct sla_station_ref *station_ref;
04894 
04895    ast_dial_join(ringing_station->station->dial);
04896    ast_dial_destroy(ringing_station->station->dial);
04897    ringing_station->station->dial = NULL;
04898 
04899    if (hangup == SLA_STATION_HANGUP_NORMAL)
04900       goto done;
04901 
04902    /* If the station is being hung up because of a timeout, then add it to the
04903     * list of timed out stations on each of the ringing trunks.  This is so
04904     * that when doing further processing to figure out which stations should be
04905     * ringing, which trunk to answer, determining timeouts, etc., we know which
04906     * ringing trunks we should ignore. */
04907    AST_LIST_TRAVERSE(&sla.ringing_trunks, ringing_trunk, entry) {
04908       AST_LIST_TRAVERSE(&ringing_station->station->trunks, trunk_ref, entry) {
04909          if (ringing_trunk->trunk == trunk_ref->trunk)
04910             break;
04911       }
04912       if (!trunk_ref)
04913          continue;
04914       if (!(station_ref = sla_create_station_ref(ringing_station->station)))
04915          continue;
04916       AST_LIST_INSERT_TAIL(&ringing_trunk->timed_out_stations, station_ref, entry);
04917    }
04918 
04919 done:
04920    ast_free(ringing_station);
04921 }
04922 
04923 static void sla_dial_state_callback(struct ast_dial *dial)
04924 {
04925    sla_queue_event(SLA_EVENT_DIAL_STATE);
04926 }
04927 
04928 /*! \brief Check to see if dialing this station already timed out for this ringing trunk
04929  * \note Assumes sla.lock is locked
04930  */
04931 static int sla_check_timed_out_station(const struct sla_ringing_trunk *ringing_trunk,
04932    const struct sla_station *station)
04933 {
04934    struct sla_station_ref *timed_out_station;
04935 
04936    AST_LIST_TRAVERSE(&ringing_trunk->timed_out_stations, timed_out_station, entry) {
04937       if (station == timed_out_station->station)
04938          return 1;
04939    }
04940 
04941    return 0;
04942 }
04943 
04944 /*! \brief Choose the highest priority ringing trunk for a station
04945  * \param station the station
04946  * \param remove remove the ringing trunk once selected
04947  * \param trunk_ref a place to store the pointer to this stations reference to
04948  *        the selected trunk
04949  * \return a pointer to the selected ringing trunk, or NULL if none found
04950  * \note Assumes that sla.lock is locked
04951  */
04952 static struct sla_ringing_trunk *sla_choose_ringing_trunk(struct sla_station *station, 
04953    struct sla_trunk_ref **trunk_ref, int rm)
04954 {
04955    struct sla_trunk_ref *s_trunk_ref;
04956    struct sla_ringing_trunk *ringing_trunk = NULL;
04957 
04958    AST_LIST_TRAVERSE(&station->trunks, s_trunk_ref, entry) {
04959       AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_trunks, ringing_trunk, entry) {
04960          /* Make sure this is the trunk we're looking for */
04961          if (s_trunk_ref->trunk != ringing_trunk->trunk)
04962             continue;
04963 
04964          /* This trunk on the station is ringing.  But, make sure this station
04965           * didn't already time out while this trunk was ringing. */
04966          if (sla_check_timed_out_station(ringing_trunk, station))
04967             continue;
04968 
04969          if (rm)
04970             AST_LIST_REMOVE_CURRENT(entry);
04971 
04972          if (trunk_ref)
04973             *trunk_ref = s_trunk_ref;
04974 
04975          break;
04976       }
04977       AST_LIST_TRAVERSE_SAFE_END;
04978    
04979       if (ringing_trunk)
04980          break;
04981    }
04982 
04983    return ringing_trunk;
04984 }
04985 
04986 static void sla_handle_dial_state_event(void)
04987 {
04988    struct sla_ringing_station *ringing_station;
04989 
04990    AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_stations, ringing_station, entry) {
04991       struct sla_trunk_ref *s_trunk_ref = NULL;
04992       struct sla_ringing_trunk *ringing_trunk = NULL;
04993       struct run_station_args args;
04994       enum ast_dial_result dial_res;
04995       pthread_t dont_care;
04996       ast_mutex_t cond_lock;
04997       ast_cond_t cond;
04998 
04999       switch ((dial_res = ast_dial_state(ringing_station->station->dial))) {
05000       case AST_DIAL_RESULT_HANGUP:
05001       case AST_DIAL_RESULT_INVALID:
05002       case AST_DIAL_RESULT_FAILED:
05003       case AST_DIAL_RESULT_TIMEOUT:
05004       case AST_DIAL_RESULT_UNANSWERED:
05005          AST_LIST_REMOVE_CURRENT(entry);
05006          sla_stop_ringing_station(ringing_station, SLA_STATION_HANGUP_NORMAL);
05007          break;
05008       case AST_DIAL_RESULT_ANSWERED:
05009          AST_LIST_REMOVE_CURRENT(entry);
05010          /* Find the appropriate trunk to answer. */
05011          ast_mutex_lock(&sla.lock);
05012          ringing_trunk = sla_choose_ringing_trunk(ringing_station->station, &s_trunk_ref, 1);
05013          ast_mutex_unlock(&sla.lock);
05014          if (!ringing_trunk) {
05015             ast_debug(1, "Found no ringing trunk for station '%s' to answer!\n", ringing_station->station->name);
05016             break;
05017          }
05018          /* Track the channel that answered this trunk */
05019          s_trunk_ref->chan = ast_dial_answered(ringing_station->station->dial);
05020          /* Actually answer the trunk */
05021          answer_trunk_chan(ringing_trunk->trunk->chan);
05022          sla_change_trunk_state(ringing_trunk->trunk, SLA_TRUNK_STATE_UP, ALL_TRUNK_REFS, NULL);
05023          /* Now, start a thread that will connect this station to the trunk.  The rest of
05024           * the code here sets up the thread and ensures that it is able to save the arguments
05025           * before they are no longer valid since they are allocated on the stack. */
05026          args.trunk_ref = s_trunk_ref;
05027          args.station = ringing_station->station;
05028          args.cond = &cond;
05029          args.cond_lock = &cond_lock;
05030          ast_free(ringing_trunk);
05031          ast_free(ringing_station);
05032          ast_mutex_init(&cond_lock);
05033          ast_cond_init(&cond, NULL);
05034          ast_mutex_lock(&cond_lock);
05035          ast_pthread_create_detached_background(&dont_care, NULL, run_station, &args);
05036          ast_cond_wait(&cond, &cond_lock);
05037          ast_mutex_unlock(&cond_lock);
05038          ast_mutex_destroy(&cond_lock);
05039          ast_cond_destroy(&cond);
05040          break;
05041       case AST_DIAL_RESULT_TRYING:
05042       case AST_DIAL_RESULT_RINGING:
05043       case AST_DIAL_RESULT_PROGRESS:
05044       case AST_DIAL_RESULT_PROCEEDING:
05045          break;
05046       }
05047       if (dial_res == AST_DIAL_RESULT_ANSWERED) {
05048          /* Queue up reprocessing ringing trunks, and then ringing stations again */
05049          sla_queue_event(SLA_EVENT_RINGING_TRUNK);
05050          sla_queue_event(SLA_EVENT_DIAL_STATE);
05051          break;
05052       }
05053    }
05054    AST_LIST_TRAVERSE_SAFE_END;
05055 }
05056 
05057 /*! \brief Check to see if this station is already ringing 
05058  * \note Assumes sla.lock is locked 
05059  */
05060 static int sla_check_ringing_station(const struct sla_station *station)
05061 {
05062    struct sla_ringing_station *ringing_station;
05063 
05064    AST_LIST_TRAVERSE(&sla.ringing_stations, ringing_station, entry) {
05065       if (station == ringing_station->station)
05066          return 1;
05067    }
05068 
05069    return 0;
05070 }
05071 
05072 /*! \brief Check to see if this station has failed to be dialed in the past minute
05073  * \note assumes sla.lock is locked
05074  */
05075 static int sla_check_failed_station(const struct sla_station *station)
05076 {
05077    struct sla_failed_station *failed_station;
05078    int res = 0;
05079 
05080    AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.failed_stations, failed_station, entry) {
05081       if (station != failed_station->station)
05082          continue;
05083       if (ast_tvdiff_ms(ast_tvnow(), failed_station->last_try) > 1000) {
05084          AST_LIST_REMOVE_CURRENT(entry);
05085          ast_free(failed_station);
05086          break;
05087       }
05088       res = 1;
05089    }
05090    AST_LIST_TRAVERSE_SAFE_END
05091 
05092    return res;
05093 }
05094 
05095 /*! \brief Ring a station
05096  * \note Assumes sla.lock is locked
05097  */
05098 static int sla_ring_station(struct sla_ringing_trunk *ringing_trunk, struct sla_station *station)
05099 {
05100    char *tech, *tech_data;
05101    struct ast_dial *dial;
05102    struct sla_ringing_station *ringing_station;
05103    const char *cid_name = NULL, *cid_num = NULL;
05104    enum ast_dial_result res;
05105 
05106    if (!(dial = ast_dial_create()))
05107       return -1;
05108 
05109    ast_dial_set_state_callback(dial, sla_dial_state_callback);
05110    tech_data = ast_strdupa(station->device);
05111    tech = strsep(&tech_data, "/");
05112 
05113    if (ast_dial_append(dial, tech, tech_data) == -1) {
05114       ast_dial_destroy(dial);
05115       return -1;
05116    }
05117 
05118    if (!sla.attempt_callerid && !ast_strlen_zero(ringing_trunk->trunk->chan->cid.cid_name)) {
05119       cid_name = ast_strdupa(ringing_trunk->trunk->chan->cid.cid_name);
05120       ast_free(ringing_trunk->trunk->chan->cid.cid_name);
05121       ringing_trunk->trunk->chan->cid.cid_name = NULL;
05122    }
05123    if (!sla.attempt_callerid && !ast_strlen_zero(ringing_trunk->trunk->chan->cid.cid_num)) {
05124       cid_num = ast_strdupa(ringing_trunk->trunk->chan->cid.cid_num);
05125       ast_free(ringing_trunk->trunk->chan->cid.cid_num);
05126       ringing_trunk->trunk->chan->cid.cid_num = NULL;
05127    }
05128 
05129    res = ast_dial_run(dial, ringing_trunk->trunk->chan, 1);
05130    
05131    if (cid_name)
05132       ringing_trunk->trunk->chan->cid.cid_name = ast_strdup(cid_name);
05133    if (cid_num)
05134       ringing_trunk->trunk->chan->cid.cid_num = ast_strdup(cid_num);
05135    
05136    if (res != AST_DIAL_RESULT_TRYING) {
05137       struct sla_failed_station *failed_station;
05138       ast_dial_destroy(dial);
05139       if (!(failed_station = ast_calloc(1, sizeof(*failed_station))))
05140          return -1;
05141       failed_station->station = station;
05142       failed_station->last_try = ast_tvnow();
05143       AST_LIST_INSERT_HEAD(&sla.failed_stations, failed_station, entry);
05144       return -1;
05145    }
05146    if (!(ringing_station = sla_create_ringing_station(station))) {
05147       ast_dial_join(dial);
05148       ast_dial_destroy(dial);
05149       return -1;
05150    }
05151 
05152    station->dial = dial;
05153 
05154    AST_LIST_INSERT_HEAD(&sla.ringing_stations, ringing_station, entry);
05155 
05156    return 0;
05157 }
05158 
05159 /*! \brief Check to see if a station is in use
05160  */
05161 static int sla_check_inuse_station(const struct sla_station *station)
05162 {
05163    struct sla_trunk_ref *trunk_ref;
05164 
05165    AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
05166       if (trunk_ref->chan)
05167          return 1;
05168    }
05169 
05170    return 0;
05171 }
05172 
05173 static struct sla_trunk_ref *sla_find_trunk_ref(const struct sla_station *station,
05174    const struct sla_trunk *trunk)
05175 {
05176    struct sla_trunk_ref *trunk_ref = NULL;
05177 
05178    AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
05179       if (trunk_ref->trunk == trunk)
05180          break;
05181    }
05182 
05183    return trunk_ref;
05184 }
05185 
05186 /*! \brief Calculate the ring delay for a given ringing trunk on a station
05187  * \param station the station
05188  * \param ringing_trunk the trunk.  If NULL, the highest priority ringing trunk will be used
05189  * \return the number of ms left before the delay is complete, or INT_MAX if there is no delay
05190  */
05191 static int sla_check_station_delay(struct sla_station *station, 
05192    struct sla_ringing_trunk *ringing_trunk)
05193 {
05194    struct sla_trunk_ref *trunk_ref;
05195    unsigned int delay = UINT_MAX;
05196    int time_left, time_elapsed;
05197 
05198    if (!ringing_trunk)
05199       ringing_trunk = sla_choose_ringing_trunk(station, &trunk_ref, 0);
05200    else
05201       trunk_ref = sla_find_trunk_ref(station, ringing_trunk->trunk);
05202 
05203    if (!ringing_trunk || !trunk_ref)
05204       return delay;
05205 
05206    /* If this station has a ring delay specific to the highest priority
05207     * ringing trunk, use that.  Otherwise, use the ring delay specified
05208     * globally for the station. */
05209    delay = trunk_ref->ring_delay;
05210    if (!delay)
05211       delay = station->ring_delay;
05212    if (!delay)
05213       return INT_MAX;
05214 
05215    time_elapsed = ast_tvdiff_ms(ast_tvnow(), ringing_trunk->ring_begin);
05216    time_left = (delay * 1000) - time_elapsed;
05217 
05218    return time_left;
05219 }
05220 
05221 /*! \brief Ring stations based on current set of ringing trunks
05222  * \note Assumes that sla.lock is locked
05223  */
05224 static void sla_ring_stations(void)
05225 {
05226    struct sla_station_ref *station_ref;
05227    struct sla_ringing_trunk *ringing_trunk;
05228 
05229    /* Make sure that every station that uses at least one of the ringing
05230     * trunks, is ringing. */
05231    AST_LIST_TRAVERSE(&sla.ringing_trunks, ringing_trunk, entry) {
05232       AST_LIST_TRAVERSE(&ringing_trunk->trunk->stations, station_ref, entry) {
05233          int time_left;
05234 
05235          /* Is this station already ringing? */
05236          if (sla_check_ringing_station(station_ref->station))
05237             continue;
05238 
05239          /* Is this station already in a call? */
05240          if (sla_check_inuse_station(station_ref->station))
05241             continue;
05242 
05243          /* Did we fail to dial this station earlier?  If so, has it been
05244           * a minute since we tried? */
05245          if (sla_check_failed_station(station_ref->station))
05246             continue;
05247 
05248          /* If this station already timed out while this trunk was ringing,
05249           * do not dial it again for this ringing trunk. */
05250          if (sla_check_timed_out_station(ringing_trunk, station_ref->station))
05251             continue;
05252 
05253          /* Check for a ring delay in progress */
05254          time_left = sla_check_station_delay(station_ref->station, ringing_trunk);
05255          if (time_left != INT_MAX && time_left > 0)
05256             continue;
05257 
05258          /* It is time to make this station begin to ring.  Do it! */
05259          sla_ring_station(ringing_trunk, station_ref->station);
05260       }
05261    }
05262    /* Now, all of the stations that should be ringing, are ringing. */
05263 }
05264 
05265 static void sla_hangup_stations(void)
05266 {
05267    struct sla_trunk_ref *trunk_ref;
05268    struct sla_ringing_station *ringing_station;
05269 
05270    AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_stations, ringing_station, entry) {
05271       AST_LIST_TRAVERSE(&ringing_station->station->trunks, trunk_ref, entry) {
05272          struct sla_ringing_trunk *ringing_trunk;
05273          ast_mutex_lock(&sla.lock);
05274          AST_LIST_TRAVERSE(&sla.ringing_trunks, ringing_trunk, entry) {
05275             if (trunk_ref->trunk == ringing_trunk->trunk)
05276                break;
05277          }
05278          ast_mutex_unlock(&sla.lock);
05279          if (ringing_trunk)
05280             break;
05281       }
05282       if (!trunk_ref) {
05283          AST_LIST_REMOVE_CURRENT(entry);
05284          ast_dial_join(ringing_station->station->dial);
05285          ast_dial_destroy(ringing_station->station->dial);
05286          ringing_station->station->dial = NULL;
05287          ast_free(ringing_station);
05288       }
05289    }
05290    AST_LIST_TRAVERSE_SAFE_END
05291 }
05292 
05293 static void sla_handle_ringing_trunk_event(void)
05294 {
05295    ast_mutex_lock(&sla.lock);
05296    sla_ring_stations();
05297    ast_mutex_unlock(&sla.lock);
05298 
05299    /* Find stations that shouldn't be ringing anymore. */
05300    sla_hangup_stations();
05301 }
05302 
05303 static void sla_handle_hold_event(struct sla_event *event)
05304 {
05305    ast_atomic_fetchadd_int((int *) &event->trunk_ref->trunk->hold_stations, 1);
05306    event->trunk_ref->state = SLA_TRUNK_STATE_ONHOLD_BYME;
05307    ast_devstate_changed(AST_DEVICE_ONHOLD, "SLA:%s_%s", 
05308       event->station->name, event->trunk_ref->trunk->name);
05309    sla_change_trunk_state(event->trunk_ref->trunk, SLA_TRUNK_STATE_ONHOLD, 
05310       INACTIVE_TRUNK_REFS, event->trunk_ref);
05311 
05312    if (event->trunk_ref->trunk->active_stations == 1) {
05313       /* The station putting it on hold is the only one on the call, so start
05314        * Music on hold to the trunk. */
05315       event->trunk_ref->trunk->on_hold = 1;
05316       ast_indicate(event->trunk_ref->trunk->chan, AST_CONTROL_HOLD);
05317    }
05318 
05319    ast_softhangup(event->trunk_ref->chan, AST_SOFTHANGUP_DEV);
05320    event->trunk_ref->chan = NULL;
05321 }
05322 
05323 /*! \brief Process trunk ring timeouts
05324  * \note Called with sla.lock locked
05325  * \return non-zero if a change to the ringing trunks was made
05326  */
05327 static int sla_calc_trunk_timeouts(unsigned int *timeout)
05328 {
05329    struct sla_ringing_trunk *ringing_trunk;
05330    int res = 0;
05331 
05332    AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_trunks, ringing_trunk, entry) {
05333       int time_left, time_elapsed;
05334       if (!ringing_trunk->trunk->ring_timeout)
05335          continue;
05336       time_elapsed = ast_tvdiff_ms(ast_tvnow(), ringing_trunk->ring_begin);
05337       time_left = (ringing_trunk->trunk->ring_timeout * 1000) - time_elapsed;
05338       if (time_left <= 0) {
05339          pbx_builtin_setvar_helper(ringing_trunk->trunk->chan, "SLATRUNK_STATUS", "RINGTIMEOUT");
05340          AST_LIST_REMOVE_CURRENT(entry);
05341          sla_stop_ringing_trunk(ringing_trunk);
05342          res = 1;
05343          continue;
05344       }
05345       if (time_left < *timeout)
05346          *timeout = time_left;
05347    }
05348    AST_LIST_TRAVERSE_SAFE_END;
05349 
05350    return res;
05351 }
05352 
05353 /*! \brief Process station ring timeouts
05354  * \note Called with sla.lock locked
05355  * \return non-zero if a change to the ringing stations was made
05356  */
05357 static int sla_calc_station_timeouts(unsigned int *timeout)
05358 {
05359    struct sla_ringing_trunk *ringing_trunk;
05360    struct sla_ringing_station *ringing_station;
05361    int res = 0;
05362 
05363    AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_stations, ringing_station, entry) {
05364       unsigned int ring_timeout = 0;
05365       int time_elapsed, time_left = INT_MAX, final_trunk_time_left = INT_MIN;
05366       struct sla_trunk_ref *trunk_ref;
05367 
05368       /* If there are any ring timeouts specified for a specific trunk
05369        * on the station, then use the highest per-trunk ring timeout.
05370        * Otherwise, use the ring timeout set for the entire station. */
05371       AST_LIST_TRAVERSE(&ringing_station->station->trunks, trunk_ref, entry) {
05372          struct sla_station_ref *station_ref;
05373          int trunk_time_elapsed, trunk_time_left;
05374 
05375          AST_LIST_TRAVERSE(&sla.ringing_trunks, ringing_trunk, entry) {
05376             if (ringing_trunk->trunk == trunk_ref->trunk)
05377                break;
05378          }
05379          if (!ringing_trunk)
05380             continue;
05381 
05382          /* If there is a trunk that is ringing without a timeout, then the
05383           * only timeout that could matter is a global station ring timeout. */
05384          if (!trunk_ref->ring_timeout)
05385             break;
05386 
05387          /* This trunk on this station is ringing and has a timeout.
05388           * However, make sure this trunk isn't still ringing from a
05389           * previous timeout.  If so, don't consider it. */
05390          AST_LIST_TRAVERSE(&ringing_trunk->timed_out_stations, station_ref, entry) {
05391             if (station_ref->station == ringing_station->station)
05392                break;
05393          }
05394          if (station_ref)
05395             continue;
05396 
05397          trunk_time_elapsed = ast_tvdiff_ms(ast_tvnow(), ringing_trunk->ring_begin);
05398          trunk_time_left = (trunk_ref->ring_timeout * 1000) - trunk_time_elapsed;
05399          if (trunk_time_left > final_trunk_time_left)
05400             final_trunk_time_left = trunk_time_left;
05401       }
05402 
05403       /* No timeout was found for ringing trunks, and no timeout for the entire station */
05404       if (final_trunk_time_left == INT_MIN && !ringing_station->station->ring_timeout)
05405          continue;
05406 
05407       /* Compute how much time is left for a global station timeout */
05408       if (ringing_station->station->ring_timeout) {
05409          ring_timeout = ringing_station->station->ring_timeout;
05410          time_elapsed = ast_tvdiff_ms(ast_tvnow(), ringing_station->ring_begin);
05411          time_left = (ring_timeout * 1000) - time_elapsed;
05412       }
05413 
05414       /* If the time left based on the per-trunk timeouts is smaller than the
05415        * global station ring timeout, use that. */
05416       if (final_trunk_time_left > INT_MIN && final_trunk_time_left < time_left)
05417          time_left = final_trunk_time_left;
05418 
05419       /* If there is no time left, the station needs to stop ringing */
05420       if (time_left <= 0) {
05421          AST_LIST_REMOVE_CURRENT(entry);
05422          sla_stop_ringing_station(ringing_station, SLA_STATION_HANGUP_TIMEOUT);
05423          res = 1;
05424          continue;
05425       }
05426 
05427       /* There is still some time left for this station to ring, so save that
05428        * timeout if it is the first event scheduled to occur */
05429       if (time_left < *timeout)
05430          *timeout = time_left;
05431    }
05432    AST_LIST_TRAVERSE_SAFE_END;
05433 
05434    return res;
05435 }
05436 
05437 /*! \brief Calculate the ring delay for a station
05438  * \note Assumes sla.lock is locked
05439  */
05440 static int sla_calc_station_delays(unsigned int *timeout)
05441 {
05442    struct sla_station *station;
05443    int res = 0;
05444 
05445    AST_LIST_TRAVERSE(&sla_stations, station, entry) {
05446       struct sla_ringing_trunk *ringing_trunk;
05447       int time_left;
05448 
05449       /* Ignore stations already ringing */
05450       if (sla_check_ringing_station(station))
05451          continue;
05452 
05453       /* Ignore stations already on a call */
05454       if (sla_check_inuse_station(station))
05455          continue;
05456 
05457       /* Ignore stations that don't have one of their trunks ringing */
05458       if (!(ringing_trunk = sla_choose_ringing_trunk(station, NULL, 0)))
05459          continue;
05460 
05461       if ((time_left = sla_check_station_delay(station, ringing_trunk)) == INT_MAX)
05462          continue;
05463 
05464       /* If there is no time left, then the station needs to start ringing.
05465        * Return non-zero so that an event will be queued up an event to 
05466        * make that happen. */
05467       if (time_left <= 0) {
05468          res = 1;
05469          continue;
05470       }
05471 
05472       if (time_left < *timeout)
05473          *timeout = time_left;
05474    }
05475 
05476    return res;
05477 }
05478 
05479 /*! \brief Calculate the time until the next known event
05480  *  \note Called with sla.lock locked */
05481 static int sla_process_timers(struct timespec *ts)
05482 {
05483    unsigned int timeout = UINT_MAX;
05484    struct timeval wait;
05485    unsigned int change_made = 0;
05486 
05487    /* Check for ring timeouts on ringing trunks */
05488    if (sla_calc_trunk_timeouts(&timeout))
05489       change_made = 1;
05490 
05491    /* Check for ring timeouts on ringing stations */
05492    if (sla_calc_station_timeouts(&timeout))
05493       change_made = 1;
05494 
05495    /* Check for station ring delays */
05496    if (sla_calc_station_delays(&timeout))
05497       change_made = 1;
05498 
05499    /* queue reprocessing of ringing trunks */
05500    if (change_made)
05501       sla_queue_event_nolock(SLA_EVENT_RINGING_TRUNK);
05502 
05503    /* No timeout */
05504    if (timeout == UINT_MAX)
05505       return 0;
05506 
05507    if (ts) {
05508       wait = ast_tvadd(ast_tvnow(), ast_samp2tv(timeout, 1000));
05509       ts->tv_sec = wait.tv_sec;
05510       ts->tv_nsec = wait.tv_usec * 1000;
05511    }
05512 
05513    return 1;
05514 }
05515 
05516 static int sla_load_config(int reload);
05517 
05518 /*! \brief Check if we can do a reload of SLA, and do it if we can */
05519 static void sla_check_reload(void)
05520 {
05521    struct sla_station *station;
05522    struct sla_trunk *trunk;
05523 
05524    ast_mutex_lock(&sla.lock);
05525 
05526    if (!AST_LIST_EMPTY(&sla.event_q) || !AST_LIST_EMPTY(&sla.ringing_trunks) 
05527       || !AST_LIST_EMPTY(&sla.ringing_stations)) {
05528       ast_mutex_unlock(&sla.lock);
05529       return;
05530    }
05531 
05532    AST_RWLIST_RDLOCK(&sla_stations);
05533    AST_RWLIST_TRAVERSE(&sla_stations, station, entry) {
05534       if (station->ref_count)
05535          break;
05536    }
05537    AST_RWLIST_UNLOCK(&sla_stations);
05538    if (station) {
05539       ast_mutex_unlock(&sla.lock);
05540       return;
05541    }
05542 
05543    AST_RWLIST_RDLOCK(&sla_trunks);
05544    AST_RWLIST_TRAVERSE(&sla_trunks, trunk, entry) {
05545       if (trunk->ref_count)
05546          break;
05547    }
05548    AST_RWLIST_UNLOCK(&sla_trunks);
05549    if (trunk) {
05550       ast_mutex_unlock(&sla.lock);
05551       return;
05552    }
05553 
05554    /* We need to actually delete the previous versions of trunks and stations now */
05555    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sla_stations, station, entry) {
05556       AST_RWLIST_REMOVE_CURRENT(entry);
05557       ast_free(station);
05558    }
05559    AST_RWLIST_TRAVERSE_SAFE_END;
05560 
05561    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&sla_trunks, trunk, entry) {
05562       AST_RWLIST_REMOVE_CURRENT(entry);
05563       ast_free(trunk);
05564    }
05565    AST_RWLIST_TRAVERSE_SAFE_END;
05566 
05567    /* yay */
05568    sla_load_config(1);
05569    sla.reload = 0;
05570 
05571    ast_mutex_unlock(&sla.lock);
05572 }
05573 
05574 static void *sla_thread(void *data)
05575 {
05576    struct sla_failed_station *failed_station;
05577    struct sla_ringing_station *ringing_station;
05578 
05579    ast_mutex_lock(&sla.lock);
05580 
05581    while (!sla.stop) {
05582       struct sla_event *event;
05583       struct timespec ts = { 0, };
05584       unsigned int have_timeout = 0;
05585 
05586       if (AST_LIST_EMPTY(&sla.event_q)) {
05587          if ((have_timeout = sla_process_timers(&ts)))
05588             ast_cond_timedwait(&sla.cond, &sla.lock, &ts);
05589          else
05590             ast_cond_wait(&sla.cond, &sla.lock);
05591          if (sla.stop)
05592             break;
05593       }
05594 
05595       if (have_timeout)
05596          sla_process_timers(NULL);
05597 
05598       while ((event = AST_LIST_REMOVE_HEAD(&sla.event_q, entry))) {
05599          ast_mutex_unlock(&sla.lock);
05600          switch (event->type) {
05601          case SLA_EVENT_HOLD:
05602             sla_handle_hold_event(event);
05603             break;
05604          case SLA_EVENT_DIAL_STATE:
05605             sla_handle_dial_state_event();
05606             break;
05607          case SLA_EVENT_RINGING_TRUNK:
05608             sla_handle_ringing_trunk_event();
05609             break;
05610          case SLA_EVENT_RELOAD:
05611             sla.reload = 1;
05612          case SLA_EVENT_CHECK_RELOAD:
05613             break;
05614          }
05615          ast_free(event);
05616          ast_mutex_lock(&sla.lock);
05617       }
05618 
05619       if (sla.reload) {
05620          sla_check_reload();
05621       }
05622    }
05623 
05624    ast_mutex_unlock(&sla.lock);
05625 
05626    while ((ringing_station = AST_LIST_REMOVE_HEAD(&sla.ringing_stations, entry)))
05627       ast_free(ringing_station);
05628 
05629    while ((failed_station = AST_LIST_REMOVE_HEAD(&sla.failed_stations, entry)))
05630       ast_free(failed_station);
05631 
05632    return NULL;
05633 }
05634 
05635 struct dial_trunk_args {
05636    struct sla_trunk_ref *trunk_ref;
05637    struct sla_station *station;
05638    ast_mutex_t *cond_lock;
05639    ast_cond_t *cond;
05640 };
05641 
05642 static void *dial_trunk(void *data)
05643 {
05644    struct dial_trunk_args *args = data;
05645    struct ast_dial *dial;
05646    char *tech, *tech_data;
05647    enum ast_dial_result dial_res;
05648    char conf_name[MAX_CONFNUM];
05649    struct ast_conference *conf;
05650    struct ast_flags conf_flags = { 0 };
05651    struct sla_trunk_ref *trunk_ref = args->trunk_ref;
05652    const char *cid_name = NULL, *cid_num = NULL;
05653 
05654    if (!(dial = ast_dial_create())) {
05655       ast_mutex_lock(args->cond_lock);
05656       ast_cond_signal(args->cond);
05657       ast_mutex_unlock(args->cond_lock);
05658       return NULL;
05659    }
05660 
05661    tech_data = ast_strdupa(trunk_ref->trunk->device);
05662    tech = strsep(&tech_data, "/");
05663    if (ast_dial_append(dial, tech, tech_data) == -1) {
05664       ast_mutex_lock(args->cond_lock);
05665       ast_cond_signal(args->cond);
05666       ast_mutex_unlock(args->cond_lock);
05667       ast_dial_destroy(dial);
05668       return NULL;
05669    }
05670 
05671    if (!sla.attempt_callerid && !ast_strlen_zero(trunk_ref->chan->cid.cid_name)) {
05672       cid_name = ast_strdupa(trunk_ref->chan->cid.cid_name);
05673       ast_free(trunk_ref->chan->cid.cid_name);
05674       trunk_ref->chan->cid.cid_name = NULL;
05675    }
05676    if (!sla.attempt_callerid && !ast_strlen_zero(trunk_ref->chan->cid.cid_num)) {
05677       cid_num = ast_strdupa(trunk_ref->chan->cid.cid_num);
05678       ast_free(trunk_ref->chan->cid.cid_num);
05679       trunk_ref->chan->cid.cid_num = NULL;
05680    }
05681 
05682    dial_res = ast_dial_run(dial, trunk_ref->chan, 1);
05683 
05684    if (cid_name)
05685       trunk_ref->chan->cid.cid_name = ast_strdup(cid_name);
05686    if (cid_num)
05687       trunk_ref->chan->cid.cid_num = ast_strdup(cid_num);
05688 
05689    if (dial_res != AST_DIAL_RESULT_TRYING) {
05690       ast_mutex_lock(args->cond_lock);
05691       ast_cond_signal(args->cond);
05692       ast_mutex_unlock(args->cond_lock);
05693       ast_dial_destroy(dial);
05694       return NULL;
05695    }
05696 
05697    for (;;) {
05698       unsigned int done = 0;
05699       switch ((dial_res = ast_dial_state(dial))) {
05700       case AST_DIAL_RESULT_ANSWERED:
05701          trunk_ref->trunk->chan = ast_dial_answered(dial);
05702       case AST_DIAL_RESULT_HANGUP:
05703       case AST_DIAL_RESULT_INVALID:
05704       case AST_DIAL_RESULT_FAILED:
05705       case AST_DIAL_RESULT_TIMEOUT:
05706       case AST_DIAL_RESULT_UNANSWERED:
05707          done = 1;
05708       case AST_DIAL_RESULT_TRYING:
05709       case AST_DIAL_RESULT_RINGING:
05710       case AST_DIAL_RESULT_PROGRESS:
05711       case AST_DIAL_RESULT_PROCEEDING:
05712          break;
05713       }
05714       if (done)
05715          break;
05716    }
05717 
05718    if (!trunk_ref->trunk->chan) {
05719       ast_mutex_lock(args->cond_lock);
05720       ast_cond_signal(args->cond);
05721       ast_mutex_unlock(args->cond_lock);
05722       ast_dial_join(dial);
05723       ast_dial_destroy(dial);
05724       return NULL;
05725    }
05726 
05727    snprintf(conf_name, sizeof(conf_name), "SLA_%s", trunk_ref->trunk->name);
05728    ast_set_flag(&conf_flags, 
05729       CONFFLAG_QUIET | CONFFLAG_MARKEDEXIT | CONFFLAG_MARKEDUSER | 
05730       CONFFLAG_PASS_DTMF | CONFFLAG_SLA_TRUNK);
05731    conf = build_conf(conf_name, "", "", 1, 1, 1, trunk_ref->trunk->chan);
05732 
05733    ast_mutex_lock(args->cond_lock);
05734    ast_cond_signal(args->cond);
05735    ast_mutex_unlock(args->cond_lock);
05736 
05737    if (conf) {
05738       conf_run(trunk_ref->trunk->chan, conf, conf_flags.flags, NULL);
05739       dispose_conf(conf);
05740       conf = NULL;
05741    }
05742 
05743    /* If the trunk is going away, it is definitely now IDLE. */
05744    sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
05745 
05746    trunk_ref->trunk->chan = NULL;
05747    trunk_ref->trunk->on_hold = 0;
05748 
05749    ast_dial_join(dial);
05750    ast_dial_destroy(dial);
05751 
05752    return NULL;
05753 }
05754 
05755 /*! \brief For a given station, choose the highest priority idle trunk
05756  */
05757 static struct sla_trunk_ref *sla_choose_idle_trunk(const struct sla_station *station)
05758 {
05759    struct sla_trunk_ref *trunk_ref = NULL;
05760 
05761    AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
05762       if (trunk_ref->state == SLA_TRUNK_STATE_IDLE)
05763          break;
05764    }
05765 
05766    return trunk_ref;
05767 }
05768 
05769 static int sla_station_exec(struct ast_channel *chan, void *data)
05770 {
05771    char *station_name, *trunk_name;
05772    struct sla_station *station;
05773    struct sla_trunk_ref *trunk_ref = NULL;
05774    char conf_name[MAX_CONFNUM];
05775    struct ast_flags conf_flags = { 0 };
05776    struct ast_conference *conf;
05777 
05778    if (ast_strlen_zero(data)) {
05779       ast_log(LOG_WARNING, "Invalid Arguments to SLAStation!\n");
05780       pbx_builtin_setvar_helper(chan, "SLASTATION_STATUS", "FAILURE");
05781       return 0;
05782    }
05783 
05784    trunk_name = ast_strdupa(data);
05785    station_name = strsep(&trunk_name, "_");
05786 
05787    if (ast_strlen_zero(station_name)) {
05788       ast_log(LOG_WARNING, "Invalid Arguments to SLAStation!\n");
05789       pbx_builtin_setvar_helper(chan, "SLASTATION_STATUS", "FAILURE");
05790       return 0;
05791    }
05792 
05793    AST_RWLIST_RDLOCK(&sla_stations);
05794    station = sla_find_station(station_name);
05795    if (station)
05796       ast_atomic_fetchadd_int((int *) &station->ref_count, 1);
05797    AST_RWLIST_UNLOCK(&sla_stations);
05798 
05799    if (!station) {
05800       ast_log(LOG_WARNING, "Station '%s' not found!\n", station_name);
05801       pbx_builtin_setvar_helper(chan, "SLASTATION_STATUS", "FAILURE");
05802       sla_queue_event(SLA_EVENT_CHECK_RELOAD);
05803       return 0;
05804    }
05805 
05806    AST_RWLIST_RDLOCK(&sla_trunks);
05807    if (!ast_strlen_zero(trunk_name)) {
05808       trunk_ref = sla_find_trunk_ref_byname(station, trunk_name);
05809    } else
05810       trunk_ref = sla_choose_idle_trunk(station);
05811    AST_RWLIST_UNLOCK(&sla_trunks);
05812 
05813    if (!trunk_ref) {
05814       if (ast_strlen_zero(trunk_name))
05815          ast_log(LOG_NOTICE, "No trunks available for call.\n");
05816       else {
05817          ast_log(LOG_NOTICE, "Can't join existing call on trunk "
05818             "'%s' due to access controls.\n", trunk_name);
05819       }
05820       pbx_builtin_setvar_helper(chan, "SLASTATION_STATUS", "CONGESTION");
05821       ast_atomic_fetchadd_int((int *) &station->ref_count, -1);
05822       sla_queue_event(SLA_EVENT_CHECK_RELOAD);
05823       return 0;
05824    }
05825 
05826    if (trunk_ref->state == SLA_TRUNK_STATE_ONHOLD_BYME) {
05827       if (ast_atomic_dec_and_test((int *) &trunk_ref->trunk->hold_stations) == 1)
05828          sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_UP, ALL_TRUNK_REFS, NULL);
05829       else {
05830          trunk_ref->state = SLA_TRUNK_STATE_UP;
05831          ast_devstate_changed(AST_DEVICE_INUSE, 
05832             "SLA:%s_%s", station->name, trunk_ref->trunk->name);
05833       }
05834    } else if (trunk_ref->state == SLA_TRUNK_STATE_RINGING) {
05835       struct sla_ringing_trunk *ringing_trunk;
05836 
05837       ast_mutex_lock(&sla.lock);
05838       AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_trunks, ringing_trunk, entry) {
05839          if (ringing_trunk->trunk == trunk_ref->trunk) {
05840             AST_LIST_REMOVE_CURRENT(entry);
05841             break;
05842          }
05843       }
05844       AST_LIST_TRAVERSE_SAFE_END
05845       ast_mutex_unlock(&sla.lock);
05846 
05847       if (ringing_trunk) {
05848          answer_trunk_chan(ringing_trunk->trunk->chan);
05849          sla_change_trunk_state(ringing_trunk->trunk, SLA_TRUNK_STATE_UP, ALL_TRUNK_REFS, NULL);
05850 
05851          free(ringing_trunk);
05852 
05853          /* Queue up reprocessing ringing trunks, and then ringing stations again */
05854          sla_queue_event(SLA_EVENT_RINGING_TRUNK);
05855          sla_queue_event(SLA_EVENT_DIAL_STATE);
05856       }
05857    }
05858 
05859    trunk_ref->chan = chan;
05860 
05861    if (!trunk_ref->trunk->chan) {
05862       ast_mutex_t cond_lock;
05863       ast_cond_t cond;
05864       pthread_t dont_care;
05865       struct dial_trunk_args args = {
05866          .trunk_ref = trunk_ref,
05867          .station = station,
05868          .cond_lock = &cond_lock,
05869          .cond = &cond,
05870       };
05871       sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_UP, ALL_TRUNK_REFS, NULL);
05872       /* Create a thread to dial the trunk and dump it into the conference.
05873        * However, we want to wait until the trunk has been dialed and the
05874        * conference is created before continuing on here. */
05875       ast_autoservice_start(chan);
05876       ast_mutex_init(&cond_lock);
05877       ast_cond_init(&cond, NULL);
05878       ast_mutex_lock(&cond_lock);
05879       ast_pthread_create_detached_background(&dont_care, NULL, dial_trunk, &args);
05880       ast_cond_wait(&cond, &cond_lock);
05881       ast_mutex_unlock(&cond_lock);
05882       ast_mutex_destroy(&cond_lock);
05883       ast_cond_destroy(&cond);
05884       ast_autoservice_stop(chan);
05885       if (!trunk_ref->trunk->chan) {
05886          ast_debug(1, "Trunk didn't get created. chan: %lx\n", (long) trunk_ref->trunk->chan);
05887          pbx_builtin_setvar_helper(chan, "SLASTATION_STATUS", "CONGESTION");
05888          sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
05889          trunk_ref->chan = NULL;
05890          ast_atomic_fetchadd_int((int *) &station->ref_count, -1);
05891          sla_queue_event(SLA_EVENT_CHECK_RELOAD);
05892          return 0;
05893       }
05894    }
05895 
05896    if (ast_atomic_fetchadd_int((int *) &trunk_ref->trunk->active_stations, 1) == 0 &&
05897       trunk_ref->trunk->on_hold) {
05898       trunk_ref->trunk->on_hold = 0;
05899       ast_indicate(trunk_ref->trunk->chan, AST_CONTROL_UNHOLD);
05900       sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_UP, ALL_TRUNK_REFS, NULL);
05901    }
05902 
05903    snprintf(conf_name, sizeof(conf_name), "SLA_%s", trunk_ref->trunk->name);
05904    ast_set_flag(&conf_flags, 
05905       CONFFLAG_QUIET | CONFFLAG_MARKEDEXIT | CONFFLAG_PASS_DTMF | CONFFLAG_SLA_STATION);
05906    ast_answer(chan);
05907    conf = build_conf(conf_name, "", "", 0, 0, 1, chan);
05908    if (conf) {
05909       conf_run(chan, conf, conf_flags.flags, NULL);
05910       dispose_conf(conf);
05911       conf = NULL;
05912    }
05913    trunk_ref->chan = NULL;
05914    if (ast_atomic_dec_and_test((int *) &trunk_ref->trunk->active_stations) &&
05915       trunk_ref->state != SLA_TRUNK_STATE_ONHOLD_BYME) {
05916       strncat(conf_name, ",K", sizeof(conf_name) - strlen(conf_name) - 1);
05917       admin_exec(NULL, conf_name);
05918       trunk_ref->trunk->hold_stations = 0;
05919       sla_change_trunk_state(trunk_ref->trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
05920    }
05921    
05922    pbx_builtin_setvar_helper(chan, "SLASTATION_STATUS", "SUCCESS");
05923 
05924    ast_atomic_fetchadd_int((int *) &station->ref_count, -1);
05925    sla_queue_event(SLA_EVENT_CHECK_RELOAD);
05926 
05927    return 0;
05928 }
05929 
05930 static struct sla_trunk_ref *create_trunk_ref(struct sla_trunk *trunk)
05931 {
05932    struct sla_trunk_ref *trunk_ref;
05933 
05934    if (!(trunk_ref = ast_calloc(1, sizeof(*trunk_ref))))
05935       return NULL;
05936 
05937    trunk_ref->trunk = trunk;
05938 
05939    return trunk_ref;
05940 }
05941 
05942 static struct sla_ringing_trunk *queue_ringing_trunk(struct sla_trunk *trunk)
05943 {
05944    struct sla_ringing_trunk *ringing_trunk;
05945 
05946    if (!(ringing_trunk = ast_calloc(1, sizeof(*ringing_trunk))))
05947       return NULL;
05948    
05949    ringing_trunk->trunk = trunk;
05950    ringing_trunk->ring_begin = ast_tvnow();
05951 
05952    sla_change_trunk_state(trunk, SLA_TRUNK_STATE_RINGING, ALL_TRUNK_REFS, NULL);
05953 
05954    ast_mutex_lock(&sla.lock);
05955    AST_LIST_INSERT_HEAD(&sla.ringing_trunks, ringing_trunk, entry);
05956    ast_mutex_unlock(&sla.lock);
05957 
05958    sla_queue_event(SLA_EVENT_RINGING_TRUNK);
05959 
05960    return ringing_trunk;
05961 }
05962 
05963 enum {
05964    SLA_TRUNK_OPT_MOH = (1 << 0),
05965 };
05966 
05967 enum {
05968    SLA_TRUNK_OPT_ARG_MOH_CLASS = 0,
05969    SLA_TRUNK_OPT_ARG_ARRAY_SIZE = 1,
05970 };
05971 
05972 AST_APP_OPTIONS(sla_trunk_opts, BEGIN_OPTIONS
05973    AST_APP_OPTION_ARG('M', SLA_TRUNK_OPT_MOH, SLA_TRUNK_OPT_ARG_MOH_CLASS),
05974 END_OPTIONS );
05975 
05976 static int sla_trunk_exec(struct ast_channel *chan, void *data)
05977 {
05978    char conf_name[MAX_CONFNUM];
05979    struct ast_conference *conf;
05980    struct ast_flags conf_flags = { 0 };
05981    struct sla_trunk *trunk;
05982    struct sla_ringing_trunk *ringing_trunk;
05983    AST_DECLARE_APP_ARGS(args,
05984       AST_APP_ARG(trunk_name);
05985       AST_APP_ARG(options);
05986    );
05987    char *opts[SLA_TRUNK_OPT_ARG_ARRAY_SIZE] = { NULL, };
05988    char *conf_opt_args[OPT_ARG_ARRAY_SIZE] = { NULL, };
05989    struct ast_flags opt_flags = { 0 };
05990    char *parse;
05991 
05992    if (ast_strlen_zero(data)) {
05993       ast_log(LOG_ERROR, "The SLATrunk application requires an argument, the trunk name\n");
05994       return -1;
05995    }
05996 
05997    parse = ast_strdupa(data);
05998    AST_STANDARD_APP_ARGS(args, parse);
05999    if (args.argc == 2) {
06000       if (ast_app_parse_options(sla_trunk_opts, &opt_flags, opts, args.options)) {
06001          ast_log(LOG_ERROR, "Error parsing options for SLATrunk\n");
06002          return -1;
06003       }
06004    }
06005 
06006    AST_RWLIST_RDLOCK(&sla_trunks);
06007    trunk = sla_find_trunk(args.trunk_name);
06008    if (trunk)
06009       ast_atomic_fetchadd_int((int *) &trunk->ref_count, 1);
06010    AST_RWLIST_UNLOCK(&sla_trunks);
06011 
06012    if (!trunk) {
06013       ast_log(LOG_ERROR, "SLA Trunk '%s' not found!\n", args.trunk_name);
06014       pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "FAILURE");
06015       sla_queue_event(SLA_EVENT_CHECK_RELOAD);  
06016       return 0;
06017    }
06018 
06019    if (trunk->chan) {
06020       ast_log(LOG_ERROR, "Call came in on %s, but the trunk is already in use!\n",
06021          args.trunk_name);
06022       pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "FAILURE");
06023       ast_atomic_fetchadd_int((int *) &trunk->ref_count, -1);
06024       sla_queue_event(SLA_EVENT_CHECK_RELOAD);  
06025       return 0;
06026    }
06027 
06028    trunk->chan = chan;
06029 
06030    if (!(ringing_trunk = queue_ringing_trunk(trunk))) {
06031       pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "FAILURE");
06032       ast_atomic_fetchadd_int((int *) &trunk->ref_count, -1);
06033       sla_queue_event(SLA_EVENT_CHECK_RELOAD);  
06034       return 0;
06035    }
06036 
06037    snprintf(conf_name, sizeof(conf_name), "SLA_%s", args.trunk_name);
06038    conf = build_conf(conf_name, "", "", 1, 1, 1, chan);
06039    if (!conf) {
06040       pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "FAILURE");
06041       ast_atomic_fetchadd_int((int *) &trunk->ref_count, -1);
06042       sla_queue_event(SLA_EVENT_CHECK_RELOAD);  
06043       return 0;
06044    }
06045    ast_set_flag(&conf_flags, 
06046       CONFFLAG_QUIET | CONFFLAG_MARKEDEXIT | CONFFLAG_MARKEDUSER | CONFFLAG_PASS_DTMF | CONFFLAG_NO_AUDIO_UNTIL_UP);
06047 
06048    if (ast_test_flag(&opt_flags, SLA_TRUNK_OPT_MOH)) {
06049       ast_indicate(chan, -1);
06050       ast_set_flag(&conf_flags, CONFFLAG_MOH);
06051       conf_opt_args[OPT_ARG_MOH_CLASS] = opts[SLA_TRUNK_OPT_ARG_MOH_CLASS];
06052    } else
06053       ast_indicate(chan, AST_CONTROL_RINGING);
06054 
06055    conf_run(chan, conf, conf_flags.flags, opts);
06056    dispose_conf(conf);
06057    conf = NULL;
06058    trunk->chan = NULL;
06059    trunk->on_hold = 0;
06060 
06061    sla_change_trunk_state(trunk, SLA_TRUNK_STATE_IDLE, ALL_TRUNK_REFS, NULL);
06062 
06063    if (!pbx_builtin_getvar_helper(chan, "SLATRUNK_STATUS"))
06064       pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "SUCCESS");
06065 
06066    /* Remove the entry from the list of ringing trunks if it is still there. */
06067    ast_mutex_lock(&sla.lock);
06068    AST_LIST_TRAVERSE_SAFE_BEGIN(&sla.ringing_trunks, ringing_trunk, entry) {
06069       if (ringing_trunk->trunk == trunk) {
06070          AST_LIST_REMOVE_CURRENT(entry);
06071          break;
06072       }
06073    }
06074    AST_LIST_TRAVERSE_SAFE_END;
06075    ast_mutex_unlock(&sla.lock);
06076    if (ringing_trunk) {
06077       ast_free(ringing_trunk);
06078       pbx_builtin_setvar_helper(chan, "SLATRUNK_STATUS", "UNANSWERED");
06079       /* Queue reprocessing of ringing trunks to make stations stop ringing
06080        * that shouldn't be ringing after this trunk stopped. */
06081       sla_queue_event(SLA_EVENT_RINGING_TRUNK);
06082    }
06083 
06084    ast_atomic_fetchadd_int((int *) &trunk->ref_count, -1);
06085    sla_queue_event(SLA_EVENT_CHECK_RELOAD);  
06086 
06087    return 0;
06088 }
06089 
06090 static enum ast_device_state sla_state(const char *data)
06091 {
06092    char *buf, *station_name, *trunk_name;
06093    struct sla_station *station;
06094    struct sla_trunk_ref *trunk_ref;
06095    enum ast_device_state res = AST_DEVICE_INVALID;
06096 
06097    trunk_name = buf = ast_strdupa(data);
06098    station_name = strsep(&trunk_name, "_");
06099 
06100    AST_RWLIST_RDLOCK(&sla_stations);
06101    AST_LIST_TRAVERSE(&sla_stations, station, entry) {
06102       if (strcasecmp(station_name, station->name))
06103          continue;
06104       AST_RWLIST_RDLOCK(&sla_trunks);
06105       AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
06106          if (!strcasecmp(trunk_name, trunk_ref->trunk->name))
06107             break;
06108       }
06109       if (!trunk_ref) {
06110          AST_RWLIST_UNLOCK(&sla_trunks);
06111          break;
06112       }
06113       res = sla_state_to_devstate(trunk_ref->state);
06114       AST_RWLIST_UNLOCK(&sla_trunks);
06115    }
06116    AST_RWLIST_UNLOCK(&sla_stations);
06117 
06118    if (res == AST_DEVICE_INVALID) {
06119       ast_log(LOG_ERROR, "Could not determine state for trunk %s on station %s!\n",
06120          trunk_name, station_name);
06121    }
06122 
06123    return res;
06124 }
06125 
06126 static void destroy_trunk(struct sla_trunk *trunk)
06127 {
06128    struct sla_station_ref *station_ref;
06129 
06130    if (!ast_strlen_zero(trunk->autocontext))
06131       ast_context_remove_extension(trunk->autocontext, "s", 1, sla_registrar);
06132 
06133    while ((station_ref = AST_LIST_REMOVE_HEAD(&trunk->stations, entry)))
06134       ast_free(station_ref);
06135 
06136    ast_string_field_free_memory(trunk);
06137    ast_free(trunk);
06138 }
06139 
06140 static void destroy_station(struct sla_station *station)
06141 {
06142    struct sla_trunk_ref *trunk_ref;
06143 
06144    if (!ast_strlen_zero(station->autocontext)) {
06145       AST_RWLIST_RDLOCK(&sla_trunks);
06146       AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
06147          char exten[AST_MAX_EXTENSION];
06148          char hint[AST_MAX_APP];
06149          snprintf(exten, sizeof(exten), "%s_%s", station->name, trunk_ref->trunk->name);
06150          snprintf(hint, sizeof(hint), "SLA:%s", exten);
06151          ast_context_remove_extension(station->autocontext, exten, 
06152             1, sla_registrar);
06153          ast_context_remove_extension(station->autocontext, hint, 
06154             PRIORITY_HINT, sla_registrar);
06155       }
06156       AST_RWLIST_UNLOCK(&sla_trunks);
06157    }
06158 
06159    while ((trunk_ref = AST_LIST_REMOVE_HEAD(&station->trunks, entry)))
06160       ast_free(trunk_ref);
06161 
06162    ast_string_field_free_memory(station);
06163    ast_free(station);
06164 }
06165 
06166 static void sla_destroy(void)
06167 {
06168    struct sla_trunk *trunk;
06169    struct sla_station *station;
06170 
06171    AST_RWLIST_WRLOCK(&sla_trunks);
06172    while ((trunk = AST_RWLIST_REMOVE_HEAD(&sla_trunks, entry)))
06173       destroy_trunk(trunk);
06174    AST_RWLIST_UNLOCK(&sla_trunks);
06175 
06176    AST_RWLIST_WRLOCK(&sla_stations);
06177    while ((station = AST_RWLIST_REMOVE_HEAD(&sla_stations, entry)))
06178       destroy_station(station);
06179    AST_RWLIST_UNLOCK(&sla_stations);
06180 
06181    if (sla.thread != AST_PTHREADT_NULL) {
06182       ast_mutex_lock(&sla.lock);
06183       sla.stop = 1;
06184       ast_cond_signal(&sla.cond);
06185       ast_mutex_unlock(&sla.lock);
06186       pthread_join(sla.thread, NULL);
06187    }
06188 
06189    /* Drop any created contexts from the dialplan */
06190    ast_context_destroy(NULL, sla_registrar);
06191 
06192    ast_mutex_destroy(&sla.lock);
06193    ast_cond_destroy(&sla.cond);
06194 }
06195 
06196 static int sla_check_device(const char *device)
06197 {
06198    char *tech, *tech_data;
06199 
06200    tech_data = ast_strdupa(device);
06201    tech = strsep(&tech_data, "/");
06202 
06203    if (ast_strlen_zero(tech) || ast_strlen_zero(tech_data))
06204       return -1;
06205 
06206    return 0;
06207 }
06208 
06209 static int sla_build_trunk(struct ast_config *cfg, const char *cat)
06210 {
06211    struct sla_trunk *trunk;
06212    struct ast_variable *var;
06213    const char *dev;
06214 
06215    if (!(dev = ast_variable_retrieve(cfg, cat, "device"))) {
06216       ast_log(LOG_ERROR, "SLA Trunk '%s' defined with no device!\n", cat);
06217       return -1;
06218    }
06219 
06220    if (sla_check_device(dev)) {
06221       ast_log(LOG_ERROR, "SLA Trunk '%s' define with invalid device '%s'!\n",
06222          cat, dev);
06223       return -1;
06224    }
06225 
06226    if (!(trunk = ast_calloc(1, sizeof(*trunk))))
06227       return -1;
06228    if (ast_string_field_init(trunk, 32)) {
06229       ast_free(trunk);
06230       return -1;
06231    }
06232 
06233    ast_string_field_set(trunk, name, cat);
06234    ast_string_field_set(trunk, device, dev);
06235 
06236    for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
06237       if (!strcasecmp(var->name, "autocontext"))
06238          ast_string_field_set(trunk, autocontext, var->value);
06239       else if (!strcasecmp(var->name, "ringtimeout")) {
06240          if (sscanf(var->value, "%30u", &trunk->ring_timeout) != 1) {
06241             ast_log(LOG_WARNING, "Invalid ringtimeout '%s' specified for trunk '%s'\n",
06242                var->value, trunk->name);
06243             trunk->ring_timeout = 0;
06244          }
06245       } else if (!strcasecmp(var->name, "barge"))
06246          trunk->barge_disabled = ast_false(var->value);
06247       else if (!strcasecmp(var->name, "hold")) {
06248          if (!strcasecmp(var->value, "private"))
06249             trunk->hold_access = SLA_HOLD_PRIVATE;
06250          else if (!strcasecmp(var->value, "open"))
06251             trunk->hold_access = SLA_HOLD_OPEN;
06252          else {
06253             ast_log(LOG_WARNING, "Invalid value '%s' for hold on trunk %s\n",
06254                var->value, trunk->name);
06255          }
06256       } else if (strcasecmp(var->name, "type") && strcasecmp(var->name, "device")) {
06257          ast_log(LOG_ERROR, "Invalid option '%s' specified at line %d of %s!\n",
06258             var->name, var->lineno, SLA_CONFIG_FILE);
06259       }
06260    }
06261 
06262    if (!ast_strlen_zero(trunk->autocontext)) {
06263       struct ast_context *context;
06264       context = ast_context_find_or_create(NULL, NULL, trunk->autocontext, sla_registrar);
06265       if (!context) {
06266          ast_log(LOG_ERROR, "Failed to automatically find or create "
06267             "context '%s' for SLA!\n", trunk->autocontext);
06268          destroy_trunk(trunk);
06269          return -1;
06270       }
06271       if (ast_add_extension2(context, 0 /* don't replace */, "s", 1,
06272          NULL, NULL, slatrunk_app, ast_strdup(trunk->name), ast_free_ptr, sla_registrar)) {
06273          ast_log(LOG_ERROR, "Failed to automatically create extension "
06274             "for trunk '%s'!\n", trunk->name);
06275          destroy_trunk(trunk);
06276          return -1;
06277       }
06278    }
06279 
06280    AST_RWLIST_WRLOCK(&sla_trunks);
06281    AST_RWLIST_INSERT_TAIL(&sla_trunks, trunk, entry);
06282    AST_RWLIST_UNLOCK(&sla_trunks);
06283 
06284    return 0;
06285 }
06286 
06287 static void sla_add_trunk_to_station(struct sla_station *station, struct ast_variable *var)
06288 {
06289    struct sla_trunk *trunk;
06290    struct sla_trunk_ref *trunk_ref;
06291    struct sla_station_ref *station_ref;
06292    char *trunk_name, *options, *cur;
06293 
06294    options = ast_strdupa(var->value);
06295    trunk_name = strsep(&options, ",");
06296    
06297    AST_RWLIST_RDLOCK(&sla_trunks);
06298    AST_RWLIST_TRAVERSE(&sla_trunks, trunk, entry) {
06299       if (!strcasecmp(trunk->name, trunk_name))
06300          break;
06301    }
06302 
06303    AST_RWLIST_UNLOCK(&sla_trunks);
06304    if (!trunk) {
06305       ast_log(LOG_ERROR, "Trunk '%s' not found!\n", var->value);
06306       return;
06307    }
06308    if (!(trunk_ref = create_trunk_ref(trunk)))
06309       return;
06310    trunk_ref->state = SLA_TRUNK_STATE_IDLE;
06311 
06312    while ((cur = strsep(&options, ","))) {
06313       char *name, *value = cur;
06314       name = strsep(&value, "=");
06315       if (!strcasecmp(name, "ringtimeout")) {
06316          if (sscanf(value, "%30u", &trunk_ref->ring_timeout) != 1) {
06317             ast_log(LOG_WARNING, "Invalid ringtimeout value '%s' for "
06318                "trunk '%s' on station '%s'\n", value, trunk->name, station->name);
06319             trunk_ref->ring_timeout = 0;
06320          }
06321       } else if (!strcasecmp(name, "ringdelay")) {
06322          if (sscanf(value, "%30u", &trunk_ref->ring_delay) != 1) {
06323             ast_log(LOG_WARNING, "Invalid ringdelay value '%s' for "
06324                "trunk '%s' on station '%s'\n", value, trunk->name, station->name);
06325             trunk_ref->ring_delay = 0;
06326          }
06327       } else {
06328          ast_log(LOG_WARNING, "Invalid option '%s' for "
06329             "trunk '%s' on station '%s'\n", name, trunk->name, station->name);
06330       }
06331    }
06332 
06333    if (!(station_ref = sla_create_station_ref(station))) {
06334       ast_free(trunk_ref);
06335       return;
06336    }
06337    ast_atomic_fetchadd_int((int *) &trunk->num_stations, 1);
06338    AST_RWLIST_WRLOCK(&sla_trunks);
06339    AST_LIST_INSERT_TAIL(&trunk->stations, station_ref, entry);
06340    AST_RWLIST_UNLOCK(&sla_trunks);
06341    AST_LIST_INSERT_TAIL(&station->trunks, trunk_ref, entry);
06342 }
06343 
06344 static int sla_build_station(struct ast_config *cfg, const char *cat)
06345 {
06346    struct sla_station *station;
06347    struct ast_variable *var;
06348    const char *dev;
06349 
06350    if (!(dev = ast_variable_retrieve(cfg, cat, "device"))) {
06351       ast_log(LOG_ERROR, "SLA Station '%s' defined with no device!\n", cat);
06352       return -1;
06353    }
06354 
06355    if (!(station = ast_calloc(1, sizeof(*station))))
06356       return -1;
06357    if (ast_string_field_init(station, 32)) {
06358       ast_free(station);
06359       return -1;
06360    }
06361 
06362    ast_string_field_set(station, name, cat);
06363    ast_string_field_set(station, device, dev);
06364 
06365    for (var = ast_variable_browse(cfg, cat); var; var = var->next) {
06366       if (!strcasecmp(var->name, "trunk"))
06367          sla_add_trunk_to_station(station, var);
06368       else if (!strcasecmp(var->name, "autocontext"))
06369          ast_string_field_set(station, autocontext, var->value);
06370       else if (!strcasecmp(var->name, "ringtimeout")) {
06371          if (sscanf(var->value, "%30u", &station->ring_timeout) != 1) {
06372             ast_log(LOG_WARNING, "Invalid ringtimeout '%s' specified for station '%s'\n",
06373                var->value, station->name);
06374             station->ring_timeout = 0;
06375          }
06376       } else if (!strcasecmp(var->name, "ringdelay")) {
06377          if (sscanf(var->value, "%30u", &station->ring_delay) != 1) {
06378             ast_log(LOG_WARNING, "Invalid ringdelay '%s' specified for station '%s'\n",
06379                var->value, station->name);
06380             station->ring_delay = 0;
06381          }
06382       } else if (!strcasecmp(var->name, "hold")) {
06383          if (!strcasecmp(var->value, "private"))
06384             station->hold_access = SLA_HOLD_PRIVATE;
06385          else if (!strcasecmp(var->value, "open"))
06386             station->hold_access = SLA_HOLD_OPEN;
06387          else {
06388             ast_log(LOG_WARNING, "Invalid value '%s' for hold on station %s\n",
06389                var->value, station->name);
06390          }
06391 
06392       } else if (strcasecmp(var->name, "type") && strcasecmp(var->name, "device")) {
06393          ast_log(LOG_ERROR, "Invalid option '%s' specified at line %d of %s!\n",
06394             var->name, var->lineno, SLA_CONFIG_FILE);
06395       }
06396    }
06397 
06398    if (!ast_strlen_zero(station->autocontext)) {
06399       struct ast_context *context;
06400       struct sla_trunk_ref *trunk_ref;
06401       context = ast_context_find_or_create(NULL, NULL, station->autocontext, sla_registrar);
06402       if (!context) {
06403          ast_log(LOG_ERROR, "Failed to automatically find or create "
06404             "context '%s' for SLA!\n", station->autocontext);
06405          destroy_station(station);
06406          return -1;
06407       }
06408       /* The extension for when the handset goes off-hook.
06409        * exten => station1,1,SLAStation(station1) */
06410       if (ast_add_extension2(context, 0 /* don't replace */, station->name, 1,
06411          NULL, NULL, slastation_app, ast_strdup(station->name), ast_free_ptr, sla_registrar)) {
06412          ast_log(LOG_ERROR, "Failed to automatically create extension "
06413             "for trunk '%s'!\n", station->name);
06414          destroy_station(station);
06415          return -1;
06416       }
06417       AST_RWLIST_RDLOCK(&sla_trunks);
06418       AST_LIST_TRAVERSE(&station->trunks, trunk_ref, entry) {
06419          char exten[AST_MAX_EXTENSION];
06420          char hint[AST_MAX_APP];
06421          snprintf(exten, sizeof(exten), "%s_%s", station->name, trunk_ref->trunk->name);
06422          snprintf(hint, sizeof(hint), "SLA:%s", exten);
06423          /* Extension for this line button 
06424           * exten => station1_line1,1,SLAStation(station1_line1) */
06425          if (ast_add_extension2(context, 0 /* don't replace */, exten, 1,
06426             NULL, NULL, slastation_app, ast_strdup(exten), ast_free_ptr, sla_registrar)) {
06427             ast_log(LOG_ERROR, "Failed to automatically create extension "
06428                "for trunk '%s'!\n", station->name);
06429             destroy_station(station);
06430             return -1;
06431          }
06432          /* Hint for this line button 
06433           * exten => station1_line1,hint,SLA:station1_line1 */
06434          if (ast_add_extension2(context, 0 /* don't replace */, exten, PRIORITY_HINT,
06435             NULL, NULL, hint, NULL, NULL, sla_registrar)) {
06436             ast_log(LOG_ERROR, "Failed to automatically create hint "
06437                "for trunk '%s'!\n", station->name);
06438             destroy_station(station);
06439             return -1;
06440          }
06441       }
06442       AST_RWLIST_UNLOCK(&sla_trunks);
06443    }
06444 
06445    AST_RWLIST_WRLOCK(&sla_stations);
06446    AST_RWLIST_INSERT_TAIL(&sla_stations, station, entry);
06447    AST_RWLIST_UNLOCK(&sla_stations);
06448 
06449    return 0;
06450 }
06451 
06452 static int sla_load_config(int reload)
06453 {
06454    struct ast_config *cfg;
06455    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
06456    const char *cat = NULL;
06457    int res = 0;
06458    const char *val;
06459 
06460    if (!reload) {
06461       ast_mutex_init(&sla.lock);
06462       ast_cond_init(&sla.cond, NULL);
06463    }
06464 
06465    if (!(cfg = ast_config_load(SLA_CONFIG_FILE, config_flags))) {
06466       return 0; /* Treat no config as normal */
06467    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
06468       return 0;
06469    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
06470       ast_log(LOG_ERROR, "Config file " SLA_CONFIG_FILE " is in an invalid format.  Aborting.\n");
06471       return 0;
06472    }
06473 
06474    if ((val = ast_variable_retrieve(cfg, "general", "attemptcallerid")))
06475       sla.attempt_callerid = ast_true(val);
06476 
06477    while ((cat = ast_category_browse(cfg, cat)) && !res) {
06478       const char *type;
06479       if (!strcasecmp(cat, "general"))
06480          continue;
06481       if (!(type = ast_variable_retrieve(cfg, cat, "type"))) {
06482          ast_log(LOG_WARNING, "Invalid entry in %s defined with no type!\n",
06483             SLA_CONFIG_FILE);
06484          continue;
06485       }
06486       if (!strcasecmp(type, "trunk"))
06487          res = sla_build_trunk(cfg, cat);
06488       else if (!strcasecmp(type, "station"))
06489          res = sla_build_station(cfg, cat);
06490       else {
06491          ast_log(LOG_WARNING, "Entry in %s defined with invalid type '%s'!\n",
06492             SLA_CONFIG_FILE, type);
06493       }
06494    }
06495 
06496    ast_config_destroy(cfg);
06497 
06498    /* Even if we don't have any stations, we may after a reload and we need to
06499     * be able to process the SLA_EVENT_RELOAD event in that case */
06500    if (sla.thread == AST_PTHREADT_NULL && (!AST_LIST_EMPTY(&sla_stations) || !AST_LIST_EMPTY(&sla_trunks))) {
06501       ast_pthread_create(&sla.thread, NULL, sla_thread, NULL);
06502    }
06503 
06504    return res;
06505 }
06506 
06507 static int acf_meetme_info_eval(char *keyword, struct ast_conference *conf)
06508 {
06509    if (!strcasecmp("lock", keyword)) {
06510       return conf->locked;
06511    } else if (!strcasecmp("parties", keyword)) {
06512       return conf->users;
06513    } else if (!strcasecmp("activity", keyword)) {
06514       time_t now;
06515       now = time(NULL);
06516       return (now - conf->start);
06517    } else if (!strcasecmp("dynamic", keyword)) {
06518       return conf->isdynamic;
06519    } else {
06520       return -1;
06521    }
06522 
06523 }
06524 
06525 static int acf_meetme_info(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
06526 {
06527    struct ast_conference *conf;
06528    char *parse;
06529    int result = -2; /* only non-negative numbers valid, -1 is used elsewhere */
06530    AST_DECLARE_APP_ARGS(args,
06531       AST_APP_ARG(keyword);
06532       AST_APP_ARG(confno);
06533    );
06534 
06535    if (ast_strlen_zero(data)) {
06536       ast_log(LOG_ERROR, "Syntax: MEETME_INFO() requires two arguments\n");
06537       return -1;
06538    }
06539 
06540    parse = ast_strdupa(data);
06541    AST_STANDARD_APP_ARGS(args, parse);
06542 
06543    if (ast_strlen_zero(args.keyword)) {
06544       ast_log(LOG_ERROR, "Syntax: MEETME_INFO() requires a keyword\n");
06545       return -1;
06546    }
06547 
06548    if (ast_strlen_zero(args.confno)) {
06549       ast_log(LOG_ERROR, "Syntax: MEETME_INFO() requires a conference number\n");
06550       return -1;
06551    }
06552 
06553    AST_LIST_LOCK(&confs);
06554    AST_LIST_TRAVERSE(&confs, conf, list) {
06555       if (!strcmp(args.confno, conf->confno)) {
06556          result = acf_meetme_info_eval(args.keyword, conf);
06557          break;
06558       }
06559    }
06560    AST_LIST_UNLOCK(&confs);
06561 
06562    if (result > -1) {
06563       snprintf(buf, len, "%d", result);
06564    } else if (result == -1) {
06565       ast_log(LOG_NOTICE, "Error: invalid keyword: '%s'\n", args.keyword);
06566       snprintf(buf, len, "0");
06567    } else if (result == -2) {
06568       ast_log(LOG_NOTICE, "Error: conference (%s) not found\n", args.confno); 
06569       snprintf(buf, len, "0");
06570    }
06571 
06572    return 0;
06573 }
06574 
06575 
06576 static struct ast_custom_function meetme_info_acf = {
06577    .name = "MEETME_INFO",
06578    .synopsis = "Query a given conference of various properties.",
06579    .syntax = "MEETME_INFO(<keyword>,<confno>)",
06580    .read = acf_meetme_info,
06581    .desc =
06582 "Returns information from a given keyword. (For booleans 1-true, 0-false)\n"
06583 "  Options:\n"
06584 "    lock     - boolean of whether the corresponding conference is locked\n" 
06585 "    parties  - number of parties in a given conference\n"
06586 "    activity - duration of conference in seconds\n"
06587 "    dynamic  - boolean of whether the corresponding coference is dynamic\n",
06588 };
06589 
06590 
06591 static int load_config(int reload)
06592 {
06593    load_config_meetme();
06594 
06595    if (reload && sla.thread != AST_PTHREADT_NULL) {
06596       sla_queue_event(SLA_EVENT_RELOAD);
06597       ast_log(LOG_NOTICE, "A reload of the SLA configuration has been requested "
06598          "and will be completed when the system is idle.\n");
06599       return 0;
06600    }
06601    
06602    return sla_load_config(0);
06603 }
06604 
06605 static int unload_module(void)
06606 {
06607    int res = 0;
06608    
06609    ast_cli_unregister_multiple(cli_meetme, ARRAY_LEN(cli_meetme));
06610    res = ast_manager_unregister("MeetmeMute");
06611    res |= ast_manager_unregister("MeetmeUnmute");
06612    res |= ast_manager_unregister("MeetmeList");
06613    res |= ast_unregister_application(app4);
06614    res |= ast_unregister_application(app3);
06615    res |= ast_unregister_application(app2);
06616    res |= ast_unregister_application(app);
06617    res |= ast_unregister_application(slastation_app);
06618    res |= ast_unregister_application(slatrunk_app);
06619 
06620    ast_devstate_prov_del("Meetme");
06621    ast_devstate_prov_del("SLA");
06622    
06623    sla_destroy();
06624    
06625    res |= ast_custom_function_unregister(&meetme_info_acf);
06626    ast_unload_realtime("meetme");
06627 
06628    return res;
06629 }
06630 
06631 static int load_module(void)
06632 {
06633    int res = 0;
06634 
06635    res |= load_config(0);
06636 
06637    ast_cli_register_multiple(cli_meetme, ARRAY_LEN(cli_meetme));
06638    res |= ast_manager_register("MeetmeMute", EVENT_FLAG_CALL, 
06639                 action_meetmemute, "Mute a Meetme user");
06640    res |= ast_manager_register("MeetmeUnmute", EVENT_FLAG_CALL, 
06641                 action_meetmeunmute, "Unmute a Meetme user");
06642    res |= ast_manager_register2("MeetmeList", EVENT_FLAG_REPORTING, 
06643                 action_meetmelist, "List participants in a conference", mandescr_meetmelist);
06644    res |= ast_register_application_xml(app4, channel_admin_exec);
06645    res |= ast_register_application_xml(app3, admin_exec);
06646    res |= ast_register_application_xml(app2, count_exec);
06647    res |= ast_register_application_xml(app, conf_exec);
06648    res |= ast_register_application_xml(slastation_app, sla_station_exec);
06649    res |= ast_register_application_xml(slatrunk_app, sla_trunk_exec);
06650 
06651    res |= ast_devstate_prov_add("Meetme", meetmestate);
06652    res |= ast_devstate_prov_add("SLA", sla_state);
06653 
06654    res |= ast_custom_function_register(&meetme_info_acf);
06655    ast_realtime_require_field("meetme", "confno", RQ_UINTEGER2, 3, "members", RQ_UINTEGER1, 3, NULL);
06656 
06657    return res;
06658 }
06659 
06660 static int reload(void)
06661 {
06662    ast_unload_realtime("meetme");
06663    return load_config(1);
06664 }
06665 
06666 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "MeetMe conference bridge",
06667       .load = load_module,
06668       .unload = unload_module,
06669       .reload = reload,
06670           );
06671 

Generated on Wed Aug 11 01:04:59 2010 for Asterisk - the Open Source PBX by  doxygen 1.5.9