Thu Aug 30 20:43:00 2012

Asterisk developer's documentation


chan_dahdi.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief DAHDI for Pseudo TDM
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * Connects to the DAHDI telephony library as well as
00026  * libpri. Libpri is optional and needed only if you are
00027  * going to use ISDN connections.
00028  *
00029  * You need to install libraries before you attempt to compile
00030  * and install the DAHDI channel.
00031  *
00032  * \par See also
00033  * \arg \ref Config_dahdi
00034  *
00035  * \ingroup channel_drivers
00036  *
00037  * \todo Deprecate the "musiconhold" configuration option post 1.4
00038  */
00039 
00040 /*** MODULEINFO
00041    <use>res_smdi</use>
00042    <depend>dahdi</depend>
00043    <depend>tonezone</depend>
00044    <use>pri</use>
00045    <use>ss7</use>
00046    <use>openr2</use>
00047    <support_level>core</support_level>
00048  ***/
00049 
00050 #include "asterisk.h"
00051 
00052 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 368759 $")
00053 
00054 #if defined(__NetBSD__) || defined(__FreeBSD__)
00055 #include <pthread.h>
00056 #include <signal.h>
00057 #else
00058 #include <sys/signal.h>
00059 #endif
00060 #include <sys/ioctl.h>
00061 #include <sys/stat.h>
00062 #include <math.h>
00063 #include <ctype.h>
00064 
00065 #include <dahdi/user.h>
00066 #include <dahdi/tonezone.h>
00067 #include "sig_analog.h"
00068 /* Analog signaling is currently still present in chan_dahdi for use with
00069  * radio. Sig_analog does not currently handle any radio operations. If
00070  * radio only uses analog signaling, then the radio handling logic could
00071  * be placed in sig_analog and the duplicated code could be removed.
00072  */
00073 
00074 #ifdef HAVE_PRI
00075 #include "sig_pri.h"
00076 #endif
00077 
00078 #if defined(HAVE_SS7)
00079 #include "sig_ss7.h"
00080 #endif   /* defined(HAVE_SS7) */
00081 
00082 #ifdef HAVE_OPENR2
00083 /* put this here until sig_mfcr2 comes along */
00084 #define SIG_MFCR2_MAX_CHANNELS   672      /*!< No more than a DS3 per trunk group */
00085 #include <openr2.h>
00086 #endif
00087 
00088 #include "asterisk/lock.h"
00089 #include "asterisk/channel.h"
00090 #include "asterisk/config.h"
00091 #include "asterisk/module.h"
00092 #include "asterisk/pbx.h"
00093 #include "asterisk/file.h"
00094 #include "asterisk/ulaw.h"
00095 #include "asterisk/alaw.h"
00096 #include "asterisk/callerid.h"
00097 #include "asterisk/adsi.h"
00098 #include "asterisk/cli.h"
00099 #include "asterisk/cdr.h"
00100 #include "asterisk/cel.h"
00101 #include "asterisk/features.h"
00102 #include "asterisk/musiconhold.h"
00103 #include "asterisk/say.h"
00104 #include "asterisk/tdd.h"
00105 #include "asterisk/app.h"
00106 #include "asterisk/dsp.h"
00107 #include "asterisk/astdb.h"
00108 #include "asterisk/manager.h"
00109 #include "asterisk/causes.h"
00110 #include "asterisk/term.h"
00111 #include "asterisk/utils.h"
00112 #include "asterisk/transcap.h"
00113 #include "asterisk/stringfields.h"
00114 #include "asterisk/abstract_jb.h"
00115 #include "asterisk/smdi.h"
00116 #include "asterisk/astobj.h"
00117 #include "asterisk/event.h"
00118 #include "asterisk/devicestate.h"
00119 #include "asterisk/paths.h"
00120 #include "asterisk/ccss.h"
00121 #include "asterisk/data.h"
00122 
00123 /*** DOCUMENTATION
00124    <application name="DAHDISendKeypadFacility" language="en_US">
00125       <synopsis>
00126          Send digits out of band over a PRI.
00127       </synopsis>
00128       <syntax>
00129          <parameter name="digits" required="true" />
00130       </syntax>
00131       <description>
00132          <para>This application will send the given string of digits in a Keypad
00133          Facility IE over the current channel.</para>
00134       </description>
00135    </application>
00136    <application name="DAHDISendCallreroutingFacility" language="en_US">
00137       <synopsis>
00138          Send an ISDN call rerouting/deflection facility message.
00139       </synopsis>
00140       <syntax argsep=",">
00141          <parameter name="destination" required="true">
00142             <para>Destination number.</para>
00143          </parameter>
00144          <parameter name="original">
00145             <para>Original called number.</para>
00146          </parameter>
00147          <parameter name="reason">
00148             <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
00149          </parameter>
00150       </syntax>
00151       <description>
00152          <para>This application will send an ISDN switch specific call
00153          rerouting/deflection facility message over the current channel.
00154          Supported switches depend upon the version of libpri in use.</para>
00155       </description>
00156    </application>
00157    <application name="DAHDIAcceptR2Call" language="en_US">
00158       <synopsis>
00159          Accept an R2 call if its not already accepted (you still need to answer it)
00160       </synopsis>
00161       <syntax>
00162          <parameter name="charge" required="true">
00163             <para>Yes or No.</para>
00164             <para>Whether you want to accept the call with charge or without charge.</para>
00165          </parameter>
00166       </syntax>
00167       <description>
00168          <para>This application will Accept the R2 call either with charge or no charge.</para>
00169       </description>
00170    </application>
00171    <manager name="DAHDITransfer" language="en_US">
00172       <synopsis>
00173          Transfer DAHDI Channel.
00174       </synopsis>
00175       <syntax>
00176          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00177          <parameter name="DAHDIChannel" required="true">
00178             <para>DAHDI channel number to transfer.</para>
00179          </parameter>
00180       </syntax>
00181       <description>
00182          <para>Simulate a flash hook event by the user connected to the channel.</para>
00183          <note><para>Valid only for analog channels.</para></note>
00184       </description>
00185    </manager>
00186    <manager name="DAHDIHangup" language="en_US">
00187       <synopsis>
00188          Hangup DAHDI Channel.
00189       </synopsis>
00190       <syntax>
00191          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00192          <parameter name="DAHDIChannel" required="true">
00193             <para>DAHDI channel number to hangup.</para>
00194          </parameter>
00195       </syntax>
00196       <description>
00197          <para>Simulate an on-hook event by the user connected to the channel.</para>
00198          <note><para>Valid only for analog channels.</para></note>
00199       </description>
00200    </manager>
00201    <manager name="DAHDIDialOffhook" language="en_US">
00202       <synopsis>
00203          Dial over DAHDI channel while offhook.
00204       </synopsis>
00205       <syntax>
00206          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00207          <parameter name="DAHDIChannel" required="true">
00208             <para>DAHDI channel number to dial digits.</para>
00209          </parameter>
00210          <parameter name="Number" required="true">
00211             <para>Digits to dial.</para>
00212          </parameter>
00213       </syntax>
00214       <description>
00215          <para>Generate DTMF control frames to the bridged peer.</para>
00216       </description>
00217    </manager>
00218    <manager name="DAHDIDNDon" language="en_US">
00219       <synopsis>
00220          Toggle DAHDI channel Do Not Disturb status ON.
00221       </synopsis>
00222       <syntax>
00223          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00224          <parameter name="DAHDIChannel" required="true">
00225             <para>DAHDI channel number to set DND on.</para>
00226          </parameter>
00227       </syntax>
00228       <description>
00229          <para>Equivalent to the CLI command "dahdi set dnd <variable>channel</variable> on".</para>
00230          <note><para>Feature only supported by analog channels.</para></note>
00231       </description>
00232    </manager>
00233    <manager name="DAHDIDNDoff" language="en_US">
00234       <synopsis>
00235          Toggle DAHDI channel Do Not Disturb status OFF.
00236       </synopsis>
00237       <syntax>
00238          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00239          <parameter name="DAHDIChannel" required="true">
00240             <para>DAHDI channel number to set DND off.</para>
00241          </parameter>
00242       </syntax>
00243       <description>
00244          <para>Equivalent to the CLI command "dahdi set dnd <variable>channel</variable> off".</para>
00245          <note><para>Feature only supported by analog channels.</para></note>
00246       </description>
00247    </manager>
00248    <manager name="DAHDIShowChannels" language="en_US">
00249       <synopsis>
00250          Show status of DAHDI channels.
00251       </synopsis>
00252       <syntax>
00253          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00254          <parameter name="DAHDIChannel">
00255             <para>Specify the specific channel number to show.  Show all channels if zero or not present.</para>
00256          </parameter>
00257       </syntax>
00258       <description>
00259          <para>Similar to the CLI command "dahdi show channels".</para>
00260       </description>
00261    </manager>
00262    <manager name="DAHDIRestart" language="en_US">
00263       <synopsis>
00264          Fully Restart DAHDI channels (terminates calls).
00265       </synopsis>
00266       <syntax>
00267          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00268       </syntax>
00269       <description>
00270          <para>Equivalent to the CLI command "dahdi restart".</para>
00271       </description>
00272    </manager>
00273  ***/
00274 
00275 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
00276 
00277 static const char * const lbostr[] = {
00278 "0 db (CSU)/0-133 feet (DSX-1)",
00279 "133-266 feet (DSX-1)",
00280 "266-399 feet (DSX-1)",
00281 "399-533 feet (DSX-1)",
00282 "533-655 feet (DSX-1)",
00283 "-7.5db (CSU)",
00284 "-15db (CSU)",
00285 "-22.5db (CSU)"
00286 };
00287 
00288 /*! Global jitterbuffer configuration - by default, jb is disabled
00289  *  \note Values shown here match the defaults shown in chan_dahdi.conf.sample */
00290 static struct ast_jb_conf default_jbconf =
00291 {
00292    .flags = 0,
00293    .max_size = 200,
00294    .resync_threshold = 1000,
00295    .impl = "fixed",
00296    .target_extra = 40,
00297 };
00298 static struct ast_jb_conf global_jbconf;
00299 
00300 /*!
00301  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
00302  * the user hangs up to reset the state machine so ring works properly.
00303  * This is used to be able to support kewlstart by putting the zhone in
00304  * groundstart mode since their forward disconnect supervision is entirely
00305  * broken even though their documentation says it isn't and their support
00306  * is entirely unwilling to provide any assistance with their channel banks
00307  * even though their web site says they support their products for life.
00308  */
00309 /* #define ZHONE_HACK */
00310 
00311 /*! \brief Typically, how many rings before we should send Caller*ID */
00312 #define DEFAULT_CIDRINGS 1
00313 
00314 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
00315 
00316 
00317 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
00318 #define NEED_MFDETECT(p) (((p)->sig == SIG_FEATDMF) || ((p)->sig == SIG_FEATDMF_TA) || ((p)->sig == SIG_E911) || ((p)->sig == SIG_FGC_CAMA) || ((p)->sig == SIG_FGC_CAMAMF) || ((p)->sig == SIG_FEATB))
00319 
00320 static const char tdesc[] = "DAHDI Telephony Driver"
00321 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
00322    " w/"
00323    #if defined(HAVE_PRI)
00324       "PRI"
00325    #endif   /* defined(HAVE_PRI) */
00326    #if defined(HAVE_SS7)
00327       #if defined(HAVE_PRI)
00328       " & "
00329       #endif   /* defined(HAVE_PRI) */
00330       "SS7"
00331    #endif   /* defined(HAVE_SS7) */
00332    #if defined(HAVE_OPENR2)
00333       #if defined(HAVE_PRI) || defined(HAVE_SS7)
00334       " & "
00335       #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
00336       "MFC/R2"
00337    #endif   /* defined(HAVE_OPENR2) */
00338 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2) */
00339 ;
00340 
00341 static const char config[] = "chan_dahdi.conf";
00342 
00343 #define SIG_EM    DAHDI_SIG_EM
00344 #define SIG_EMWINK   (0x0100000 | DAHDI_SIG_EM)
00345 #define SIG_FEATD (0x0200000 | DAHDI_SIG_EM)
00346 #define  SIG_FEATDMF (0x0400000 | DAHDI_SIG_EM)
00347 #define  SIG_FEATB   (0x0800000 | DAHDI_SIG_EM)
00348 #define  SIG_E911 (0x1000000 | DAHDI_SIG_EM)
00349 #define  SIG_FEATDMF_TA (0x2000000 | DAHDI_SIG_EM)
00350 #define  SIG_FGC_CAMA   (0x4000000 | DAHDI_SIG_EM)
00351 #define  SIG_FGC_CAMAMF (0x8000000 | DAHDI_SIG_EM)
00352 #define SIG_FXSLS DAHDI_SIG_FXSLS
00353 #define SIG_FXSGS DAHDI_SIG_FXSGS
00354 #define SIG_FXSKS DAHDI_SIG_FXSKS
00355 #define SIG_FXOLS DAHDI_SIG_FXOLS
00356 #define SIG_FXOGS DAHDI_SIG_FXOGS
00357 #define SIG_FXOKS DAHDI_SIG_FXOKS
00358 #define SIG_PRI      DAHDI_SIG_CLEAR
00359 #define SIG_BRI      (0x2000000 | DAHDI_SIG_CLEAR)
00360 #define SIG_BRI_PTMP (0X4000000 | DAHDI_SIG_CLEAR)
00361 #define SIG_SS7      (0x1000000 | DAHDI_SIG_CLEAR)
00362 #define SIG_MFCR2    DAHDI_SIG_CAS
00363 #define  SIG_SF      DAHDI_SIG_SF
00364 #define SIG_SFWINK   (0x0100000 | DAHDI_SIG_SF)
00365 #define SIG_SF_FEATD (0x0200000 | DAHDI_SIG_SF)
00366 #define  SIG_SF_FEATDMF (0x0400000 | DAHDI_SIG_SF)
00367 #define  SIG_SF_FEATB   (0x0800000 | DAHDI_SIG_SF)
00368 #define SIG_EM_E1 DAHDI_SIG_EM_E1
00369 
00370 #ifdef LOTS_OF_SPANS
00371 #define NUM_SPANS DAHDI_MAX_SPANS
00372 #else
00373 #define NUM_SPANS       32
00374 #endif
00375 
00376 #define CHAN_PSEUDO  -2
00377 
00378 #define CALLPROGRESS_PROGRESS    1
00379 #define CALLPROGRESS_FAX_OUTGOING   2
00380 #define CALLPROGRESS_FAX_INCOMING   4
00381 #define CALLPROGRESS_FAX      (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
00382 
00383 #define NUM_CADENCE_MAX 25
00384 static int num_cadence = 4;
00385 static int user_has_defined_cadences = 0;
00386 
00387 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
00388    { { 125, 125, 2000, 4000 } },       /*!< Quick chirp followed by normal ring */
00389    { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
00390    { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
00391    { { 1000, 500, 2500, 5000 } },   /*!< Long ring */
00392 };
00393 
00394 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
00395  * is 1, the second pause is 2 and so on.
00396  */
00397 
00398 static int cidrings[NUM_CADENCE_MAX] = {
00399    2,                            /*!< Right after first long ring */
00400    4,                            /*!< Right after long part */
00401    3,                            /*!< After third chirp */
00402    2,                            /*!< Second spell */
00403 };
00404 
00405 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
00406 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
00407 
00408 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
00409          (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
00410 
00411 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
00412 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
00413 
00414 static char defaultcic[64] = "";
00415 static char defaultozz[64] = "";
00416 
00417 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
00418 static char mwimonitornotify[PATH_MAX] = "";
00419 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
00420 static int  mwisend_rpas = 0;
00421 #endif
00422 
00423 static char progzone[10] = "";
00424 
00425 static int usedistinctiveringdetection = 0;
00426 static int distinctiveringaftercid = 0;
00427 
00428 static int numbufs = 4;
00429 
00430 static int mwilevel = 512;
00431 static int dtmfcid_level = 256;
00432 
00433 #define REPORT_CHANNEL_ALARMS 1
00434 #define REPORT_SPAN_ALARMS    2 
00435 static int report_alarms = REPORT_CHANNEL_ALARMS;
00436 
00437 #ifdef HAVE_PRI
00438 static int pridebugfd = -1;
00439 static char pridebugfilename[1024] = "";
00440 #endif
00441 
00442 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
00443 static int firstdigittimeout = 16000;
00444 
00445 /*! \brief How long to wait for following digits (FXO logic) */
00446 static int gendigittimeout = 8000;
00447 
00448 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
00449 static int matchdigittimeout = 3000;
00450 
00451 /*! \brief Protect the interface list (of dahdi_pvt's) */
00452 AST_MUTEX_DEFINE_STATIC(iflock);
00453 
00454 
00455 static int ifcount = 0;
00456 
00457 #ifdef HAVE_PRI
00458 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
00459 #endif
00460 
00461 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00462    when it's doing something critical. */
00463 AST_MUTEX_DEFINE_STATIC(monlock);
00464 
00465 /*! \brief This is the thread for the monitor which checks for input on the channels
00466    which are not currently in use. */
00467 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00468 static ast_cond_t ss_thread_complete;
00469 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
00470 AST_MUTEX_DEFINE_STATIC(restart_lock);
00471 static int ss_thread_count = 0;
00472 static int num_restart_pending = 0;
00473 
00474 static int restart_monitor(void);
00475 
00476 static enum ast_bridge_result dahdi_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
00477 
00478 static int dahdi_sendtext(struct ast_channel *c, const char *text);
00479 
00480 static void mwi_event_cb(const struct ast_event *event, void *userdata)
00481 {
00482    /* This module does not handle MWI in an event-based manner.  However, it
00483     * subscribes to MWI for each mailbox that is configured so that the core
00484     * knows that we care about it.  Then, chan_dahdi will get the MWI from the
00485     * event cache instead of checking the mailbox directly. */
00486 }
00487 
00488 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
00489 static inline int dahdi_get_event(int fd)
00490 {
00491    int j;
00492    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00493       return -1;
00494    return j;
00495 }
00496 
00497 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
00498 static inline int dahdi_wait_event(int fd)
00499 {
00500    int i, j = 0;
00501    i = DAHDI_IOMUX_SIGEVENT;
00502    if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
00503       return -1;
00504    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00505       return -1;
00506    return j;
00507 }
00508 
00509 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
00510 #define READ_SIZE 160
00511 
00512 #define MASK_AVAIL      (1 << 0) /*!< Channel available for PRI use */
00513 #define MASK_INUSE      (1 << 1) /*!< Channel currently in use */
00514 
00515 #define CALLWAITING_SILENT_SAMPLES     ((300 * 8) / READ_SIZE) /*!< 300 ms */
00516 #define CALLWAITING_REPEAT_SAMPLES     ((10000 * 8) / READ_SIZE) /*!< 10,000 ms */
00517 #define CALLWAITING_SUPPRESS_SAMPLES   ((100 * 8) / READ_SIZE) /*!< 100 ms */
00518 #define CIDCW_EXPIRE_SAMPLES        ((500 * 8) / READ_SIZE) /*!< 500 ms */
00519 #define MIN_MS_SINCE_FLASH          ((2000) )   /*!< 2000 ms */
00520 #define DEFAULT_RINGT               ((8000 * 8) / READ_SIZE) /*!< 8,000 ms */
00521 
00522 struct dahdi_pvt;
00523 
00524 /*!
00525  * \brief Configured ring timeout base.
00526  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
00527  */
00528 static int ringt_base = DEFAULT_RINGT;
00529 
00530 #if defined(HAVE_SS7)
00531 
00532 struct dahdi_ss7 {
00533    struct sig_ss7_linkset ss7;
00534 };
00535 
00536 static struct dahdi_ss7 linksets[NUM_SPANS];
00537 
00538 static int cur_ss7type = -1;
00539 static int cur_linkset = -1;
00540 static int cur_pointcode = -1;
00541 static int cur_cicbeginswith = -1;
00542 static int cur_adjpointcode = -1;
00543 static int cur_networkindicator = -1;
00544 static int cur_defaultdpc = -1;
00545 #endif   /* defined(HAVE_SS7) */
00546 
00547 #ifdef HAVE_OPENR2
00548 struct dahdi_mfcr2 {
00549    pthread_t r2master;            /*!< Thread of master */
00550    openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
00551    struct dahdi_pvt *pvts[SIG_MFCR2_MAX_CHANNELS];     /*!< Member channel pvt structs */
00552    int numchans;                          /*!< Number of channels in this R2 block */
00553    int monitored_count;                   /*!< Number of channels being monitored */
00554 };
00555 
00556 struct dahdi_mfcr2_conf {
00557    openr2_variant_t variant;
00558    int mfback_timeout;
00559    int metering_pulse_timeout;
00560    int max_ani;
00561    int max_dnis;
00562    signed int get_ani_first:2;
00563 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
00564    signed int skip_category_request:2;
00565 #endif
00566    unsigned int call_files:1;
00567    unsigned int allow_collect_calls:1;
00568    unsigned int charge_calls:1;
00569    unsigned int accept_on_offer:1;
00570    unsigned int forced_release:1;
00571    unsigned int double_answer:1;
00572    signed int immediate_accept:2;
00573    char logdir[OR2_MAX_PATH];
00574    char r2proto_file[OR2_MAX_PATH];
00575    openr2_log_level_t loglevel;
00576    openr2_calling_party_category_t category;
00577 };
00578 
00579 /* malloc'd array of malloc'd r2links */
00580 static struct dahdi_mfcr2 **r2links;
00581 /* how many r2links have been malloc'd */
00582 static int r2links_count = 0;
00583 
00584 #endif /* HAVE_OPENR2 */
00585 
00586 #ifdef HAVE_PRI
00587 
00588 struct dahdi_pri {
00589    int dchannels[SIG_PRI_NUM_DCHANS];     /*!< What channel are the dchannels on */
00590    int mastertrunkgroup;               /*!< What trunk group is our master */
00591    int prilogicalspan;                 /*!< Logical span number within trunk group */
00592    struct sig_pri_span pri;
00593 };
00594 
00595 static struct dahdi_pri pris[NUM_SPANS];
00596 
00597 #if defined(HAVE_PRI_CCSS)
00598 /*! DAHDI PRI CCSS agent and monitor type name. */
00599 static const char dahdi_pri_cc_type[] = "DAHDI/PRI";
00600 #endif   /* defined(HAVE_PRI_CCSS) */
00601 
00602 #else
00603 /*! Shut up the compiler */
00604 struct dahdi_pri;
00605 #endif
00606 
00607 #define SUB_REAL  0        /*!< Active call */
00608 #define SUB_CALLWAIT 1        /*!< Call-Waiting call on hold */
00609 #define SUB_THREEWAY 2        /*!< Three-way call */
00610 
00611 /* Polarity states */
00612 #define POLARITY_IDLE   0
00613 #define POLARITY_REV    1
00614 
00615 
00616 struct distRingData {
00617    int ring[3];
00618    int range;
00619 };
00620 struct ringContextData {
00621    char contextData[AST_MAX_CONTEXT];
00622 };
00623 struct dahdi_distRings {
00624    struct distRingData ringnum[3];
00625    struct ringContextData ringContext[3];
00626 };
00627 
00628 static const char * const subnames[] = {
00629    "Real",
00630    "Callwait",
00631    "Threeway"
00632 };
00633 
00634 struct dahdi_subchannel {
00635    int dfd;
00636    struct ast_channel *owner;
00637    int chan;
00638    short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
00639    struct ast_frame f;     /*!< One frame for each channel.  How did this ever work before? */
00640    unsigned int needringing:1;
00641    unsigned int needbusy:1;
00642    unsigned int needcongestion:1;
00643    unsigned int needanswer:1;
00644    unsigned int needflash:1;
00645    unsigned int needhold:1;
00646    unsigned int needunhold:1;
00647    unsigned int linear:1;
00648    unsigned int inthreeway:1;
00649    struct dahdi_confinfo curconf;
00650 };
00651 
00652 #define CONF_USER_REAL     (1 << 0)
00653 #define CONF_USER_THIRDCALL   (1 << 1)
00654 
00655 #define MAX_SLAVES   4
00656 
00657 /* States for sending MWI message
00658  * First three states are required for send Ring Pulse Alert Signal
00659  */
00660 typedef enum {
00661    MWI_SEND_NULL = 0,
00662    MWI_SEND_SA,
00663    MWI_SEND_SA_WAIT,
00664    MWI_SEND_PAUSE,
00665    MWI_SEND_SPILL,
00666    MWI_SEND_CLEANUP,
00667    MWI_SEND_DONE,
00668 } mwisend_states;
00669 
00670 struct mwisend_info {
00671    struct   timeval  pause;
00672    mwisend_states    mwisend_current;
00673 };
00674 
00675 /*! Specify the lists dahdi_pvt can be put in. */
00676 enum DAHDI_IFLIST {
00677    DAHDI_IFLIST_NONE,   /*!< The dahdi_pvt is not in any list. */
00678    DAHDI_IFLIST_MAIN,   /*!< The dahdi_pvt is in the main interface list */
00679 #if defined(HAVE_PRI)
00680    DAHDI_IFLIST_NO_B_CHAN, /*!< The dahdi_pvt is in a no B channel interface list */
00681 #endif   /* defined(HAVE_PRI) */
00682 };
00683 
00684 struct dahdi_pvt {
00685    ast_mutex_t lock;             /*!< Channel private lock. */
00686    struct callerid_state *cs;
00687    struct ast_channel *owner;       /*!< Our current active owner (if applicable) */
00688                      /*!< Up to three channels can be associated with this call */
00689 
00690    struct dahdi_subchannel sub_unused;    /*!< Just a safety precaution */
00691    struct dahdi_subchannel subs[3];       /*!< Sub-channels */
00692    struct dahdi_confinfo saveconf;        /*!< Saved conference info */
00693 
00694    struct dahdi_pvt *slaves[MAX_SLAVES];     /*!< Slave to us (follows our conferencing) */
00695    struct dahdi_pvt *master;           /*!< Master to us (we follow their conferencing) */
00696    int inconference;          /*!< If our real should be in the conference */
00697 
00698    int bufsize;                /*!< Size of the buffers */
00699    int buf_no;             /*!< Number of buffers */
00700    int buf_policy;            /*!< Buffer policy */
00701    int faxbuf_no;              /*!< Number of Fax buffers */
00702    int faxbuf_policy;          /*!< Fax buffer policy */
00703    int sig;             /*!< Signalling style */
00704    /*!
00705     * \brief Nonzero if the signaling type is sent over a radio.
00706     * \note Set to a couple of nonzero values but it is only tested like a boolean.
00707     */
00708    int radio;
00709    int outsigmod;             /*!< Outbound Signalling style (modifier) */
00710    int oprmode;               /*!< "Operator Services" mode */
00711    struct dahdi_pvt *oprpeer;          /*!< "Operator Services" peer tech_pvt ptr */
00712    /*! \brief Amount of gain to increase during caller id */
00713    float cid_rxgain;
00714    /*! \brief Rx gain set by chan_dahdi.conf */
00715    float rxgain;
00716    /*! \brief Tx gain set by chan_dahdi.conf */
00717    float txgain;
00718 
00719    float txdrc; /*!< Dynamic Range Compression factor. a number between 1 and 6ish */
00720    float rxdrc;
00721    
00722    int tonezone;              /*!< tone zone for this chan, or -1 for default */
00723    enum DAHDI_IFLIST which_iflist;  /*!< Which interface list is this structure listed? */
00724    struct dahdi_pvt *next;          /*!< Next channel in list */
00725    struct dahdi_pvt *prev;          /*!< Prev channel in list */
00726 
00727    /* flags */
00728 
00729    /*!
00730     * \brief TRUE if ADSI (Analog Display Services Interface) available
00731     * \note Set from the "adsi" value read in from chan_dahdi.conf
00732     */
00733    unsigned int adsi:1;
00734    /*!
00735     * \brief TRUE if we can use a polarity reversal to mark when an outgoing
00736     * call is answered by the remote party.
00737     * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
00738     */
00739    unsigned int answeronpolarityswitch:1;
00740    /*!
00741     * \brief TRUE if busy detection is enabled.
00742     * (Listens for the beep-beep busy pattern.)
00743     * \note Set from the "busydetect" value read in from chan_dahdi.conf
00744     */
00745    unsigned int busydetect:1;
00746    /*!
00747     * \brief TRUE if call return is enabled.
00748     * (*69, if your dialplan doesn't catch this first)
00749     * \note Set from the "callreturn" value read in from chan_dahdi.conf
00750     */
00751    unsigned int callreturn:1;
00752    /*!
00753     * \brief TRUE if busy extensions will hear the call-waiting tone
00754     * and can use hook-flash to switch between callers.
00755     * \note Can be disabled by dialing *70.
00756     * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
00757     */
00758    unsigned int callwaiting:1;
00759    /*!
00760     * \brief TRUE if send caller ID for Call Waiting
00761     * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
00762     */
00763    unsigned int callwaitingcallerid:1;
00764    /*!
00765     * \brief TRUE if support for call forwarding enabled.
00766     * Dial *72 to enable call forwarding.
00767     * Dial *73 to disable call forwarding.
00768     * \note Set from the "cancallforward" value read in from chan_dahdi.conf
00769     */
00770    unsigned int cancallforward:1;
00771    /*!
00772     * \brief TRUE if support for call parking is enabled.
00773     * \note Set from the "canpark" value read in from chan_dahdi.conf
00774     */
00775    unsigned int canpark:1;
00776    /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
00777    unsigned int confirmanswer:1;
00778    /*!
00779     * \brief TRUE if the channel is to be destroyed on hangup.
00780     * (Used by pseudo channels.)
00781     */
00782    unsigned int destroy:1;
00783    unsigned int didtdd:1;           /*!< flag to say its done it once */
00784    /*! \brief TRUE if analog type line dialed no digits in Dial() */
00785    unsigned int dialednone:1;
00786    /*!
00787     * \brief TRUE if in the process of dialing digits or sending something.
00788     * \note This is used as a receive squelch for ISDN until connected.
00789     */
00790    unsigned int dialing:1;
00791    /*! \brief TRUE if the transfer capability of the call is digital. */
00792    unsigned int digital:1;
00793    /*! \brief TRUE if Do-Not-Disturb is enabled, present only for non sig_analog */
00794    unsigned int dnd:1;
00795    /*! \brief XXX BOOLEAN Purpose??? */
00796    unsigned int echobreak:1;
00797    /*!
00798     * \brief TRUE if echo cancellation enabled when bridged.
00799     * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
00800     * \note Disabled if the echo canceller is not setup.
00801     */
00802    unsigned int echocanbridged:1;
00803    /*! \brief TRUE if echo cancellation is turned on. */
00804    unsigned int echocanon:1;
00805    /*! \brief TRUE if a fax tone has already been handled. */
00806    unsigned int faxhandled:1;
00807    /*! TRUE if dynamic faxbuffers are configured for use, default is OFF */
00808    unsigned int usefaxbuffers:1;
00809    /*! TRUE while buffer configuration override is in use */
00810    unsigned int bufferoverrideinuse:1;
00811    /*! \brief TRUE if over a radio and dahdi_read() has been called. */
00812    unsigned int firstradio:1;
00813    /*!
00814     * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
00815     * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
00816     */
00817    unsigned int hanguponpolarityswitch:1;
00818    /*! \brief TRUE if DTMF detection needs to be done by hardware. */
00819    unsigned int hardwaredtmf:1;
00820    /*!
00821     * \brief TRUE if the outgoing caller ID is blocked/hidden.
00822     * \note Caller ID can be disabled by dialing *67.
00823     * \note Caller ID can be enabled by dialing *82.
00824     * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
00825     */
00826    unsigned int hidecallerid:1;
00827    /*!
00828     * \brief TRUE if hide just the name not the number for legacy PBX use.
00829     * \note Only applies to PRI channels.
00830     * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
00831     */
00832    unsigned int hidecalleridname:1;
00833    /*! \brief TRUE if DTMF detection is disabled. */
00834    unsigned int ignoredtmf:1;
00835    /*!
00836     * \brief TRUE if the channel should be answered immediately
00837     * without attempting to gather any digits.
00838     * \note Set from the "immediate" value read in from chan_dahdi.conf
00839     */
00840    unsigned int immediate:1;
00841    /*! \brief TRUE if in an alarm condition. */
00842    unsigned int inalarm:1;
00843    /*! \brief TRUE if TDD in MATE mode */
00844    unsigned int mate:1;
00845    /*! \brief TRUE if we originated the call leg. */
00846    unsigned int outgoing:1;
00847    /* unsigned int overlapdial:1;         unused and potentially confusing */
00848    /*!
00849     * \brief TRUE if busy extensions will hear the call-waiting tone
00850     * and can use hook-flash to switch between callers.
00851     * \note Set from the "callwaiting" value read in from chan_dahdi.conf
00852     */
00853    unsigned int permcallwaiting:1;
00854    /*!
00855     * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
00856     * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
00857     */
00858    unsigned int permhidecallerid:1;
00859    /*!
00860     * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
00861     * \note Set from the "priindication" value read in from chan_dahdi.conf
00862     */
00863    unsigned int priindication_oob:1;
00864    /*!
00865     * \brief TRUE if PRI B channels are always exclusively selected.
00866     * \note Set from the "priexclusive" value read in from chan_dahdi.conf
00867     */
00868    unsigned int priexclusive:1;
00869    /*!
00870     * \brief TRUE if we will pulse dial.
00871     * \note Set from the "pulsedial" value read in from chan_dahdi.conf
00872     */
00873    unsigned int pulse:1;
00874    /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
00875    unsigned int pulsedial:1;
00876    unsigned int restartpending:1;      /*!< flag to ensure counted only once for restart */
00877    /*!
00878     * \brief TRUE if caller ID is restricted.
00879     * \note Set but not used.  Should be deleted.  Redundant with permhidecallerid.
00880     * \note Set from the "restrictcid" value read in from chan_dahdi.conf
00881     */
00882    unsigned int restrictcid:1;
00883    /*!
00884     * \brief TRUE if three way calling is enabled
00885     * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
00886     */
00887    unsigned int threewaycalling:1;
00888    /*!
00889     * \brief TRUE if call transfer is enabled
00890     * \note For FXS ports (either direct analog or over T1/E1):
00891     *   Support flash-hook call transfer
00892     * \note For digital ports using ISDN PRI protocols:
00893     *   Support switch-side transfer (called 2BCT, RLT or other names)
00894     * \note Set from the "transfer" value read in from chan_dahdi.conf
00895     */
00896    unsigned int transfer:1;
00897    /*!
00898     * \brief TRUE if caller ID is used on this channel.
00899     * \note PRI and SS7 spans will save caller ID from the networking peer.
00900     * \note FXS ports will generate the caller ID spill.
00901     * \note FXO ports will listen for the caller ID spill.
00902     * \note Set from the "usecallerid" value read in from chan_dahdi.conf
00903     */
00904    unsigned int use_callerid:1;
00905    /*!
00906     * \brief TRUE if we will use the calling presentation setting
00907     * from the Asterisk channel for outgoing calls.
00908     * \note Only applies to PRI and SS7 channels.
00909     * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
00910     */
00911    unsigned int use_callingpres:1;
00912    /*!
00913     * \brief TRUE if distinctive rings are to be detected.
00914     * \note For FXO lines
00915     * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
00916     */
00917    unsigned int usedistinctiveringdetection:1;
00918    /*!
00919     * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
00920     * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
00921     */
00922    unsigned int dahditrcallerid:1;
00923    /*!
00924     * \brief TRUE if allowed to flash-transfer to busy channels.
00925     * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
00926     */
00927    unsigned int transfertobusy:1;
00928    /*!
00929     * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
00930     * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
00931     */
00932    unsigned int mwimonitor_neon:1;
00933    /*!
00934     * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
00935     * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
00936     */
00937    unsigned int mwimonitor_fsk:1;
00938    /*!
00939     * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
00940     * \note RPAS - Ring Pulse Alert Signal
00941     * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
00942     */
00943    unsigned int mwimonitor_rpas:1;
00944    /*! \brief TRUE if an MWI monitor thread is currently active */
00945    unsigned int mwimonitoractive:1;
00946    /*! \brief TRUE if a MWI message sending thread is active */
00947    unsigned int mwisendactive:1;
00948    /*!
00949     * \brief TRUE if channel is out of reset and ready
00950     * \note Set but not used.
00951     */
00952    unsigned int inservice:1;
00953    /*!
00954     * \brief TRUE if the channel is locally blocked.
00955     * \note Applies to SS7 and MFCR2 channels.
00956     */
00957    unsigned int locallyblocked:1;
00958    /*!
00959     * \brief TRUE if the channel is remotely blocked.
00960     * \note Applies to SS7 and MFCR2 channels.
00961     */
00962    unsigned int remotelyblocked:1;
00963    /*!
00964     * \brief TRUE if the channel alarms will be managed also as Span ones
00965     * \note Applies to all channels
00966     */
00967    unsigned int manages_span_alarms:1;
00968 
00969 #if defined(HAVE_PRI)
00970    struct sig_pri_span *pri;
00971    int logicalspan;
00972 #endif
00973    /*!
00974     * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
00975     * \note Set from the "usesmdi" value read in from chan_dahdi.conf
00976     */
00977    unsigned int use_smdi:1;
00978    struct mwisend_info mwisend_data;
00979    /*! \brief The SMDI interface to get SMDI messages from. */
00980    struct ast_smdi_interface *smdi_iface;
00981 
00982    /*! \brief Distinctive Ring data */
00983    struct dahdi_distRings drings;
00984 
00985    /*!
00986     * \brief The configured context for incoming calls.
00987     * \note The "context" string read in from chan_dahdi.conf
00988     */
00989    char context[AST_MAX_CONTEXT];
00990    /*!
00991     * \brief Saved context string.
00992     */
00993    char defcontext[AST_MAX_CONTEXT];
00994    /*! \brief Extension to use in the dialplan. */
00995    char exten[AST_MAX_EXTENSION];
00996    /*!
00997     * \brief Language configured for calls.
00998     * \note The "language" string read in from chan_dahdi.conf
00999     */
01000    char language[MAX_LANGUAGE];
01001    /*!
01002     * \brief The configured music-on-hold class to use for calls.
01003     * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
01004     */
01005    char mohinterpret[MAX_MUSICCLASS];
01006    /*!
01007     * \brief Suggested music-on-hold class for peer channel to use for calls.
01008     * \note The "mohsuggest" string read in from chan_dahdi.conf
01009     */
01010    char mohsuggest[MAX_MUSICCLASS];
01011    char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
01012 #if defined(HAVE_PRI) || defined(HAVE_SS7)
01013    /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
01014    char cid_ani[AST_MAX_EXTENSION];
01015 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
01016    /*! \brief Automatic Number Identification code from PRI */
01017    int cid_ani2;
01018    /*! \brief Caller ID number from an incoming call. */
01019    char cid_num[AST_MAX_EXTENSION];
01020    /*!
01021     * \brief Caller ID tag from incoming call
01022     * \note the "cid_tag" string read in from chan_dahdi.conf
01023     */
01024    char cid_tag[AST_MAX_EXTENSION];
01025    /*! \brief Caller ID Q.931 TON/NPI field values.  Set by PRI. Zero otherwise. */
01026    int cid_ton;
01027    /*! \brief Caller ID name from an incoming call. */
01028    char cid_name[AST_MAX_EXTENSION];
01029    /*! \brief Caller ID subaddress from an incoming call. */
01030    char cid_subaddr[AST_MAX_EXTENSION];
01031    char *origcid_num;            /*!< malloced original callerid */
01032    char *origcid_name;           /*!< malloced original callerid */
01033    /*! \brief Call waiting number. */
01034    char callwait_num[AST_MAX_EXTENSION];
01035    /*! \brief Call waiting name. */
01036    char callwait_name[AST_MAX_EXTENSION];
01037    /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
01038    char rdnis[AST_MAX_EXTENSION];
01039    /*! \brief Dialed Number Identifier */
01040    char dnid[AST_MAX_EXTENSION];
01041    /*!
01042     * \brief Bitmapped groups this belongs to.
01043     * \note The "group" bitmapped group string read in from chan_dahdi.conf
01044     */
01045    ast_group_t group;
01046    /*! \brief Default call PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW. */
01047    int law_default;
01048    /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
01049    int law;
01050    int confno;             /*!< Our conference */
01051    int confusers;             /*!< Who is using our conference */
01052    int propconfno;               /*!< Propagated conference number */
01053    /*!
01054     * \brief Bitmapped call groups this belongs to.
01055     * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
01056     */
01057    ast_group_t callgroup;
01058    /*!
01059     * \brief Bitmapped pickup groups this belongs to.
01060     * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
01061     */
01062    ast_group_t pickupgroup;
01063    /*!
01064     * \brief Channel variable list with associated values to set when a channel is created.
01065     * \note The "setvar" strings read in from chan_dahdi.conf
01066     */
01067    struct ast_variable *vars;
01068    int channel;               /*!< Channel Number */
01069    int span;               /*!< Span number */
01070    time_t guardtime;          /*!< Must wait this much time before using for new call */
01071    int cid_signalling;           /*!< CID signalling type bell202 or v23 */
01072    int cid_start;             /*!< CID start indicator, polarity or ring or DTMF without warning event */
01073    int dtmfcid_holdoff_state;    /*!< State indicator that allows for line to settle before checking for dtmf energy */
01074    struct timeval dtmfcid_delay;  /*!< Time value used for allow line to settle */
01075    int callingpres;           /*!< The value of calling presentation that we're going to use when placing a PRI call */
01076    int callwaitingrepeat;           /*!< How many samples to wait before repeating call waiting */
01077    int cidcwexpire;           /*!< When to stop waiting for CID/CW CAS response (In samples) */
01078    int cid_suppress_expire;      /*!< How many samples to suppress after a CID spill. */
01079    /*! \brief Analog caller ID waveform sample buffer */
01080    unsigned char *cidspill;
01081    /*! \brief Position in the cidspill buffer to send out next. */
01082    int cidpos;
01083    /*! \brief Length of the cidspill buffer containing samples. */
01084    int cidlen;
01085    /*! \brief Ring timeout timer?? */
01086    int ringt;
01087    /*!
01088     * \brief Ring timeout base.
01089     * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
01090     */
01091    int ringt_base;
01092    /*!
01093     * \brief Number of most significant digits/characters to strip from the dialed number.
01094     * \note Feature is deprecated.  Use dialplan logic.
01095     * \note The characters are stripped before the PRI TON/NPI prefix
01096     * characters are processed.
01097     */
01098    int stripmsd;
01099    /*!
01100     * \brief TRUE if Call Waiting (CW) CPE Alert Signal (CAS) is being sent.
01101     * \note
01102     * After CAS is sent, the call waiting caller id will be sent if the phone
01103     * gives a positive reply.
01104     */
01105    int callwaitcas;
01106    /*! \brief Number of call waiting rings. */
01107    int callwaitrings;
01108    /*! \brief Echo cancel parameters. */
01109    struct {
01110       struct dahdi_echocanparams head;
01111       struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
01112    } echocancel;
01113    /*!
01114     * \brief Echo training time. 0 = disabled
01115     * \note Set from the "echotraining" value read in from chan_dahdi.conf
01116     */
01117    int echotraining;
01118    /*! \brief Filled with 'w'.  XXX Purpose?? */
01119    char echorest[20];
01120    /*!
01121     * \brief Number of times to see "busy" tone before hanging up.
01122     * \note Set from the "busycount" value read in from chan_dahdi.conf
01123     */
01124    int busycount;
01125    /*!
01126     * \brief Length of "busy" tone on time.
01127     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01128     */
01129    int busy_tonelength;
01130    /*!
01131     * \brief Length of "busy" tone off time.
01132     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01133     */
01134    int busy_quietlength;
01135    /*!
01136     * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
01137     * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
01138     */
01139    int callprogress;
01140    /*!
01141     * \brief Number of milliseconds to wait for dialtone.
01142     * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
01143     */
01144    int waitfordialtone;
01145    struct timeval waitingfordt;        /*!< Time we started waiting for dialtone */
01146    struct timeval flashtime;        /*!< Last flash-hook time */
01147    /*! \brief Opaque DSP configuration structure. */
01148    struct ast_dsp *dsp;
01149    /*! \brief DAHDI dial operation command struct for ioctl() call. */
01150    struct dahdi_dialoperation dop;
01151    int whichwink;             /*!< SIG_FEATDMF_TA Which wink are we on? */
01152    /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
01153    char finaldial[64];
01154    char accountcode[AST_MAX_ACCOUNT_CODE];      /*!< Account code */
01155    int amaflags;              /*!< AMA Flags */
01156    struct tdd_state *tdd;           /*!< TDD flag */
01157    /*! \brief Accumulated call forwarding number. */
01158    char call_forward[AST_MAX_EXTENSION];
01159    /*!
01160     * \brief Voice mailbox location.
01161     * \note Set from the "mailbox" string read in from chan_dahdi.conf
01162     */
01163    char mailbox[AST_MAX_EXTENSION];
01164    /*! \brief Opaque event subscription parameters for message waiting indication support. */
01165    struct ast_event_sub *mwi_event_sub;
01166    /*! \brief Delayed dialing for E911.  Overlap digits for ISDN. */
01167    char dialdest[256];
01168 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01169    struct dahdi_vmwi_info mwisend_setting;            /*!< Which VMWI methods to use */
01170    unsigned int mwisend_fsk: 1;     /*! Variable for enabling FSK MWI handling in chan_dahdi */
01171    unsigned int mwisend_rpas:1;     /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
01172 #endif
01173    int distinctivering;          /*!< Which distinctivering to use */
01174    int dtmfrelax;             /*!< whether to run in relaxed DTMF mode */
01175    /*! \brief Holding place for event injected from outside normal operation. */
01176    int fake_event;
01177    /*!
01178     * \brief Minimal time period (ms) between the answer polarity
01179     * switch and hangup polarity switch.
01180     */
01181    int polarityonanswerdelay;
01182    /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
01183    struct timeval polaritydelaytv;
01184    /*!
01185     * \brief Send caller ID on FXS after this many rings. Set to 1 for US.
01186     * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
01187     */
01188    int sendcalleridafter;
01189    /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
01190    int polarity;
01191    /*! \brief DSP feature flags: DSP_FEATURE_xxx */
01192    int dsp_features;
01193 #if defined(HAVE_SS7)
01194    /*! \brief SS7 control parameters */
01195    struct sig_ss7_linkset *ss7;
01196 #endif   /* defined(HAVE_SS7) */
01197 #ifdef HAVE_OPENR2
01198    struct dahdi_mfcr2 *mfcr2;
01199    openr2_chan_t *r2chan;
01200    openr2_calling_party_category_t mfcr2_recvd_category;
01201    openr2_calling_party_category_t mfcr2_category;
01202    int mfcr2_dnis_index;
01203    int mfcr2_ani_index;
01204    int mfcr2call:1;
01205    int mfcr2_answer_pending:1;
01206    int mfcr2_charge_calls:1;
01207    int mfcr2_allow_collect_calls:1;
01208    int mfcr2_forced_release:1;
01209    int mfcr2_dnis_matched:1;
01210    int mfcr2_call_accepted:1;
01211    int mfcr2_progress:1;
01212    int mfcr2_accept_on_offer:1;
01213 #endif
01214    /*! \brief DTMF digit in progress.  0 when no digit in progress. */
01215    char begindigit;
01216    /*! \brief TRUE if confrence is muted. */
01217    int muting;
01218    void *sig_pvt;
01219    struct ast_cc_config_params *cc_params;
01220    /* DAHDI channel names may differ greatly from the
01221     * string that was provided to an app such as Dial. We
01222     * need to save the original string passed to dahdi_request
01223     * for call completion purposes. This way, we can replicate
01224     * the original dialed string later.
01225     */
01226    char dialstring[AST_CHANNEL_NAME];
01227 };
01228 
01229 #define DATA_EXPORT_DAHDI_PVT(MEMBER)              \
01230    MEMBER(dahdi_pvt, cid_rxgain, AST_DATA_DOUBLE)        \
01231    MEMBER(dahdi_pvt, rxgain, AST_DATA_DOUBLE)         \
01232    MEMBER(dahdi_pvt, txgain, AST_DATA_DOUBLE)         \
01233    MEMBER(dahdi_pvt, txdrc, AST_DATA_DOUBLE)       \
01234    MEMBER(dahdi_pvt, rxdrc, AST_DATA_DOUBLE)       \
01235    MEMBER(dahdi_pvt, adsi, AST_DATA_BOOLEAN)       \
01236    MEMBER(dahdi_pvt, answeronpolarityswitch, AST_DATA_BOOLEAN) \
01237    MEMBER(dahdi_pvt, busydetect, AST_DATA_BOOLEAN)       \
01238    MEMBER(dahdi_pvt, callreturn, AST_DATA_BOOLEAN)       \
01239    MEMBER(dahdi_pvt, callwaiting, AST_DATA_BOOLEAN)      \
01240    MEMBER(dahdi_pvt, callwaitingcallerid, AST_DATA_BOOLEAN) \
01241    MEMBER(dahdi_pvt, cancallforward, AST_DATA_BOOLEAN)      \
01242    MEMBER(dahdi_pvt, canpark, AST_DATA_BOOLEAN)       \
01243    MEMBER(dahdi_pvt, confirmanswer, AST_DATA_BOOLEAN)    \
01244    MEMBER(dahdi_pvt, destroy, AST_DATA_BOOLEAN)       \
01245    MEMBER(dahdi_pvt, didtdd, AST_DATA_BOOLEAN)        \
01246    MEMBER(dahdi_pvt, dialednone, AST_DATA_BOOLEAN)       \
01247    MEMBER(dahdi_pvt, dialing, AST_DATA_BOOLEAN)       \
01248    MEMBER(dahdi_pvt, digital, AST_DATA_BOOLEAN)       \
01249    MEMBER(dahdi_pvt, dnd, AST_DATA_BOOLEAN)        \
01250    MEMBER(dahdi_pvt, echobreak, AST_DATA_BOOLEAN)        \
01251    MEMBER(dahdi_pvt, echocanbridged, AST_DATA_BOOLEAN)      \
01252    MEMBER(dahdi_pvt, echocanon, AST_DATA_BOOLEAN)        \
01253    MEMBER(dahdi_pvt, faxhandled, AST_DATA_BOOLEAN)       \
01254    MEMBER(dahdi_pvt, usefaxbuffers, AST_DATA_BOOLEAN)    \
01255    MEMBER(dahdi_pvt, bufferoverrideinuse, AST_DATA_BOOLEAN) \
01256    MEMBER(dahdi_pvt, firstradio, AST_DATA_BOOLEAN)       \
01257    MEMBER(dahdi_pvt, hanguponpolarityswitch, AST_DATA_BOOLEAN) \
01258    MEMBER(dahdi_pvt, hardwaredtmf, AST_DATA_BOOLEAN)     \
01259    MEMBER(dahdi_pvt, hidecallerid, AST_DATA_BOOLEAN)     \
01260    MEMBER(dahdi_pvt, hidecalleridname, AST_DATA_BOOLEAN)    \
01261    MEMBER(dahdi_pvt, ignoredtmf, AST_DATA_BOOLEAN)       \
01262    MEMBER(dahdi_pvt, immediate, AST_DATA_BOOLEAN)        \
01263    MEMBER(dahdi_pvt, inalarm, AST_DATA_BOOLEAN)       \
01264    MEMBER(dahdi_pvt, mate, AST_DATA_BOOLEAN)       \
01265    MEMBER(dahdi_pvt, outgoing, AST_DATA_BOOLEAN)         \
01266    MEMBER(dahdi_pvt, permcallwaiting, AST_DATA_BOOLEAN)     \
01267    MEMBER(dahdi_pvt, priindication_oob, AST_DATA_BOOLEAN)      \
01268    MEMBER(dahdi_pvt, priexclusive, AST_DATA_BOOLEAN)     \
01269    MEMBER(dahdi_pvt, pulse, AST_DATA_BOOLEAN)         \
01270    MEMBER(dahdi_pvt, pulsedial, AST_DATA_BOOLEAN)        \
01271    MEMBER(dahdi_pvt, restartpending, AST_DATA_BOOLEAN)      \
01272    MEMBER(dahdi_pvt, restrictcid, AST_DATA_BOOLEAN)      \
01273    MEMBER(dahdi_pvt, threewaycalling, AST_DATA_BOOLEAN)     \
01274    MEMBER(dahdi_pvt, transfer, AST_DATA_BOOLEAN)         \
01275    MEMBER(dahdi_pvt, use_callerid, AST_DATA_BOOLEAN)     \
01276    MEMBER(dahdi_pvt, use_callingpres, AST_DATA_BOOLEAN)     \
01277    MEMBER(dahdi_pvt, usedistinctiveringdetection, AST_DATA_BOOLEAN)  \
01278    MEMBER(dahdi_pvt, dahditrcallerid, AST_DATA_BOOLEAN)        \
01279    MEMBER(dahdi_pvt, transfertobusy, AST_DATA_BOOLEAN)         \
01280    MEMBER(dahdi_pvt, mwimonitor_neon, AST_DATA_BOOLEAN)        \
01281    MEMBER(dahdi_pvt, mwimonitor_fsk, AST_DATA_BOOLEAN)         \
01282    MEMBER(dahdi_pvt, mwimonitor_rpas, AST_DATA_BOOLEAN)        \
01283    MEMBER(dahdi_pvt, mwimonitoractive, AST_DATA_BOOLEAN)       \
01284    MEMBER(dahdi_pvt, mwisendactive, AST_DATA_BOOLEAN)       \
01285    MEMBER(dahdi_pvt, inservice, AST_DATA_BOOLEAN)           \
01286    MEMBER(dahdi_pvt, locallyblocked, AST_DATA_BOOLEAN)         \
01287    MEMBER(dahdi_pvt, remotelyblocked, AST_DATA_BOOLEAN)        \
01288    MEMBER(dahdi_pvt, manages_span_alarms, AST_DATA_BOOLEAN)    \
01289    MEMBER(dahdi_pvt, use_smdi, AST_DATA_BOOLEAN)            \
01290    MEMBER(dahdi_pvt, context, AST_DATA_STRING)           \
01291    MEMBER(dahdi_pvt, defcontext, AST_DATA_STRING)           \
01292    MEMBER(dahdi_pvt, exten, AST_DATA_STRING)          \
01293    MEMBER(dahdi_pvt, language, AST_DATA_STRING)          \
01294    MEMBER(dahdi_pvt, mohinterpret, AST_DATA_STRING)         \
01295    MEMBER(dahdi_pvt, mohsuggest, AST_DATA_STRING)           \
01296    MEMBER(dahdi_pvt, parkinglot, AST_DATA_STRING)
01297 
01298 AST_DATA_STRUCTURE(dahdi_pvt, DATA_EXPORT_DAHDI_PVT);
01299 
01300 static struct dahdi_pvt *iflist = NULL;   /*!< Main interface list start */
01301 static struct dahdi_pvt *ifend = NULL; /*!< Main interface list end */
01302 
01303 #if defined(HAVE_PRI)
01304 static struct dahdi_parms_pseudo {
01305    int buf_no;             /*!< Number of buffers */
01306    int buf_policy;            /*!< Buffer policy */
01307    int faxbuf_no;              /*!< Number of Fax buffers */
01308    int faxbuf_policy;          /*!< Fax buffer policy */
01309 } dahdi_pseudo_parms;
01310 #endif   /* defined(HAVE_PRI) */
01311 
01312 /*! \brief Channel configuration from chan_dahdi.conf .
01313  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
01314  * Generally there is a field here for every possible configuration item.
01315  *
01316  * The state of fields is saved along the parsing and whenever a 'channel'
01317  * statement is reached, the current dahdi_chan_conf is used to configure the
01318  * channel (struct dahdi_pvt)
01319  *
01320  * \see dahdi_chan_init for the default values.
01321  */
01322 struct dahdi_chan_conf {
01323    struct dahdi_pvt chan;
01324 #ifdef HAVE_PRI
01325    struct dahdi_pri pri;
01326 #endif
01327 
01328 #if defined(HAVE_SS7)
01329    struct dahdi_ss7 ss7;
01330 #endif   /* defined(HAVE_SS7) */
01331 
01332 #ifdef HAVE_OPENR2
01333    struct dahdi_mfcr2_conf mfcr2;
01334 #endif
01335    struct dahdi_params timing;
01336    int is_sig_auto; /*!< Use channel signalling from DAHDI? */
01337    /*! Continue configuration even if a channel is not there. */
01338    int ignore_failed_channels;
01339 
01340    /*!
01341     * \brief The serial port to listen for SMDI data on
01342     * \note Set from the "smdiport" string read in from chan_dahdi.conf
01343     */
01344    char smdi_port[SMDI_MAX_FILENAME_LEN];
01345 };
01346 
01347 /*! returns a new dahdi_chan_conf with default values (by-value) */
01348 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
01349 {
01350    /* recall that if a field is not included here it is initialized
01351     * to 0 or equivalent
01352     */
01353    struct dahdi_chan_conf conf = {
01354 #ifdef HAVE_PRI
01355       .pri.pri = {
01356          .nsf = PRI_NSF_NONE,
01357          .switchtype = PRI_SWITCH_NI2,
01358          .dialplan = PRI_UNKNOWN + 1,
01359          .localdialplan = PRI_NATIONAL_ISDN + 1,
01360          .nodetype = PRI_CPE,
01361          .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
01362 
01363 #if defined(HAVE_PRI_CCSS)
01364          .cc_ptmp_recall_mode = 1,/* specificRecall */
01365          .cc_qsig_signaling_link_req = 1,/* retain */
01366          .cc_qsig_signaling_link_rsp = 1,/* retain */
01367 #endif   /* defined(HAVE_PRI_CCSS) */
01368 
01369          .minunused = 2,
01370          .idleext = "",
01371          .idledial = "",
01372          .internationalprefix = "",
01373          .nationalprefix = "",
01374          .localprefix = "",
01375          .privateprefix = "",
01376          .unknownprefix = "",
01377          .resetinterval = -1,
01378       },
01379 #endif
01380 #if defined(HAVE_SS7)
01381       .ss7.ss7 = {
01382          .called_nai = SS7_NAI_NATIONAL,
01383          .calling_nai = SS7_NAI_NATIONAL,
01384          .internationalprefix = "",
01385          .nationalprefix = "",
01386          .subscriberprefix = "",
01387          .unknownprefix = ""
01388       },
01389 #endif   /* defined(HAVE_SS7) */
01390 #ifdef HAVE_OPENR2
01391       .mfcr2 = {
01392          .variant = OR2_VAR_ITU,
01393          .mfback_timeout = -1,
01394          .metering_pulse_timeout = -1,
01395          .max_ani = 10,
01396          .max_dnis = 4,
01397          .get_ani_first = -1,
01398 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
01399          .skip_category_request = -1,
01400 #endif
01401          .call_files = 0,
01402          .allow_collect_calls = 0,
01403          .charge_calls = 1,
01404          .accept_on_offer = 1,
01405          .forced_release = 0,
01406          .double_answer = 0,
01407          .immediate_accept = -1,
01408          .logdir = "",
01409          .r2proto_file = "",
01410          .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
01411          .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
01412       },
01413 #endif
01414       .chan = {
01415          .context = "default",
01416          .cid_num = "",
01417          .cid_name = "",
01418          .cid_tag = "",
01419          .mohinterpret = "default",
01420          .mohsuggest = "",
01421          .parkinglot = "",
01422          .transfertobusy = 1,
01423 
01424          .cid_signalling = CID_SIG_BELL,
01425          .cid_start = CID_START_RING,
01426          .dahditrcallerid = 0,
01427          .use_callerid = 1,
01428          .sig = -1,
01429          .outsigmod = -1,
01430 
01431          .cid_rxgain = +5.0,
01432 
01433          .tonezone = -1,
01434 
01435          .echocancel.head.tap_length = 1,
01436 
01437          .busycount = 3,
01438 
01439          .accountcode = "",
01440 
01441          .mailbox = "",
01442 
01443 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01444          .mwisend_fsk = 1,
01445 #endif
01446          .polarityonanswerdelay = 600,
01447 
01448          .sendcalleridafter = DEFAULT_CIDRINGS,
01449 
01450          .buf_policy = DAHDI_POLICY_IMMEDIATE,
01451          .buf_no = numbufs,
01452          .usefaxbuffers = 0,
01453          .cc_params = ast_cc_config_params_init(),
01454       },
01455       .timing = {
01456          .prewinktime = -1,
01457          .preflashtime = -1,
01458          .winktime = -1,
01459          .flashtime = -1,
01460          .starttime = -1,
01461          .rxwinktime = -1,
01462          .rxflashtime = -1,
01463          .debouncetime = -1
01464       },
01465       .is_sig_auto = 1,
01466       .smdi_port = "/dev/ttyS0",
01467    };
01468 
01469    return conf;
01470 }
01471 
01472 
01473 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01474 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
01475 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
01476 static int dahdi_sendtext(struct ast_channel *c, const char *text);
01477 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
01478 static int dahdi_hangup(struct ast_channel *ast);
01479 static int dahdi_answer(struct ast_channel *ast);
01480 static struct ast_frame *dahdi_read(struct ast_channel *ast);
01481 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
01482 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
01483 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
01484 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01485 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01486 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01487 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
01488 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value);
01489 static int dahdi_devicestate(void *data);
01490 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback);
01491 
01492 static const struct ast_channel_tech dahdi_tech = {
01493    .type = "DAHDI",
01494    .description = tdesc,
01495    .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
01496    .requester = dahdi_request,
01497    .send_digit_begin = dahdi_digit_begin,
01498    .send_digit_end = dahdi_digit_end,
01499    .send_text = dahdi_sendtext,
01500    .call = dahdi_call,
01501    .hangup = dahdi_hangup,
01502    .answer = dahdi_answer,
01503    .read = dahdi_read,
01504    .write = dahdi_write,
01505    .bridge = dahdi_bridge,
01506    .exception = dahdi_exception,
01507    .indicate = dahdi_indicate,
01508    .fixup = dahdi_fixup,
01509    .setoption = dahdi_setoption,
01510    .queryoption = dahdi_queryoption,
01511    .func_channel_read = dahdi_func_read,
01512    .func_channel_write = dahdi_func_write,
01513    .devicestate = dahdi_devicestate,
01514    .cc_callback = dahdi_cc_callback,
01515 };
01516 
01517 #define GET_CHANNEL(p) ((p)->channel)
01518 
01519 #define SIG_PRI_LIB_HANDLE_CASES \
01520    SIG_PRI:                \
01521    case SIG_BRI:              \
01522    case SIG_BRI_PTMP
01523 
01524 /*!
01525  * \internal
01526  * \brief Determine if sig_pri handles the signaling.
01527  * \since 1.8
01528  *
01529  * \param signaling Signaling to determine if is for sig_pri.
01530  *
01531  * \return TRUE if the signaling is for sig_pri.
01532  */
01533 static inline int dahdi_sig_pri_lib_handles(int signaling)
01534 {
01535    int handles;
01536 
01537    switch (signaling) {
01538    case SIG_PRI_LIB_HANDLE_CASES:
01539       handles = 1;
01540       break;
01541    default:
01542       handles = 0;
01543       break;
01544    }
01545 
01546    return handles;
01547 }
01548 
01549 static enum analog_sigtype dahdisig_to_analogsig(int sig)
01550 {
01551    switch (sig) {
01552    case SIG_FXOLS:
01553       return ANALOG_SIG_FXOLS;
01554    case SIG_FXOGS:
01555       return ANALOG_SIG_FXOGS;
01556    case SIG_FXOKS:
01557       return ANALOG_SIG_FXOKS;
01558    case SIG_FXSLS:
01559       return ANALOG_SIG_FXSLS;
01560    case SIG_FXSGS:
01561       return ANALOG_SIG_FXSGS;
01562    case SIG_FXSKS:
01563       return ANALOG_SIG_FXSKS;
01564    case SIG_EMWINK:
01565       return ANALOG_SIG_EMWINK;
01566    case SIG_EM:
01567       return ANALOG_SIG_EM;
01568    case SIG_EM_E1:
01569       return ANALOG_SIG_EM_E1;
01570    case SIG_FEATD:
01571       return ANALOG_SIG_FEATD;
01572    case SIG_FEATDMF:
01573       return ANALOG_SIG_FEATDMF;
01574    case SIG_E911:
01575       return SIG_E911;
01576    case SIG_FGC_CAMA:
01577       return ANALOG_SIG_FGC_CAMA;
01578    case SIG_FGC_CAMAMF:
01579       return ANALOG_SIG_FGC_CAMAMF;
01580    case SIG_FEATB:
01581       return ANALOG_SIG_FEATB;
01582    case SIG_SFWINK:
01583       return ANALOG_SIG_SFWINK;
01584    case SIG_SF:
01585       return ANALOG_SIG_SF;
01586    case SIG_SF_FEATD:
01587       return ANALOG_SIG_SF_FEATD;
01588    case SIG_SF_FEATDMF:
01589       return ANALOG_SIG_SF_FEATDMF;
01590    case SIG_FEATDMF_TA:
01591       return ANALOG_SIG_FEATDMF_TA;
01592    case SIG_SF_FEATB:
01593       return ANALOG_SIG_FEATB;
01594    default:
01595       return -1;
01596    }
01597 }
01598 
01599 
01600 static int analog_tone_to_dahditone(enum analog_tone tone)
01601 {
01602    switch (tone) {
01603    case ANALOG_TONE_RINGTONE:
01604       return DAHDI_TONE_RINGTONE;
01605    case ANALOG_TONE_STUTTER:
01606       return DAHDI_TONE_STUTTER;
01607    case ANALOG_TONE_CONGESTION:
01608       return DAHDI_TONE_CONGESTION;
01609    case ANALOG_TONE_DIALTONE:
01610       return DAHDI_TONE_DIALTONE;
01611    case ANALOG_TONE_DIALRECALL:
01612       return DAHDI_TONE_DIALRECALL;
01613    case ANALOG_TONE_INFO:
01614       return DAHDI_TONE_INFO;
01615    default:
01616       return -1;
01617    }
01618 }
01619 
01620 static int analogsub_to_dahdisub(enum analog_sub analogsub)
01621 {
01622    int index;
01623 
01624    switch (analogsub) {
01625    case ANALOG_SUB_REAL:
01626       index = SUB_REAL;
01627       break;
01628    case ANALOG_SUB_CALLWAIT:
01629       index = SUB_CALLWAIT;
01630       break;
01631    case ANALOG_SUB_THREEWAY:
01632       index = SUB_THREEWAY;
01633       break;
01634    default:
01635       ast_log(LOG_ERROR, "Unidentified sub!\n");
01636       index = SUB_REAL;
01637    }
01638 
01639    return index;
01640 }
01641 
01642 static enum analog_event dahdievent_to_analogevent(int event);
01643 static int bump_gains(struct dahdi_pvt *p);
01644 static int dahdi_setlinear(int dfd, int linear);
01645 
01646 static int my_start_cid_detect(void *pvt, int cid_signalling)
01647 {
01648    struct dahdi_pvt *p = pvt;
01649    int index = SUB_REAL;
01650    p->cs = callerid_new(cid_signalling);
01651    if (!p->cs) {
01652       ast_log(LOG_ERROR, "Unable to alloc callerid\n");
01653       return -1;
01654    }
01655    bump_gains(p);
01656    dahdi_setlinear(p->subs[index].dfd, 0);
01657 
01658    return 0;
01659 }
01660 
01661 static int my_stop_cid_detect(void *pvt)
01662 {
01663    struct dahdi_pvt *p = pvt;
01664    int index = SUB_REAL;
01665    if (p->cs)
01666       callerid_free(p->cs);
01667    dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
01668    return 0;
01669 }
01670 
01671 static int my_get_callerid(void *pvt, char *namebuf, char *numbuf, enum analog_event *ev, size_t timeout)
01672 {
01673    struct dahdi_pvt *p = pvt;
01674    struct analog_pvt *analog_p = p->sig_pvt;
01675    struct pollfd poller;
01676    char *name, *num;
01677    int index = SUB_REAL;
01678    int res;
01679    unsigned char buf[256];
01680    int flags;
01681 
01682    poller.fd = p->subs[SUB_REAL].dfd;
01683    poller.events = POLLPRI | POLLIN;
01684    poller.revents = 0;
01685 
01686    res = poll(&poller, 1, timeout);
01687 
01688    if (poller.revents & POLLPRI) {
01689       *ev = dahdievent_to_analogevent(dahdi_get_event(p->subs[SUB_REAL].dfd));
01690       return 1;
01691    }
01692 
01693    if (poller.revents & POLLIN) {
01694       /*** NOTES ***/
01695       /* Change API: remove cid_signalling from get_callerid, add a new start_cid_detect and stop_cid_detect function
01696        * to enable slin mode and allocate cid detector. get_callerid should be able to be called any number of times until
01697        * either a timeout occurs or CID is detected (returns 0). returning 1 should be event received, and -1 should be
01698        * a failure and die, and returning 2 means no event was received. */
01699       res = read(p->subs[index].dfd, buf, sizeof(buf));
01700       if (res < 0) {
01701          if (errno != ELAST) {
01702             ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
01703             callerid_free(p->cs);
01704             return -1;
01705          }
01706       }
01707 
01708       if (analog_p->ringt > 0) {
01709          if (!(--analog_p->ringt)) {
01710             /* only return if we timeout from a ring event */
01711             return -1;
01712          }
01713       }
01714 
01715       if (p->cid_signalling == CID_SIG_V23_JP) {
01716          res = callerid_feed_jp(p->cs, buf, res, AST_LAW(p));
01717       } else {
01718          res = callerid_feed(p->cs, buf, res, AST_LAW(p));
01719       }
01720       if (res < 0) {
01721          /*
01722           * The previous diagnostic message output likely
01723           * explains why it failed.
01724           */
01725          ast_log(LOG_WARNING, "Failed to decode CallerID\n");
01726          return -1;
01727       }
01728 
01729       if (res == 1) {
01730          callerid_get(p->cs, &name, &num, &flags);
01731          if (name)
01732             ast_copy_string(namebuf, name, ANALOG_MAX_CID);
01733          if (num)
01734             ast_copy_string(numbuf, num, ANALOG_MAX_CID);
01735 
01736          ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", num, name, flags);
01737          return 0;
01738       }
01739    }
01740 
01741    *ev = ANALOG_EVENT_NONE;
01742    return 2;
01743 }
01744 
01745 static const char *event2str(int event);
01746 static int restore_gains(struct dahdi_pvt *p);
01747 
01748 static int my_distinctive_ring(struct ast_channel *chan, void *pvt, int idx, int *ringdata)
01749 {
01750    unsigned char buf[256];
01751    int distMatches;
01752    int curRingData[RING_PATTERNS];
01753    int receivedRingT;
01754    int counter1;
01755    int counter;
01756    int i;
01757    int res;
01758    int checkaftercid = 0;
01759 
01760    struct dahdi_pvt *p = pvt;
01761    struct analog_pvt *analog_p = p->sig_pvt;
01762 
01763    if (ringdata == NULL) {
01764       ringdata = curRingData;
01765    } else {
01766       checkaftercid = 1;
01767    }
01768 
01769    /* We must have a ring by now, so, if configured, lets try to listen for
01770     * distinctive ringing */
01771    if ((checkaftercid && distinctiveringaftercid) || !checkaftercid) {
01772       /* Clear the current ring data array so we don't have old data in it. */
01773       for (receivedRingT = 0; receivedRingT < RING_PATTERNS; receivedRingT++)
01774          ringdata[receivedRingT] = 0;
01775       receivedRingT = 0;
01776       if (checkaftercid && distinctiveringaftercid)
01777          ast_verb(3, "Detecting post-CID distinctive ring\n");
01778       /* Check to see if context is what it should be, if not set to be. */
01779       else if (strcmp(p->context,p->defcontext) != 0) {
01780          ast_copy_string(p->context, p->defcontext, sizeof(p->context));
01781          ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
01782       }
01783 
01784       for (;;) {
01785          i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
01786          if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
01787             ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
01788             ast_hangup(chan);
01789             return 1;
01790          }
01791          if (i & DAHDI_IOMUX_SIGEVENT) {
01792             res = dahdi_get_event(p->subs[idx].dfd);
01793             if (res == DAHDI_EVENT_NOALARM) {
01794                p->inalarm = 0;
01795                analog_p->inalarm = 0;
01796             }
01797             ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
01798             res = 0;
01799             /* Let us detect distinctive ring */
01800 
01801             ringdata[receivedRingT] = analog_p->ringt;
01802 
01803             if (analog_p->ringt < analog_p->ringt_base/2)
01804                break;
01805             /* Increment the ringT counter so we can match it against
01806                values in chan_dahdi.conf for distinctive ring */
01807             if (++receivedRingT == RING_PATTERNS)
01808                break;
01809          } else if (i & DAHDI_IOMUX_READ) {
01810             res = read(p->subs[idx].dfd, buf, sizeof(buf));
01811             if (res < 0) {
01812                if (errno != ELAST) {
01813                   ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
01814                   ast_hangup(chan);
01815                   return 1;
01816                }
01817                break;
01818             }
01819             if (analog_p->ringt > 0) {
01820                if (!(--analog_p->ringt)) {
01821                   res = -1;
01822                   break;
01823                }
01824             }
01825          }
01826       }
01827    }
01828    if ((checkaftercid && usedistinctiveringdetection) || !checkaftercid) {
01829       /* this only shows up if you have n of the dring patterns filled in */
01830       ast_verb(3, "Detected ring pattern: %d,%d,%d\n",ringdata[0],ringdata[1],ringdata[2]);
01831       for (counter = 0; counter < 3; counter++) {
01832       /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this channel */
01833          distMatches = 0;
01834          /* this only shows up if you have n of the dring patterns filled in */
01835          ast_verb(3, "Checking %d,%d,%d\n",
01836                p->drings.ringnum[counter].ring[0],
01837                p->drings.ringnum[counter].ring[1],
01838                p->drings.ringnum[counter].ring[2]);
01839          for (counter1 = 0; counter1 < 3; counter1++) {
01840             ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
01841             if (p->drings.ringnum[counter].ring[counter1] == -1) {
01842                ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
01843                ringdata[counter1]);
01844                distMatches++;
01845             } else if (ringdata[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
01846                               ringdata[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
01847                ast_verb(3, "Ring pattern matched in range: %d to %d\n",
01848                (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
01849                (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
01850                distMatches++;
01851             }
01852          }
01853 
01854          if (distMatches == 3) {
01855             /* The ring matches, set the context to whatever is for distinctive ring.. */
01856             ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
01857             ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
01858             ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
01859             break;
01860          }
01861       }
01862    }
01863    /* Restore linear mode (if appropriate) for Caller*ID processing */
01864    dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
01865    restore_gains(p);
01866 
01867    return 0;
01868 }
01869 
01870 static int my_stop_callwait(void *pvt)
01871 {
01872    struct dahdi_pvt *p = pvt;
01873    p->callwaitingrepeat = 0;
01874    p->cidcwexpire = 0;
01875    p->cid_suppress_expire = 0;
01876 
01877    return 0;
01878 }
01879 
01880 static int send_callerid(struct dahdi_pvt *p);
01881 static int save_conference(struct dahdi_pvt *p);
01882 static int restore_conference(struct dahdi_pvt *p);
01883 
01884 static int my_callwait(void *pvt)
01885 {
01886    struct dahdi_pvt *p = pvt;
01887    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
01888    if (p->cidspill) {
01889       ast_log(LOG_WARNING, "Spill already exists?!?\n");
01890       ast_free(p->cidspill);
01891    }
01892 
01893    /*
01894     * SAS: Subscriber Alert Signal, 440Hz for 300ms
01895     * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
01896     */
01897    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
01898       return -1;
01899    save_conference(p);
01900    /* Silence */
01901    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
01902    if (!p->callwaitrings && p->callwaitingcallerid) {
01903       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
01904       p->callwaitcas = 1;
01905       p->cidlen = 2400 + 680 + READ_SIZE * 4;
01906    } else {
01907       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
01908       p->callwaitcas = 0;
01909       p->cidlen = 2400 + READ_SIZE * 4;
01910    }
01911    p->cidpos = 0;
01912    send_callerid(p);
01913 
01914    return 0;
01915 }
01916 
01917 static int my_send_callerid(void *pvt, int cwcid, struct ast_party_caller *caller)
01918 {
01919    struct dahdi_pvt *p = pvt;
01920 
01921    ast_debug(2, "Starting cid spill\n");
01922 
01923    if (p->cidspill) {
01924       ast_log(LOG_WARNING, "cidspill already exists??\n");
01925       ast_free(p->cidspill);
01926    }
01927 
01928    if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
01929       if (cwcid == 0) {
01930          p->cidlen = ast_callerid_generate(p->cidspill,
01931             caller->id.name.str,
01932             caller->id.number.str,
01933             AST_LAW(p));
01934       } else {
01935          ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n",
01936             caller->id.name.str, caller->id.number.str);
01937          p->callwaitcas = 0;
01938          p->cidcwexpire = 0;
01939          p->cidlen = ast_callerid_callwaiting_generate(p->cidspill,
01940             caller->id.name.str,
01941             caller->id.number.str,
01942             AST_LAW(p));
01943          p->cidlen += READ_SIZE * 4;
01944       }
01945       p->cidpos = 0;
01946       p->cid_suppress_expire = 0;
01947       send_callerid(p);
01948    }
01949    return 0;
01950 }
01951 
01952 static int my_dsp_reset_and_flush_digits(void *pvt)
01953 {
01954    struct dahdi_pvt *p = pvt;
01955    if (p->dsp)
01956       ast_dsp_digitreset(p->dsp);
01957 
01958    return 0;
01959 }
01960 
01961 static int my_dsp_set_digitmode(void *pvt, enum analog_dsp_digitmode mode)
01962 {
01963    struct dahdi_pvt *p = pvt;
01964 
01965    if (p->channel == CHAN_PSEUDO)
01966       ast_log(LOG_ERROR, "You have assumed incorrectly sir!\n");
01967 
01968    if (mode == ANALOG_DIGITMODE_DTMF) {
01969       /* If we do hardware dtmf, no need for a DSP */
01970       if (p->hardwaredtmf) {
01971          if (p->dsp) {
01972             ast_dsp_free(p->dsp);
01973             p->dsp = NULL;
01974          }
01975          return 0;
01976       }
01977 
01978       if (!p->dsp) {
01979          p->dsp = ast_dsp_new();
01980          if (!p->dsp) {
01981             ast_log(LOG_ERROR, "Unable to allocate DSP\n");
01982             return -1;
01983          }
01984       }
01985 
01986       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
01987    } else if (mode == ANALOG_DIGITMODE_MF) {
01988       if (!p->dsp) {
01989          p->dsp = ast_dsp_new();
01990          if (!p->dsp) {
01991             ast_log(LOG_ERROR, "Unable to allocate DSP\n");
01992             return -1;
01993          }
01994       }
01995       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
01996    }
01997    return 0;
01998 }
01999 
02000 static int dahdi_wink(struct dahdi_pvt *p, int index);
02001 
02002 static int my_wink(void *pvt, enum analog_sub sub)
02003 {
02004    struct dahdi_pvt *p = pvt;
02005    int index = analogsub_to_dahdisub(sub);
02006    if (index != SUB_REAL) {
02007       ast_log(LOG_ERROR, "We used a sub other than SUB_REAL (incorrect assumption sir)\n");
02008    }
02009    return dahdi_wink(p, index);
02010 }
02011 
02012 static void wakeup_sub(struct dahdi_pvt *p, int a);
02013 
02014 static int reset_conf(struct dahdi_pvt *p);
02015 
02016 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted);
02017 
02018 static void my_handle_dtmf(void *pvt, struct ast_channel *ast, enum analog_sub analog_index, struct ast_frame **dest)
02019 {
02020    struct ast_frame *f = *dest;
02021    struct dahdi_pvt *p = pvt;
02022    int idx = analogsub_to_dahdisub(analog_index);
02023 
02024    ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
02025       f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
02026       f->subclass.integer, f->subclass.integer, ast->name);
02027 
02028    if (f->subclass.integer == 'f') {
02029       if (f->frametype == AST_FRAME_DTMF_END) {
02030          /* Fax tone -- Handle and return NULL */
02031          if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
02032             /* If faxbuffers are configured, use them for the fax transmission */
02033             if (p->usefaxbuffers && !p->bufferoverrideinuse) {
02034                struct dahdi_bufferinfo bi = {
02035                   .txbufpolicy = p->faxbuf_policy,
02036                   .bufsize = p->bufsize,
02037                   .numbufs = p->faxbuf_no
02038                };
02039                int res;
02040 
02041                if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
02042                   ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
02043                } else {
02044                   p->bufferoverrideinuse = 1;
02045                }
02046             }
02047             p->faxhandled = 1;
02048             if (p->dsp) {
02049                p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
02050                ast_dsp_set_features(p->dsp, p->dsp_features);
02051                ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
02052             }
02053             if (strcmp(ast->exten, "fax")) {
02054                const char *target_context = S_OR(ast->macrocontext, ast->context);
02055 
02056                /* We need to unlock 'ast' here because ast_exists_extension has the
02057                 * potential to start autoservice on the channel. Such action is prone
02058                 * to deadlock.
02059                 */
02060                ast_mutex_unlock(&p->lock);
02061                ast_channel_unlock(ast);
02062                if (ast_exists_extension(ast, target_context, "fax", 1,
02063                   S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
02064                   ast_channel_lock(ast);
02065                   ast_mutex_lock(&p->lock);
02066                   ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
02067                   /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
02068                   pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
02069                   if (ast_async_goto(ast, target_context, "fax", 1))
02070                      ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
02071                } else {
02072                   ast_channel_lock(ast);
02073                   ast_mutex_lock(&p->lock);
02074                   ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
02075                }
02076             } else {
02077                ast_debug(1, "Already in a fax extension, not redirecting\n");
02078             }
02079          } else {
02080             ast_debug(1, "Fax already handled\n");
02081          }
02082          dahdi_confmute(p, 0);
02083       }
02084       p->subs[idx].f.frametype = AST_FRAME_NULL;
02085       p->subs[idx].f.subclass.integer = 0;
02086       *dest = &p->subs[idx].f;
02087    }
02088 }
02089 
02090 static void my_lock_private(void *pvt)
02091 {
02092    struct dahdi_pvt *p = pvt;
02093    ast_mutex_lock(&p->lock);
02094 }
02095 
02096 static void my_unlock_private(void *pvt)
02097 {
02098    struct dahdi_pvt *p = pvt;
02099    ast_mutex_unlock(&p->lock);
02100 }
02101 
02102 static void my_deadlock_avoidance_private(void *pvt)
02103 {
02104    struct dahdi_pvt *p = pvt;
02105 
02106    DEADLOCK_AVOIDANCE(&p->lock);
02107 }
02108 
02109 /*!
02110  * \internal
02111  * \brief Post an AMI DAHDI channel association event.
02112  * \since 1.8
02113  *
02114  * \param p DAHDI private pointer
02115  * \param chan Channel associated with the private pointer
02116  *
02117  * \return Nothing
02118  */
02119 static void dahdi_ami_channel_event(struct dahdi_pvt *p, struct ast_channel *chan)
02120 {
02121    char ch_name[20];
02122 
02123    if (p->channel < CHAN_PSEUDO) {
02124       /* No B channel */
02125       snprintf(ch_name, sizeof(ch_name), "no-media (%d)", p->channel);
02126    } else if (p->channel == CHAN_PSEUDO) {
02127       /* Pseudo channel */
02128       strcpy(ch_name, "pseudo");
02129    } else {
02130       /* Real channel */
02131       snprintf(ch_name, sizeof(ch_name), "%d", p->channel);
02132    }
02133    ast_manager_event(chan, EVENT_FLAG_CALL, "DAHDIChannel",
02134       "Channel: %s\r\n"
02135       "Uniqueid: %s\r\n"
02136       "DAHDISpan: %d\r\n"
02137       "DAHDIChannel: %s\r\n",
02138       chan->name,
02139       chan->uniqueid,
02140       p->span,
02141       ch_name);
02142 }
02143 
02144 #ifdef HAVE_PRI
02145 /*!
02146  * \internal
02147  * \brief Post an AMI DAHDI channel association event.
02148  * \since 1.8
02149  *
02150  * \param pvt DAHDI private pointer
02151  * \param chan Channel associated with the private pointer
02152  *
02153  * \return Nothing
02154  */
02155 static void my_ami_channel_event(void *pvt, struct ast_channel *chan)
02156 {
02157    struct dahdi_pvt *p = pvt;
02158 
02159    dahdi_ami_channel_event(p, chan);
02160 }
02161 #endif
02162 
02163 /* linear_mode = 0 - turn linear mode off, >0 - turn linear mode on
02164 *  returns the last value of the linear setting 
02165 */ 
02166 static int my_set_linear_mode(void *pvt, enum analog_sub sub, int linear_mode)
02167 {
02168    struct dahdi_pvt *p = pvt;
02169    int oldval;
02170    int idx = analogsub_to_dahdisub(sub);
02171    
02172    dahdi_setlinear(p->subs[idx].dfd, linear_mode);
02173    oldval = p->subs[idx].linear;
02174    p->subs[idx].linear = linear_mode ? 1 : 0;
02175    return oldval;
02176 }
02177 
02178 static void my_set_inthreeway(void *pvt, enum analog_sub sub, int inthreeway)
02179 {
02180    struct dahdi_pvt *p = pvt;
02181    int idx = analogsub_to_dahdisub(sub);
02182 
02183    p->subs[idx].inthreeway = inthreeway;
02184 }
02185 
02186 static int get_alarms(struct dahdi_pvt *p);
02187 static void handle_alarms(struct dahdi_pvt *p, int alms);
02188 static void my_get_and_handle_alarms(void *pvt)
02189 {
02190    int res;
02191    struct dahdi_pvt *p = pvt;
02192 
02193    res = get_alarms(p);
02194    handle_alarms(p, res);
02195 }
02196 
02197 static void *my_get_sigpvt_bridged_channel(struct ast_channel *chan)
02198 {
02199    struct dahdi_pvt *p = ast_bridged_channel(chan)->tech_pvt;
02200    if (p)
02201       return p->sig_pvt;
02202    else
02203       return NULL;
02204 }
02205 
02206 static int my_get_sub_fd(void *pvt, enum analog_sub sub)
02207 {
02208    struct dahdi_pvt *p = pvt;
02209    int dahdi_sub = analogsub_to_dahdisub(sub);
02210    return p->subs[dahdi_sub].dfd;
02211 }
02212 
02213 static void my_set_cadence(void *pvt, int *cid_rings, struct ast_channel *ast)
02214 {
02215    struct dahdi_pvt *p = pvt;
02216 
02217    /* Choose proper cadence */
02218    if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
02219       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
02220          ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast->name, strerror(errno));
02221       *cid_rings = cidrings[p->distinctivering - 1];
02222    } else {
02223       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
02224          ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast->name, strerror(errno));
02225       *cid_rings = p->sendcalleridafter;
02226    }
02227 }
02228 
02229 static void my_set_alarm(void *pvt, int in_alarm)
02230 {
02231    struct dahdi_pvt *p = pvt;
02232 
02233    p->inalarm = in_alarm;
02234 }
02235 
02236 static void my_set_dialing(void *pvt, int is_dialing)
02237 {
02238    struct dahdi_pvt *p = pvt;
02239 
02240    p->dialing = is_dialing;
02241 }
02242 
02243 static void my_set_outgoing(void *pvt, int is_outgoing)
02244 {
02245    struct dahdi_pvt *p = pvt;
02246 
02247    p->outgoing = is_outgoing;
02248 }
02249 
02250 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02251 static void my_set_digital(void *pvt, int is_digital)
02252 {
02253    struct dahdi_pvt *p = pvt;
02254 
02255    p->digital = is_digital;
02256 }
02257 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02258 
02259 #if defined(HAVE_SS7)
02260 static void my_set_inservice(void *pvt, int is_inservice)
02261 {
02262    struct dahdi_pvt *p = pvt;
02263 
02264    p->inservice = is_inservice;
02265 }
02266 #endif   /* defined(HAVE_SS7) */
02267 
02268 #if defined(HAVE_SS7)
02269 static void my_set_locallyblocked(void *pvt, int is_blocked)
02270 {
02271    struct dahdi_pvt *p = pvt;
02272 
02273    p->locallyblocked = is_blocked;
02274 }
02275 #endif   /* defined(HAVE_SS7) */
02276 
02277 #if defined(HAVE_SS7)
02278 static void my_set_remotelyblocked(void *pvt, int is_blocked)
02279 {
02280    struct dahdi_pvt *p = pvt;
02281 
02282    p->remotelyblocked = is_blocked;
02283 }
02284 #endif   /* defined(HAVE_SS7) */
02285 
02286 static void my_set_ringtimeout(void *pvt, int ringt)
02287 {
02288    struct dahdi_pvt *p = pvt;
02289    p->ringt = ringt;
02290 }
02291 
02292 static void my_set_waitingfordt(void *pvt, struct ast_channel *ast)
02293 {
02294    struct dahdi_pvt *p = pvt;
02295 
02296    if (p->waitfordialtone && CANPROGRESSDETECT(p) && p->dsp) {
02297       ast_log(LOG_DEBUG, "Defer dialing for %dms or dialtone\n", p->waitfordialtone);
02298       gettimeofday(&p->waitingfordt, NULL);
02299       ast_setstate(ast, AST_STATE_OFFHOOK);
02300    }
02301 }
02302 
02303 static int my_check_waitingfordt(void *pvt)
02304 {
02305    struct dahdi_pvt *p = pvt;
02306 
02307    if (p->waitingfordt.tv_usec) {
02308       return 1;
02309    }
02310 
02311    return 0;
02312 }
02313 
02314 static void my_set_confirmanswer(void *pvt, int flag)
02315 {
02316    struct dahdi_pvt *p = pvt;
02317    p->confirmanswer = flag;
02318 }
02319 
02320 static int my_check_confirmanswer(void *pvt)
02321 {
02322    struct dahdi_pvt *p = pvt;
02323    if (p->confirmanswer) {
02324       return 1;
02325    }
02326 
02327    return 0;
02328 }
02329 
02330 static void my_set_callwaiting(void *pvt, int callwaiting_enable)
02331 {
02332    struct dahdi_pvt *p = pvt;
02333 
02334    p->callwaiting = callwaiting_enable;
02335 }
02336 
02337 static void my_cancel_cidspill(void *pvt)
02338 {
02339    struct dahdi_pvt *p = pvt;
02340 
02341    ast_free(p->cidspill);
02342    p->cidspill = NULL;
02343    restore_conference(p);
02344 }
02345 
02346 static int my_confmute(void *pvt, int mute)
02347 {
02348    struct dahdi_pvt *p = pvt;
02349    return dahdi_confmute(p, mute);
02350 }
02351 
02352 static void my_set_pulsedial(void *pvt, int flag)
02353 {
02354    struct dahdi_pvt *p = pvt;
02355    p->pulsedial = flag;
02356 }
02357 
02358 static void my_set_new_owner(void *pvt, struct ast_channel *new_owner)
02359 {
02360    struct dahdi_pvt *p = pvt;
02361 
02362    p->owner = new_owner;
02363 }
02364 
02365 static const char *my_get_orig_dialstring(void *pvt)
02366 {
02367    struct dahdi_pvt *p = pvt;
02368 
02369    return p->dialstring;
02370 }
02371 
02372 static void my_increase_ss_count(void)
02373 {
02374    ast_mutex_lock(&ss_thread_lock);
02375    ss_thread_count++;
02376    ast_mutex_unlock(&ss_thread_lock);
02377 }
02378 
02379 static void my_decrease_ss_count(void)
02380 {
02381    ast_mutex_lock(&ss_thread_lock);
02382    ss_thread_count--;
02383    ast_cond_signal(&ss_thread_complete);
02384    ast_mutex_unlock(&ss_thread_lock);
02385 }
02386 
02387 static void my_all_subchannels_hungup(void *pvt)
02388 {
02389    struct dahdi_pvt *p = pvt;
02390    int res, law;
02391 
02392    p->faxhandled = 0;
02393    p->didtdd = 0;
02394 
02395    if (p->dsp) {
02396       ast_dsp_free(p->dsp);
02397       p->dsp = NULL;
02398    }
02399 
02400    p->law = p->law_default;
02401    law = p->law_default;
02402    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
02403    if (res < 0)
02404       ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
02405 
02406    dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
02407 
02408 #if 1
02409    {
02410    int i;
02411    p->owner = NULL;
02412    /* Cleanup owners here */
02413    for (i = 0; i < 3; i++) {
02414       p->subs[i].owner = NULL;
02415    }
02416    }
02417 #endif
02418 
02419    reset_conf(p);
02420    if (num_restart_pending == 0) {
02421       restart_monitor();
02422    }
02423 }
02424 
02425 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index);
02426 
02427 static int my_conf_del(void *pvt, enum analog_sub sub)
02428 {
02429    struct dahdi_pvt *p = pvt;
02430    int x = analogsub_to_dahdisub(sub);
02431 
02432    return conf_del(p, &p->subs[x], x);
02433 }
02434 
02435 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index, int slavechannel);
02436 
02437 static int my_conf_add(void *pvt, enum analog_sub sub)
02438 {
02439    struct dahdi_pvt *p = pvt;
02440    int x = analogsub_to_dahdisub(sub);
02441 
02442    return conf_add(p, &p->subs[x], x, 0);
02443 }
02444 
02445 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out);
02446 
02447 static int my_complete_conference_update(void *pvt, int needconference)
02448 {
02449    struct dahdi_pvt *p = pvt;
02450    int needconf = needconference;
02451    int x;
02452    int useslavenative;
02453    struct dahdi_pvt *slave = NULL;
02454 
02455    useslavenative = isslavenative(p, &slave);
02456 
02457    /* If we have a slave, add him to our conference now. or DAX
02458       if this is slave native */
02459    for (x = 0; x < MAX_SLAVES; x++) {
02460       if (p->slaves[x]) {
02461          if (useslavenative)
02462             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
02463          else {
02464             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
02465             needconf++;
02466          }
02467       }
02468    }
02469    /* If we're supposed to be in there, do so now */
02470    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
02471       if (useslavenative)
02472          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
02473       else {
02474          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
02475          needconf++;
02476       }
02477    }
02478    /* If we have a master, add ourselves to his conference */
02479    if (p->master) {
02480       if (isslavenative(p->master, NULL)) {
02481          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
02482       } else {
02483          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
02484       }
02485    }
02486    if (!needconf) {
02487       /* Nobody is left (or should be left) in our conference.
02488          Kill it. */
02489       p->confno = -1;
02490    }
02491 
02492    return 0;
02493 }
02494 
02495 static int check_for_conference(struct dahdi_pvt *p);
02496 
02497 static int my_check_for_conference(void *pvt)
02498 {
02499    struct dahdi_pvt *p = pvt;
02500    return check_for_conference(p);
02501 }
02502 
02503 static void my_swap_subchannels(void *pvt, enum analog_sub a, struct ast_channel *ast_a,  enum analog_sub b, struct ast_channel *ast_b)
02504 {
02505    struct dahdi_pvt *p = pvt;
02506    int da, db;
02507    int tchan;
02508    int tinthreeway;
02509 
02510    da = analogsub_to_dahdisub(a);
02511    db = analogsub_to_dahdisub(b);
02512 
02513    tchan = p->subs[da].chan;
02514    p->subs[da].chan = p->subs[db].chan;
02515    p->subs[db].chan = tchan;
02516 
02517    tinthreeway = p->subs[da].inthreeway;
02518    p->subs[da].inthreeway = p->subs[db].inthreeway;
02519    p->subs[db].inthreeway = tinthreeway;
02520 
02521    p->subs[da].owner = ast_a;
02522    p->subs[db].owner = ast_b;
02523 
02524    if (ast_a)
02525       ast_channel_set_fd(ast_a, 0, p->subs[da].dfd);
02526    if (ast_b)
02527       ast_channel_set_fd(ast_b, 0, p->subs[db].dfd);
02528 
02529    wakeup_sub(p, a);
02530    wakeup_sub(p, b);
02531 
02532    return;
02533 }
02534 
02535 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid);
02536 
02537 static struct ast_channel *my_new_analog_ast_channel(void *pvt, int state, int startpbx, enum analog_sub sub, const struct ast_channel *requestor)
02538 {
02539    struct dahdi_pvt *p = pvt;
02540    int dsub = analogsub_to_dahdisub(sub);
02541 
02542    return dahdi_new(p, state, startpbx, dsub, 0, requestor ? requestor->linkedid : "");
02543 }
02544 
02545 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02546 static int dahdi_setlaw(int dfd, int law)
02547 {
02548    int res;
02549    res = ioctl(dfd, DAHDI_SETLAW, &law);
02550    if (res)
02551       return res;
02552    return 0;
02553 }
02554 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02555 
02556 #if defined(HAVE_PRI)
02557 static struct ast_channel *my_new_pri_ast_channel(void *pvt, int state, enum sig_pri_law law, char *exten, const struct ast_channel *requestor)
02558 {
02559    struct dahdi_pvt *p = pvt;
02560    int audio;
02561    int newlaw = -1;
02562 
02563    switch (p->sig) {
02564    case SIG_PRI_LIB_HANDLE_CASES:
02565       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
02566          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
02567          break;
02568       }
02569       /* Fall through */
02570    default:
02571       /* Set to audio mode at this point */
02572       audio = 1;
02573       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1) {
02574          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
02575             p->channel, audio, strerror(errno));
02576       }
02577       break;
02578    }
02579 
02580    if (law != SIG_PRI_DEFLAW) {
02581       dahdi_setlaw(p->subs[SUB_REAL].dfd, (law == SIG_PRI_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
02582    }
02583 
02584    ast_copy_string(p->exten, exten, sizeof(p->exten));
02585 
02586    switch (law) {
02587       case SIG_PRI_DEFLAW:
02588          newlaw = 0;
02589          break;
02590       case SIG_PRI_ALAW:
02591          newlaw = DAHDI_LAW_ALAW;
02592          break;
02593       case SIG_PRI_ULAW:
02594          newlaw = DAHDI_LAW_MULAW;
02595          break;
02596    }
02597    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
02598 }
02599 #endif   /* defined(HAVE_PRI) */
02600 
02601 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law);
02602 
02603 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02604 /*!
02605  * \internal
02606  * \brief Open the PRI/SS7 channel media path.
02607  * \since 1.8
02608  *
02609  * \param p Channel private control structure.
02610  *
02611  * \return Nothing
02612  */
02613 static void my_pri_ss7_open_media(void *p)
02614 {
02615    struct dahdi_pvt *pvt = p;
02616    int res;
02617    int dfd;
02618    int set_val;
02619 
02620    dfd = pvt->subs[SUB_REAL].dfd;
02621 
02622    /* Open the media path. */
02623    set_val = 1;
02624    res = ioctl(dfd, DAHDI_AUDIOMODE, &set_val);
02625    if (res < 0) {
02626       ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n",
02627          pvt->channel, strerror(errno));
02628    }
02629 
02630    /* Set correct companding law for this call. */
02631    res = dahdi_setlaw(dfd, pvt->law);
02632    if (res < 0) {
02633       ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pvt->channel);
02634    }
02635 
02636    /* Set correct gain for this call. */
02637    if (pvt->digital) {
02638       res = set_actual_gain(dfd, 0, 0, pvt->rxdrc, pvt->txdrc, pvt->law);
02639    } else {
02640       res = set_actual_gain(dfd, pvt->rxgain, pvt->txgain, pvt->rxdrc, pvt->txdrc,
02641          pvt->law);
02642    }
02643    if (res < 0) {
02644       ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pvt->channel);
02645    }
02646 
02647    if (pvt->dsp_features && pvt->dsp) {
02648       ast_dsp_set_features(pvt->dsp, pvt->dsp_features);
02649       pvt->dsp_features = 0;
02650    }
02651 }
02652 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02653 
02654 #if defined(HAVE_PRI)
02655 /*!
02656  * \internal
02657  * \brief Ask DAHDI to dial the given dial string.
02658  * \since 1.8.11
02659  *
02660  * \param p Channel private control structure.
02661  * \param dial_string String to pass to DAHDI to dial.
02662  *
02663  * \note The channel private lock needs to be held when calling.
02664  *
02665  * \return Nothing
02666  */
02667 static void my_pri_dial_digits(void *p, const char *dial_string)
02668 {
02669    struct dahdi_dialoperation zo = {
02670       .op = DAHDI_DIAL_OP_APPEND,
02671    };
02672    struct dahdi_pvt *pvt = p;
02673    int res;
02674 
02675    snprintf(zo.dialstr, sizeof(zo.dialstr), "T%s", dial_string);
02676    ast_debug(1, "Channel %d: Sending '%s' to DAHDI_DIAL.\n", pvt->channel, zo.dialstr);
02677    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo);
02678    if (res) {
02679       ast_log(LOG_WARNING, "Channel %d: Couldn't dial '%s': %s\n",
02680          pvt->channel, dial_string, strerror(errno));
02681    } else {
02682       pvt->dialing = 1;
02683    }
02684 }
02685 #endif   /* defined(HAVE_PRI) */
02686 
02687 static int unalloc_sub(struct dahdi_pvt *p, int x);
02688 
02689 static int my_unallocate_sub(void *pvt, enum analog_sub analogsub)
02690 {
02691    struct dahdi_pvt *p = pvt;
02692 
02693    return unalloc_sub(p, analogsub_to_dahdisub(analogsub));
02694 }
02695 
02696 static int alloc_sub(struct dahdi_pvt *p, int x);
02697 
02698 static int my_allocate_sub(void *pvt, enum analog_sub analogsub)
02699 {
02700    struct dahdi_pvt *p = pvt;
02701 
02702    return alloc_sub(p, analogsub_to_dahdisub(analogsub));
02703 }
02704 
02705 static int has_voicemail(struct dahdi_pvt *p);
02706 
02707 static int my_has_voicemail(void *pvt)
02708 {
02709    struct dahdi_pvt *p = pvt;
02710 
02711    return has_voicemail(p);
02712 }
02713 
02714 static int my_play_tone(void *pvt, enum analog_sub sub, enum analog_tone tone)
02715 {
02716    struct dahdi_pvt *p = pvt;
02717    int index;
02718 
02719    index = analogsub_to_dahdisub(sub);
02720 
02721    return tone_zone_play_tone(p->subs[index].dfd, analog_tone_to_dahditone(tone));
02722 }
02723 
02724 static enum analog_event dahdievent_to_analogevent(int event)
02725 {
02726    enum analog_event res;
02727 
02728    switch (event) {
02729    case DAHDI_EVENT_ONHOOK:
02730       res = ANALOG_EVENT_ONHOOK;
02731       break;
02732    case DAHDI_EVENT_RINGOFFHOOK:
02733       res = ANALOG_EVENT_RINGOFFHOOK;
02734       break;
02735    case DAHDI_EVENT_WINKFLASH:
02736       res = ANALOG_EVENT_WINKFLASH;
02737       break;
02738    case DAHDI_EVENT_ALARM:
02739       res = ANALOG_EVENT_ALARM;
02740       break;
02741    case DAHDI_EVENT_NOALARM:
02742       res = ANALOG_EVENT_NOALARM;
02743       break;
02744    case DAHDI_EVENT_DIALCOMPLETE:
02745       res = ANALOG_EVENT_DIALCOMPLETE;
02746       break;
02747    case DAHDI_EVENT_RINGERON:
02748       res = ANALOG_EVENT_RINGERON;
02749       break;
02750    case DAHDI_EVENT_RINGEROFF:
02751       res = ANALOG_EVENT_RINGEROFF;
02752       break;
02753    case DAHDI_EVENT_HOOKCOMPLETE:
02754       res = ANALOG_EVENT_HOOKCOMPLETE;
02755       break;
02756    case DAHDI_EVENT_PULSE_START:
02757       res = ANALOG_EVENT_PULSE_START;
02758       break;
02759    case DAHDI_EVENT_POLARITY:
02760       res = ANALOG_EVENT_POLARITY;
02761       break;
02762    case DAHDI_EVENT_RINGBEGIN:
02763       res = ANALOG_EVENT_RINGBEGIN;
02764       break;
02765    case DAHDI_EVENT_EC_DISABLED:
02766       res = ANALOG_EVENT_EC_DISABLED;
02767       break;
02768    case DAHDI_EVENT_REMOVED:
02769       res = ANALOG_EVENT_REMOVED;
02770       break;
02771    case DAHDI_EVENT_NEONMWI_ACTIVE:
02772       res = ANALOG_EVENT_NEONMWI_ACTIVE;
02773       break;
02774    case DAHDI_EVENT_NEONMWI_INACTIVE:
02775       res = ANALOG_EVENT_NEONMWI_INACTIVE;
02776       break;
02777 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
02778    case DAHDI_EVENT_TX_CED_DETECTED:
02779       res = ANALOG_EVENT_TX_CED_DETECTED;
02780       break;
02781    case DAHDI_EVENT_RX_CED_DETECTED:
02782       res = ANALOG_EVENT_RX_CED_DETECTED;
02783       break;
02784    case DAHDI_EVENT_EC_NLP_DISABLED:
02785       res = ANALOG_EVENT_EC_NLP_DISABLED;
02786       break;
02787    case DAHDI_EVENT_EC_NLP_ENABLED:
02788       res = ANALOG_EVENT_EC_NLP_ENABLED;
02789       break;
02790 #endif
02791    case DAHDI_EVENT_PULSEDIGIT:
02792       res = ANALOG_EVENT_PULSEDIGIT;
02793       break;
02794    case DAHDI_EVENT_DTMFDOWN:
02795       res = ANALOG_EVENT_DTMFDOWN;
02796       break;
02797    case DAHDI_EVENT_DTMFUP:
02798       res = ANALOG_EVENT_DTMFUP;
02799       break;
02800    default:
02801       switch(event & 0xFFFF0000) {
02802       case DAHDI_EVENT_PULSEDIGIT:
02803       case DAHDI_EVENT_DTMFDOWN:
02804       case DAHDI_EVENT_DTMFUP:
02805          /* The event includes a digit number in the low word.
02806           * Converting it to a 'enum analog_event' would remove
02807           * that information. Thus it is returned as-is.
02808           */
02809          return event;
02810       }
02811 
02812       res = ANALOG_EVENT_ERROR;
02813       break;
02814    }
02815 
02816    return res;
02817 }
02818 
02819 static inline int dahdi_wait_event(int fd);
02820 
02821 static int my_wait_event(void *pvt)
02822 {
02823    struct dahdi_pvt *p = pvt;
02824 
02825    return dahdi_wait_event(p->subs[SUB_REAL].dfd);
02826 }
02827 
02828 static int my_get_event(void *pvt)
02829 {
02830    struct dahdi_pvt *p = pvt;
02831    int res;
02832 
02833    if (p->fake_event) {
02834       res = p->fake_event;
02835       p->fake_event = 0;
02836    } else
02837       res = dahdi_get_event(p->subs[SUB_REAL].dfd);
02838 
02839    return dahdievent_to_analogevent(res);
02840 }
02841 
02842 static int my_is_off_hook(void *pvt)
02843 {
02844    struct dahdi_pvt *p = pvt;
02845    int res;
02846    struct dahdi_params par;
02847 
02848    memset(&par, 0, sizeof(par));
02849 
02850    if (p->subs[SUB_REAL].dfd > -1)
02851       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
02852    else {
02853       /* Assume not off hook on CVRS */
02854       res = 0;
02855       par.rxisoffhook = 0;
02856    }
02857    if (res) {
02858       ast_log(LOG_WARNING, "Unable to check hook state on channel %d: %s\n", p->channel, strerror(errno));
02859    }
02860 
02861    if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
02862       /* When "onhook" that means no battery on the line, and thus
02863       it is out of service..., if it's on a TDM card... If it's a channel
02864       bank, there is no telling... */
02865       return (par.rxbits > -1) || par.rxisoffhook;
02866    }
02867 
02868    return par.rxisoffhook;
02869 }
02870 
02871 static void dahdi_enable_ec(struct dahdi_pvt *p);
02872 static void dahdi_disable_ec(struct dahdi_pvt *p);
02873 
02874 static int my_set_echocanceller(void *pvt, int enable)
02875 {
02876    struct dahdi_pvt *p = pvt;
02877 
02878    if (enable)
02879       dahdi_enable_ec(p);
02880    else
02881       dahdi_disable_ec(p);
02882 
02883    return 0;
02884 }
02885 
02886 static int dahdi_ring_phone(struct dahdi_pvt *p);
02887 
02888 static int my_ring(void *pvt)
02889 {
02890    struct dahdi_pvt *p = pvt;
02891 
02892    return dahdi_ring_phone(p);
02893 }
02894 
02895 static int my_flash(void *pvt)
02896 {
02897    struct dahdi_pvt *p = pvt;
02898    int func = DAHDI_FLASH;
02899    return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &func);
02900 }
02901 
02902 static inline int dahdi_set_hook(int fd, int hs);
02903 
02904 static int my_off_hook(void *pvt)
02905 {
02906    struct dahdi_pvt *p = pvt;
02907    return dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
02908 }
02909 
02910 static void my_set_needringing(void *pvt, int value)
02911 {
02912    struct dahdi_pvt *p = pvt;
02913    p->subs[SUB_REAL].needringing = value;
02914 }
02915 
02916 static void my_set_polarity(void *pvt, int value)
02917 {
02918    struct dahdi_pvt *p = pvt;
02919 
02920    if (p->channel == CHAN_PSEUDO) {
02921       return;
02922    }
02923    p->polarity = value;
02924    ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETPOLARITY, &value);
02925 }
02926 
02927 static void my_start_polarityswitch(void *pvt)
02928 {
02929    struct dahdi_pvt *p = pvt;
02930 
02931    if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
02932       my_set_polarity(pvt, 0);
02933    }
02934 }
02935 
02936 static void my_answer_polarityswitch(void *pvt)
02937 {
02938    struct dahdi_pvt *p = pvt;
02939 
02940    if (!p->answeronpolarityswitch) {
02941       return;
02942    }
02943 
02944    my_set_polarity(pvt, 1);
02945 }
02946 
02947 static void my_hangup_polarityswitch(void *pvt)
02948 {
02949    struct dahdi_pvt *p = pvt;
02950 
02951    if (!p->hanguponpolarityswitch) {
02952       return;
02953    }
02954 
02955    if (p->answeronpolarityswitch) {
02956       my_set_polarity(pvt, 0);
02957    } else {
02958       my_set_polarity(pvt, 1);
02959    }
02960 }
02961 
02962 static int my_start(void *pvt)
02963 {
02964    struct dahdi_pvt *p = pvt;
02965    int x = DAHDI_START;
02966 
02967    return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
02968 }
02969 
02970 static int my_dial_digits(void *pvt, enum analog_sub sub, struct analog_dialoperation *dop)
02971 {
02972    int index = analogsub_to_dahdisub(sub);
02973    int res;
02974    struct dahdi_pvt *p = pvt;
02975    struct dahdi_dialoperation ddop;
02976 
02977    if (dop->op != ANALOG_DIAL_OP_REPLACE) {
02978       ast_log(LOG_ERROR, "Fix the dial_digits callback!\n");
02979       return -1;
02980    }
02981 
02982    if (sub != ANALOG_SUB_REAL) {
02983       ast_log(LOG_ERROR, "Trying to dial_digits '%s' on channel %d subchannel %d\n",
02984          dop->dialstr, p->channel, sub);
02985       return -1;
02986    }
02987 
02988    ddop.op = DAHDI_DIAL_OP_REPLACE;
02989    ast_copy_string(ddop.dialstr, dop->dialstr, sizeof(ddop.dialstr));
02990 
02991    ast_debug(1, "Channel %d: Sending '%s' to DAHDI_DIAL.\n", p->channel, ddop.dialstr);
02992 
02993    res = ioctl(p->subs[index].dfd, DAHDI_DIAL, &ddop);
02994    if (res == -1) {
02995       ast_debug(1, "DAHDI_DIAL ioctl failed on %s: %s\n", p->owner->name, strerror(errno));
02996    }
02997 
02998    return res;
02999 }
03000 
03001 static void dahdi_train_ec(struct dahdi_pvt *p);
03002 
03003 static int my_train_echocanceller(void *pvt)
03004 {
03005    struct dahdi_pvt *p = pvt;
03006 
03007    dahdi_train_ec(p);
03008 
03009    return 0;
03010 }
03011 
03012 static int my_is_dialing(void *pvt, enum analog_sub sub)
03013 {
03014    struct dahdi_pvt *p = pvt;
03015    int index;
03016    int x;
03017 
03018    index = analogsub_to_dahdisub(sub);
03019 
03020    if (ioctl(p->subs[index].dfd, DAHDI_DIALING, &x)) {
03021       ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed!\n");
03022       return -1;
03023    }
03024 
03025    return x;
03026 }
03027 
03028 static int my_on_hook(void *pvt)
03029 {
03030    struct dahdi_pvt *p = pvt;
03031    return dahdi_set_hook(p->subs[ANALOG_SUB_REAL].dfd, DAHDI_ONHOOK);
03032 }
03033 
03034 #if defined(HAVE_PRI)
03035 static void my_pri_fixup_chans(void *chan_old, void *chan_new)
03036 {
03037    struct dahdi_pvt *old_chan = chan_old;
03038    struct dahdi_pvt *new_chan = chan_new;
03039 
03040    new_chan->owner = old_chan->owner;
03041    old_chan->owner = NULL;
03042    if (new_chan->owner) {
03043       new_chan->owner->tech_pvt = new_chan;
03044       new_chan->owner->fds[0] = new_chan->subs[SUB_REAL].dfd;
03045       new_chan->subs[SUB_REAL].owner = old_chan->subs[SUB_REAL].owner;
03046       old_chan->subs[SUB_REAL].owner = NULL;
03047    }
03048    /* Copy any DSP that may be present */
03049    new_chan->dsp = old_chan->dsp;
03050    new_chan->dsp_features = old_chan->dsp_features;
03051    old_chan->dsp = NULL;
03052    old_chan->dsp_features = 0;
03053 
03054    /* Transfer flags from the old channel. */
03055    new_chan->dialing = old_chan->dialing;
03056    new_chan->digital = old_chan->digital;
03057    new_chan->outgoing = old_chan->outgoing;
03058    old_chan->dialing = 0;
03059    old_chan->digital = 0;
03060    old_chan->outgoing = 0;
03061 
03062    /* More stuff to transfer to the new channel. */
03063    new_chan->law = old_chan->law;
03064    strcpy(new_chan->dialstring, old_chan->dialstring);
03065 }
03066 #endif   /* defined(HAVE_PRI) */
03067 
03068 #if defined(HAVE_PRI)
03069 static int sig_pri_tone_to_dahditone(enum sig_pri_tone tone)
03070 {
03071    switch (tone) {
03072    case SIG_PRI_TONE_RINGTONE:
03073       return DAHDI_TONE_RINGTONE;
03074    case SIG_PRI_TONE_STUTTER:
03075       return DAHDI_TONE_STUTTER;
03076    case SIG_PRI_TONE_CONGESTION:
03077       return DAHDI_TONE_CONGESTION;
03078    case SIG_PRI_TONE_DIALTONE:
03079       return DAHDI_TONE_DIALTONE;
03080    case SIG_PRI_TONE_DIALRECALL:
03081       return DAHDI_TONE_DIALRECALL;
03082    case SIG_PRI_TONE_INFO:
03083       return DAHDI_TONE_INFO;
03084    case SIG_PRI_TONE_BUSY:
03085       return DAHDI_TONE_BUSY;
03086    default:
03087       return -1;
03088    }
03089 }
03090 #endif   /* defined(HAVE_PRI) */
03091 
03092 #if defined(HAVE_PRI)
03093 static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
03094 {
03095    int x;
03096 
03097    ioctl(pri->fds[index], DAHDI_GETEVENT, &x);
03098    switch (x) {
03099    case DAHDI_EVENT_NONE:
03100       break;
03101    case DAHDI_EVENT_ALARM:
03102    case DAHDI_EVENT_NOALARM:
03103       if (sig_pri_is_alarm_ignored(pri)) {
03104          break;
03105       }
03106       /* Fall through */
03107    default:
03108       ast_log(LOG_NOTICE, "PRI got event: %s (%d) on D-channel of span %d\n",
03109          event2str(x), x, pri->span);
03110       break;
03111    }
03112    /* Keep track of alarm state */
03113    switch (x) {
03114    case DAHDI_EVENT_ALARM:
03115       pri_event_alarm(pri, index, 0);
03116       break;
03117    case DAHDI_EVENT_NOALARM:
03118       pri_event_noalarm(pri, index, 0);
03119       break;
03120    default:
03121       break;
03122    }
03123 }
03124 #endif   /* defined(HAVE_PRI) */
03125 
03126 #if defined(HAVE_PRI)
03127 static int my_pri_play_tone(void *pvt, enum sig_pri_tone tone)
03128 {
03129    struct dahdi_pvt *p = pvt;
03130 
03131    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_pri_tone_to_dahditone(tone));
03132 }
03133 #endif   /* defined(HAVE_PRI) */
03134 
03135 #if defined(HAVE_PRI) || defined(HAVE_SS7)
03136 /*!
03137  * \internal
03138  * \brief Set the caller id information.
03139  * \since 1.8
03140  *
03141  * \param pvt DAHDI private structure
03142  * \param caller Caller-id information to set.
03143  *
03144  * \return Nothing
03145  */
03146 static void my_set_callerid(void *pvt, const struct ast_party_caller *caller)
03147 {
03148    struct dahdi_pvt *p = pvt;
03149 
03150    ast_copy_string(p->cid_num,
03151       S_COR(caller->id.number.valid, caller->id.number.str, ""),
03152       sizeof(p->cid_num));
03153    ast_copy_string(p->cid_name,
03154       S_COR(caller->id.name.valid, caller->id.name.str, ""),
03155       sizeof(p->cid_name));
03156    ast_copy_string(p->cid_subaddr,
03157       S_COR(caller->id.subaddress.valid, caller->id.subaddress.str, ""),
03158       sizeof(p->cid_subaddr));
03159    p->cid_ton = caller->id.number.plan;
03160    p->callingpres = ast_party_id_presentation(&caller->id);
03161    if (caller->id.tag) {
03162       ast_copy_string(p->cid_tag, caller->id.tag, sizeof(p->cid_tag));
03163    }
03164    ast_copy_string(p->cid_ani,
03165       S_COR(caller->ani.number.valid, caller->ani.number.str, ""),
03166       sizeof(p->cid_ani));
03167    p->cid_ani2 = caller->ani2;
03168 }
03169 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03170 
03171 #if defined(HAVE_PRI) || defined(HAVE_SS7)
03172 /*!
03173  * \internal
03174  * \brief Set the Dialed Number Identifier.
03175  * \since 1.8
03176  *
03177  * \param pvt DAHDI private structure
03178  * \param dnid Dialed Number Identifier string.
03179  *
03180  * \return Nothing
03181  */
03182 static void my_set_dnid(void *pvt, const char *dnid)
03183 {
03184    struct dahdi_pvt *p = pvt;
03185 
03186    ast_copy_string(p->dnid, dnid, sizeof(p->dnid));
03187 }
03188 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03189 
03190 #if defined(HAVE_PRI)
03191 /*!
03192  * \internal
03193  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
03194  * \since 1.8
03195  *
03196  * \param pvt DAHDI private structure
03197  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
03198  *
03199  * \return Nothing
03200  */
03201 static void my_set_rdnis(void *pvt, const char *rdnis)
03202 {
03203    struct dahdi_pvt *p = pvt;
03204 
03205    ast_copy_string(p->rdnis, rdnis, sizeof(p->rdnis));
03206 }
03207 #endif   /* defined(HAVE_PRI) */
03208 
03209 #if defined(HAVE_PRI)
03210 /*!
03211  * \internal
03212  * \brief Make a dialstring for native ISDN CC to recall properly.
03213  * \since 1.8
03214  *
03215  * \param priv Channel private control structure.
03216  * \param buf Where to put the modified dialstring.
03217  * \param buf_size Size of modified dialstring buffer.
03218  *
03219  * \details
03220  * original dialstring:
03221  * DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03222  *
03223  * The modified dialstring will have prefixed the channel-group section
03224  * with the ISDN channel restriction.
03225  *
03226  * buf:
03227  * DAHDI/i<span>-(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03228  *
03229  * The routine will check to see if the ISDN channel restriction is already
03230  * in the original dialstring.
03231  *
03232  * \return Nothing
03233  */
03234 static void my_pri_make_cc_dialstring(void *priv, char *buf, size_t buf_size)
03235 {
03236    char *dial;
03237    struct dahdi_pvt *pvt;
03238    AST_DECLARE_APP_ARGS(args,
03239       AST_APP_ARG(tech);   /* channel technology token */
03240       AST_APP_ARG(group);  /* channel/group token */
03241       //AST_APP_ARG(ext);  /* extension token */
03242       //AST_APP_ARG(opts); /* options token */
03243       //AST_APP_ARG(other);   /* Any remining unused arguments */
03244    );
03245 
03246    pvt = priv;
03247    dial = ast_strdupa(pvt->dialstring);
03248    AST_NONSTANDARD_APP_ARGS(args, dial, '/');
03249    if (!args.tech) {
03250       ast_copy_string(buf, pvt->dialstring, buf_size);
03251       return;
03252    }
03253    if (!args.group) {
03254       /* Append the ISDN span channel restriction to the dialstring. */
03255       snprintf(buf, buf_size, "%s/i%d-", args.tech, pvt->pri->span);
03256       return;
03257    }
03258    if (isdigit(args.group[0]) || args.group[0] == 'i' || strchr(args.group, '!')) {
03259       /* The ISDN span channel restriction is not needed or already
03260        * in the dialstring. */
03261       ast_copy_string(buf, pvt->dialstring, buf_size);
03262       return;
03263    }
03264    /* Insert the ISDN span channel restriction into the dialstring. */
03265    snprintf(buf, buf_size, "%s/i%d-%s", args.tech, pvt->pri->span, args.group);
03266 }
03267 #endif   /* defined(HAVE_PRI) */
03268 
03269 #if defined(HAVE_PRI)
03270 /*!
03271  * \internal
03272  * \brief Reevaluate the PRI span device state.
03273  * \since 1.8
03274  *
03275  * \param pri Asterisk D channel control structure.
03276  *
03277  * \return Nothing
03278  *
03279  * \note Assumes the pri->lock is already obtained.
03280  */
03281 static void dahdi_pri_update_span_devstate(struct sig_pri_span *pri)
03282 {
03283    unsigned idx;
03284    unsigned num_b_chans;   /* Number of B channels provisioned on the span. */
03285    unsigned in_use;     /* Number of B channels in use on the span. */
03286    unsigned in_alarm;      /* TRUE if the span is in alarm condition. */
03287    enum ast_device_state new_state;
03288 
03289    /* Count the number of B channels and the number of B channels in use. */
03290    num_b_chans = 0;
03291    in_use = 0;
03292    in_alarm = 1;
03293    for (idx = pri->numchans; idx--;) {
03294       if (pri->pvts[idx] && !pri->pvts[idx]->no_b_channel) {
03295          /* This is a B channel interface. */
03296          ++num_b_chans;
03297          if (!sig_pri_is_chan_available(pri->pvts[idx])) {
03298             ++in_use;
03299          }
03300          if (!pri->pvts[idx]->inalarm) {
03301             /* There is a channel that is not in alarm. */
03302             in_alarm = 0;
03303          }
03304       }
03305    }
03306 
03307    /* Update the span congestion device state and report any change. */
03308    if (in_alarm) {
03309       new_state = AST_DEVICE_UNAVAILABLE;
03310    } else {
03311       new_state = num_b_chans == in_use ? AST_DEVICE_BUSY : AST_DEVICE_NOT_INUSE;
03312    }
03313    if (pri->congestion_devstate != new_state) {
03314       pri->congestion_devstate = new_state;
03315       ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/congestion", pri->span);
03316    }
03317 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
03318    /* Update the span threshold device state and report any change. */
03319    if (in_alarm) {
03320       new_state = AST_DEVICE_UNAVAILABLE;
03321    } else if (!in_use) {
03322       new_state = AST_DEVICE_NOT_INUSE;
03323    } else if (!pri->user_busy_threshold) {
03324       new_state = in_use < num_b_chans ? AST_DEVICE_INUSE : AST_DEVICE_BUSY;
03325    } else {
03326       new_state = in_use < pri->user_busy_threshold ? AST_DEVICE_INUSE
03327          : AST_DEVICE_BUSY;
03328    }
03329    if (pri->threshold_devstate != new_state) {
03330       pri->threshold_devstate = new_state;
03331       ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/threshold", pri->span);
03332    }
03333 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
03334 }
03335 #endif   /* defined(HAVE_PRI) */
03336 
03337 #if defined(HAVE_PRI)
03338 /*!
03339  * \internal
03340  * \brief Reference this module.
03341  * \since 1.8
03342  *
03343  * \return Nothing
03344  */
03345 static void my_module_ref(void)
03346 {
03347    ast_module_ref(ast_module_info->self);
03348 }
03349 #endif   /* defined(HAVE_PRI) */
03350 
03351 #if defined(HAVE_PRI)
03352 /*!
03353  * \internal
03354  * \brief Unreference this module.
03355  * \since 1.8
03356  *
03357  * \return Nothing
03358  */
03359 static void my_module_unref(void)
03360 {
03361    ast_module_unref(ast_module_info->self);
03362 }
03363 #endif   /* defined(HAVE_PRI) */
03364 
03365 #if defined(HAVE_PRI)
03366 #if defined(HAVE_PRI_CALL_WAITING)
03367 static void my_pri_init_config(void *priv, struct sig_pri_span *pri);
03368 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03369 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri);
03370 
03371 static struct sig_pri_callback dahdi_pri_callbacks =
03372 {
03373    .handle_dchan_exception = my_handle_dchan_exception,
03374    .play_tone = my_pri_play_tone,
03375    .set_echocanceller = my_set_echocanceller,
03376    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03377    .lock_private = my_lock_private,
03378    .unlock_private = my_unlock_private,
03379    .new_ast_channel = my_new_pri_ast_channel,
03380    .fixup_chans = my_pri_fixup_chans,
03381    .set_alarm = my_set_alarm,
03382    .set_dialing = my_set_dialing,
03383    .set_outgoing = my_set_outgoing,
03384    .set_digital = my_set_digital,
03385    .set_callerid = my_set_callerid,
03386    .set_dnid = my_set_dnid,
03387    .set_rdnis = my_set_rdnis,
03388    .new_nobch_intf = dahdi_new_pri_nobch_channel,
03389 #if defined(HAVE_PRI_CALL_WAITING)
03390    .init_config = my_pri_init_config,
03391 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03392    .get_orig_dialstring = my_get_orig_dialstring,
03393    .make_cc_dialstring = my_pri_make_cc_dialstring,
03394    .update_span_devstate = dahdi_pri_update_span_devstate,
03395    .module_ref = my_module_ref,
03396    .module_unref = my_module_unref,
03397    .dial_digits = my_pri_dial_digits,
03398    .open_media = my_pri_ss7_open_media,
03399    .ami_channel_event = my_ami_channel_event,
03400 };
03401 #endif   /* defined(HAVE_PRI) */
03402 
03403 #if defined(HAVE_SS7)
03404 /*!
03405  * \internal
03406  * \brief Handle the SS7 link exception.
03407  * \since 1.8
03408  *
03409  * \param linkset Controlling linkset for the channel.
03410  * \param which Link index of the signaling channel.
03411  *
03412  * \return Nothing
03413  */
03414 static void my_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
03415 {
03416    int event;
03417 
03418    if (ioctl(linkset->fds[which], DAHDI_GETEVENT, &event)) {
03419       ast_log(LOG_ERROR, "SS7: Error in exception retrieval on span %d/%d!\n",
03420          linkset->span, which);
03421       return;
03422    }
03423    switch (event) {
03424    case DAHDI_EVENT_NONE:
03425       break;
03426    case DAHDI_EVENT_ALARM:
03427       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03428          event2str(event), event, linkset->span, which);
03429       sig_ss7_link_alarm(linkset, which);
03430       break;
03431    case DAHDI_EVENT_NOALARM:
03432       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03433          event2str(event), event, linkset->span, which);
03434       sig_ss7_link_noalarm(linkset, which);
03435       break;
03436    default:
03437       ast_log(LOG_NOTICE, "SS7 got event: %s(%d) on span %d/%d\n",
03438          event2str(event), event, linkset->span, which);
03439       break;
03440    }
03441 }
03442 #endif   /* defined(HAVE_SS7) */
03443 
03444 #if defined(HAVE_SS7)
03445 static void my_ss7_set_loopback(void *pvt, int enable)
03446 {
03447    struct dahdi_pvt *p = pvt;
03448 
03449    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
03450       ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel,
03451          strerror(errno));
03452    }
03453 }
03454 #endif   /* defined(HAVE_SS7) */
03455 
03456 #if defined(HAVE_SS7)
03457 /*!
03458  * \internal
03459  * \brief Create a new asterisk channel structure for SS7.
03460  * \since 1.8
03461  *
03462  * \param pvt Private channel structure.
03463  * \param state Initial state of new channel.
03464  * \param law Combanding law to use.
03465  * \param exten Dialplan extension for incoming call.
03466  * \param requestor Channel requesting this new channel.
03467  *
03468  * \retval ast_channel on success.
03469  * \retval NULL on error.
03470  */
03471 static struct ast_channel *my_new_ss7_ast_channel(void *pvt, int state, enum sig_ss7_law law, char *exten, const struct ast_channel *requestor)
03472 {
03473    struct dahdi_pvt *p = pvt;
03474    int audio;
03475    int newlaw;
03476 
03477    /* Set to audio mode at this point */
03478    audio = 1;
03479    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1)
03480       ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
03481          p->channel, audio, strerror(errno));
03482 
03483    if (law != SIG_SS7_DEFLAW) {
03484       dahdi_setlaw(p->subs[SUB_REAL].dfd,
03485          (law == SIG_SS7_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
03486    }
03487 
03488    ast_copy_string(p->exten, exten, sizeof(p->exten));
03489 
03490    newlaw = -1;
03491    switch (law) {
03492    case SIG_SS7_DEFLAW:
03493       newlaw = 0;
03494       break;
03495    case SIG_SS7_ALAW:
03496       newlaw = DAHDI_LAW_ALAW;
03497       break;
03498    case SIG_SS7_ULAW:
03499       newlaw = DAHDI_LAW_MULAW;
03500       break;
03501    }
03502    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
03503 }
03504 #endif   /* defined(HAVE_SS7) */
03505 
03506 #if defined(HAVE_SS7)
03507 static int sig_ss7_tone_to_dahditone(enum sig_ss7_tone tone)
03508 {
03509    switch (tone) {
03510    case SIG_SS7_TONE_RINGTONE:
03511       return DAHDI_TONE_RINGTONE;
03512    case SIG_SS7_TONE_STUTTER:
03513       return DAHDI_TONE_STUTTER;
03514    case SIG_SS7_TONE_CONGESTION:
03515       return DAHDI_TONE_CONGESTION;
03516    case SIG_SS7_TONE_DIALTONE:
03517       return DAHDI_TONE_DIALTONE;
03518    case SIG_SS7_TONE_DIALRECALL:
03519       return DAHDI_TONE_DIALRECALL;
03520    case SIG_SS7_TONE_INFO:
03521       return DAHDI_TONE_INFO;
03522    case SIG_SS7_TONE_BUSY:
03523       return DAHDI_TONE_BUSY;
03524    default:
03525       return -1;
03526    }
03527 }
03528 #endif   /* defined(HAVE_SS7) */
03529 
03530 #if defined(HAVE_SS7)
03531 static int my_ss7_play_tone(void *pvt, enum sig_ss7_tone tone)
03532 {
03533    struct dahdi_pvt *p = pvt;
03534 
03535    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_ss7_tone_to_dahditone(tone));
03536 }
03537 #endif   /* defined(HAVE_SS7) */
03538 
03539 #if defined(HAVE_SS7)
03540 static struct sig_ss7_callback dahdi_ss7_callbacks =
03541 {
03542    .lock_private = my_lock_private,
03543    .unlock_private = my_unlock_private,
03544 
03545    .set_echocanceller = my_set_echocanceller,
03546    .set_loopback = my_ss7_set_loopback,
03547 
03548    .new_ast_channel = my_new_ss7_ast_channel,
03549    .play_tone = my_ss7_play_tone,
03550 
03551    .handle_link_exception = my_handle_link_exception,
03552    .set_alarm = my_set_alarm,
03553    .set_dialing = my_set_dialing,
03554    .set_outgoing = my_set_outgoing,
03555    .set_digital = my_set_digital,
03556    .set_inservice = my_set_inservice,
03557    .set_locallyblocked = my_set_locallyblocked,
03558    .set_remotelyblocked = my_set_remotelyblocked,
03559    .set_callerid = my_set_callerid,
03560    .set_dnid = my_set_dnid,
03561    .open_media = my_pri_ss7_open_media,
03562 };
03563 #endif   /* defined(HAVE_SS7) */
03564 
03565 /*!
03566  * \brief Send MWI state change
03567  *
03568  * \arg mailbox_full This is the mailbox associated with the FXO line that the
03569  *      MWI state has changed on.
03570  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
03571  *      whether there are messages waiting or not.
03572  *
03573  *  \return nothing
03574  *
03575  * This function does two things:
03576  *
03577  * 1) It generates an internal Asterisk event notifying any other module that
03578  *    cares about MWI that the state of a mailbox has changed.
03579  *
03580  * 2) It runs the script specified by the mwimonitornotify option to allow
03581  *    some custom handling of the state change.
03582  */
03583 static void notify_message(char *mailbox_full, int thereornot)
03584 {
03585    char s[sizeof(mwimonitornotify) + 80];
03586    struct ast_event *event;
03587    char *mailbox, *context;
03588 
03589    /* Strip off @default */
03590    context = mailbox = ast_strdupa(mailbox_full);
03591    strsep(&context, "@");
03592    if (ast_strlen_zero(context))
03593       context = "default";
03594 
03595    if (!(event = ast_event_new(AST_EVENT_MWI,
03596          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
03597          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
03598          AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03599          AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03600          AST_EVENT_IE_END))) {
03601       return;
03602    }
03603 
03604    ast_event_queue_and_cache(event);
03605 
03606    if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
03607       snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
03608       ast_safe_system(s);
03609    }
03610 }
03611 
03612 static void my_handle_notify_message(struct ast_channel *chan, void *pvt, int cid_flags, int neon_mwievent)
03613 {
03614    struct dahdi_pvt *p = pvt;
03615 
03616    if (neon_mwievent > -1 && !p->mwimonitor_neon)
03617       return;
03618 
03619    if (neon_mwievent == ANALOG_EVENT_NEONMWI_ACTIVE || cid_flags & CID_MSGWAITING) {
03620       ast_log(LOG_NOTICE, "MWI: Channel %d message waiting, mailbox %s\n", p->channel, p->mailbox);
03621       notify_message(p->mailbox, 1);
03622    } else if (neon_mwievent == ANALOG_EVENT_NEONMWI_INACTIVE || cid_flags & CID_NOMSGWAITING) {
03623       ast_log(LOG_NOTICE, "MWI: Channel %d no message waiting, mailbox %s\n", p->channel, p->mailbox);
03624       notify_message(p->mailbox, 0);
03625    }
03626    /* If the CID had Message waiting payload, assume that this for MWI only and hangup the call */
03627    /* If generated using Ring Pulse Alert, then ring has been answered as a call and needs to be hungup */
03628    if (neon_mwievent == -1 && p->mwimonitor_rpas) {
03629       ast_hangup(chan);
03630       return;
03631    }
03632 }
03633 
03634 static int my_have_progressdetect(void *pvt)
03635 {
03636    struct dahdi_pvt *p = pvt;
03637 
03638    if ((p->callprogress & CALLPROGRESS_PROGRESS)
03639       && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
03640       return 1;
03641    } else {
03642       /* Don't have progress detection. */
03643       return 0;
03644    }
03645 }
03646 
03647 static struct analog_callback dahdi_analog_callbacks =
03648 {
03649    .play_tone = my_play_tone,
03650    .get_event = my_get_event,
03651    .wait_event = my_wait_event,
03652    .is_off_hook = my_is_off_hook,
03653    .set_echocanceller = my_set_echocanceller,
03654    .ring = my_ring,
03655    .flash = my_flash,
03656    .off_hook = my_off_hook,
03657    .dial_digits = my_dial_digits,
03658    .train_echocanceller = my_train_echocanceller,
03659    .on_hook = my_on_hook,
03660    .is_dialing = my_is_dialing,
03661    .allocate_sub = my_allocate_sub,
03662    .unallocate_sub = my_unallocate_sub,
03663    .swap_subs = my_swap_subchannels,
03664    .has_voicemail = my_has_voicemail,
03665    .check_for_conference = my_check_for_conference,
03666    .conf_add = my_conf_add,
03667    .conf_del = my_conf_del,
03668    .complete_conference_update = my_complete_conference_update,
03669    .start = my_start,
03670    .all_subchannels_hungup = my_all_subchannels_hungup,
03671    .lock_private = my_lock_private,
03672    .unlock_private = my_unlock_private,
03673    .deadlock_avoidance_private = my_deadlock_avoidance_private,
03674    .handle_dtmf = my_handle_dtmf,
03675    .wink = my_wink,
03676    .new_ast_channel = my_new_analog_ast_channel,
03677    .dsp_set_digitmode = my_dsp_set_digitmode,
03678    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03679    .send_callerid = my_send_callerid,
03680    .callwait = my_callwait,
03681    .stop_callwait = my_stop_callwait,
03682    .get_callerid = my_get_callerid,
03683    .start_cid_detect = my_start_cid_detect,
03684    .stop_cid_detect = my_stop_cid_detect,
03685    .handle_notify_message = my_handle_notify_message,
03686    .increase_ss_count = my_increase_ss_count,
03687    .decrease_ss_count = my_decrease_ss_count,
03688    .distinctive_ring = my_distinctive_ring,
03689    .set_linear_mode = my_set_linear_mode,
03690    .set_inthreeway = my_set_inthreeway,
03691    .get_and_handle_alarms = my_get_and_handle_alarms,
03692    .get_sigpvt_bridged_channel = my_get_sigpvt_bridged_channel,
03693    .get_sub_fd = my_get_sub_fd,
03694    .set_cadence = my_set_cadence,
03695    .set_alarm = my_set_alarm,
03696    .set_dialing = my_set_dialing,
03697    .set_outgoing = my_set_outgoing,
03698    .set_ringtimeout = my_set_ringtimeout,
03699    .set_waitingfordt = my_set_waitingfordt,
03700    .check_waitingfordt = my_check_waitingfordt,
03701    .set_confirmanswer = my_set_confirmanswer,
03702    .check_confirmanswer = my_check_confirmanswer,
03703    .set_callwaiting = my_set_callwaiting,
03704    .cancel_cidspill = my_cancel_cidspill,
03705    .confmute = my_confmute,
03706    .set_pulsedial = my_set_pulsedial,
03707    .set_new_owner = my_set_new_owner,
03708    .get_orig_dialstring = my_get_orig_dialstring,
03709    .set_needringing = my_set_needringing,
03710    .set_polarity = my_set_polarity,
03711    .start_polarityswitch = my_start_polarityswitch,
03712    .answer_polarityswitch = my_answer_polarityswitch,
03713    .hangup_polarityswitch = my_hangup_polarityswitch,
03714    .have_progressdetect = my_have_progressdetect,
03715 };
03716 
03717 /*! Round robin search locations. */
03718 static struct dahdi_pvt *round_robin[32];
03719 
03720 #define dahdi_get_index(ast, p, nullok)   _dahdi_get_index(ast, p, nullok, __PRETTY_FUNCTION__, __LINE__)
03721 static int _dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok, const char *fname, unsigned long line)
03722 {
03723    int res;
03724    if (p->subs[SUB_REAL].owner == ast)
03725       res = 0;
03726    else if (p->subs[SUB_CALLWAIT].owner == ast)
03727       res = 1;
03728    else if (p->subs[SUB_THREEWAY].owner == ast)
03729       res = 2;
03730    else {
03731       res = -1;
03732       if (!nullok)
03733          ast_log(LOG_WARNING,
03734             "Unable to get index for '%s' on channel %d (%s(), line %lu)\n",
03735             ast ? ast->name : "", p->channel, fname, line);
03736    }
03737    return res;
03738 }
03739 
03740 /*!
03741  * \internal
03742  * \brief Obtain the specified subchannel owner lock if the owner exists.
03743  *
03744  * \param pvt Channel private struct.
03745  * \param sub_idx Subchannel owner to lock.
03746  *
03747  * \note Assumes the pvt->lock is already obtained.
03748  *
03749  * \note
03750  * Because deadlock avoidance may have been necessary, you need to confirm
03751  * the state of things before continuing.
03752  *
03753  * \return Nothing
03754  */
03755 static void dahdi_lock_sub_owner(struct dahdi_pvt *pvt, int sub_idx)
03756 {
03757    for (;;) {
03758       if (!pvt->subs[sub_idx].owner) {
03759          /* No subchannel owner pointer */
03760          break;
03761       }
03762       if (!ast_channel_trylock(pvt->subs[sub_idx].owner)) {
03763          /* Got subchannel owner lock */
03764          break;
03765       }
03766       /* We must unlock the private to avoid the possibility of a deadlock */
03767       DEADLOCK_AVOIDANCE(&pvt->lock);
03768    }
03769 }
03770 
03771 static void wakeup_sub(struct dahdi_pvt *p, int a)
03772 {
03773    dahdi_lock_sub_owner(p, a);
03774    if (p->subs[a].owner) {
03775       ast_queue_frame(p->subs[a].owner, &ast_null_frame);
03776       ast_channel_unlock(p->subs[a].owner);
03777    }
03778 }
03779 
03780 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f)
03781 {
03782    for (;;) {
03783       if (p->owner) {
03784          if (ast_channel_trylock(p->owner)) {
03785             DEADLOCK_AVOIDANCE(&p->lock);
03786          } else {
03787             ast_queue_frame(p->owner, f);
03788             ast_channel_unlock(p->owner);
03789             break;
03790          }
03791       } else
03792          break;
03793    }
03794 }
03795 
03796 static void handle_clear_alarms(struct dahdi_pvt *p)
03797 {
03798 #if defined(HAVE_PRI)
03799    if (dahdi_sig_pri_lib_handles(p->sig) && sig_pri_is_alarm_ignored(p->pri)) {
03800       return;
03801    }
03802 #endif   /* defined(HAVE_PRI) */
03803 
03804    if (report_alarms & REPORT_CHANNEL_ALARMS) {
03805       ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
03806       manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
03807    }
03808    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
03809       ast_log(LOG_NOTICE, "Alarm cleared on span %d\n", p->span);
03810       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarmClear", "Span: %d\r\n", p->span);
03811    }
03812 }
03813 
03814 #ifdef HAVE_OPENR2
03815 
03816 static int dahdi_r2_answer(struct dahdi_pvt *p)
03817 {
03818    int res = 0;
03819    /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
03820    * and does not has support for openr2_chan_answer_call_with_mode
03821    *  */
03822 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
03823    const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
03824    int wants_double_answer = ast_true(double_answer) ? 1 : 0;
03825    if (!double_answer) {
03826       /* this still can result in double answer if the channel context
03827       * was configured that way */
03828       res = openr2_chan_answer_call(p->r2chan);
03829    } else if (wants_double_answer) {
03830       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
03831    } else {
03832       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
03833    }
03834 #else
03835    res = openr2_chan_answer_call(p->r2chan);
03836 #endif
03837    return res;
03838 }
03839 
03840 
03841 
03842 /* should be called with the ast_channel locked */
03843 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
03844 {
03845    openr2_calling_party_category_t cat;
03846    const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
03847    struct dahdi_pvt *p = c->tech_pvt;
03848    if (ast_strlen_zero(catstr)) {
03849       ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
03850             c->name, openr2_proto_get_category_string(p->mfcr2_category));
03851       return p->mfcr2_category;
03852    }
03853    if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
03854       ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
03855             catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
03856       return p->mfcr2_category;
03857    }
03858    ast_debug(1, "Using category %s\n", catstr);
03859    return cat;
03860 }
03861 
03862 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
03863 {
03864    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03865    ast_mutex_lock(&p->lock);
03866    if (p->mfcr2call) {
03867       ast_mutex_unlock(&p->lock);
03868       /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
03869          interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
03870          can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
03871          the other end will see our seize as a forced release and drop the call, we will see an invalid
03872          pattern that will be seen and treated as protocol error. */
03873       ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
03874       return;
03875    }
03876    p->mfcr2call = 1;
03877    /* better safe than sorry ... */
03878    p->cid_name[0] = '\0';
03879    p->cid_num[0] = '\0';
03880    p->cid_subaddr[0] = '\0';
03881    p->rdnis[0] = '\0';
03882    p->exten[0] = '\0';
03883    p->mfcr2_ani_index = '\0';
03884    p->mfcr2_dnis_index = '\0';
03885    p->mfcr2_dnis_matched = 0;
03886    p->mfcr2_answer_pending = 0;
03887    p->mfcr2_call_accepted = 0;
03888    ast_mutex_unlock(&p->lock);
03889    ast_verbose("New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
03890 }
03891 
03892 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
03893 {
03894    int res;
03895    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03896    ast_mutex_lock(&p->lock);
03897    p->inalarm = alarm ? 1 : 0;
03898    if (p->inalarm) {
03899       res = get_alarms(p);
03900       handle_alarms(p, res);
03901    } else {
03902       handle_clear_alarms(p);
03903    }
03904    ast_mutex_unlock(&p->lock);
03905 }
03906 
03907 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
03908 {
03909    ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
03910 }
03911 
03912 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
03913 {
03914    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03915    ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
03916    if (p->owner) {
03917       p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
03918       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03919    }
03920    ast_mutex_lock(&p->lock);
03921    p->mfcr2call = 0;
03922    ast_mutex_unlock(&p->lock);
03923 }
03924 
03925 static void dahdi_r2_disconnect_call(struct dahdi_pvt *p, openr2_call_disconnect_cause_t cause)
03926 {
03927    if (openr2_chan_disconnect_call(p->r2chan, cause)) {
03928       ast_log(LOG_NOTICE, "Bad! failed to disconnect call on channel %d with reason %s, hope for the best!\n",
03929          p->channel, openr2_proto_get_disconnect_string(cause));
03930       /* force the chan to idle and release the call flag now since we will not see a clean on_call_end */
03931       openr2_chan_set_idle(p->r2chan);
03932       ast_mutex_lock(&p->lock);
03933       p->mfcr2call = 0;
03934       ast_mutex_unlock(&p->lock);
03935    }
03936 }
03937 
03938 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
03939 {
03940    struct dahdi_pvt *p;
03941    struct ast_channel *c;
03942    ast_verbose("MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
03943          openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
03944          openr2_proto_get_category_string(category));
03945    p = openr2_chan_get_client_data(r2chan);
03946    /* if collect calls are not allowed and this is a collect call, reject it! */
03947    if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
03948       ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
03949       dahdi_r2_disconnect_call(p, OR2_CAUSE_COLLECT_CALL_REJECTED);
03950       return;
03951    }
03952    ast_mutex_lock(&p->lock);
03953    p->mfcr2_recvd_category = category;
03954    /* if we're not supposed to use CID, clear whatever we have */
03955    if (!p->use_callerid) {
03956       ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
03957       p->cid_num[0] = 0;
03958       p->cid_name[0] = 0;
03959    }
03960    /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
03961    if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
03962       ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
03963       p->exten[0] = 's';
03964       p->exten[1] = 0;
03965    }
03966    ast_mutex_unlock(&p->lock);
03967    if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
03968       ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
03969             p->channel, p->exten, p->context);
03970       dahdi_r2_disconnect_call(p, OR2_CAUSE_UNALLOCATED_NUMBER);
03971       return;
03972    }
03973    if (!p->mfcr2_accept_on_offer) {
03974       /* The user wants us to start the PBX thread right away without accepting the call first */
03975       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
03976       if (c) {
03977          /* Done here, don't disable reading now since we still need to generate MF tones to accept
03978             the call or reject it and detect the tone off condition of the other end, all of this
03979             will be done in the PBX thread now */
03980          return;
03981       }
03982       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
03983       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
03984    } else if (p->mfcr2_charge_calls) {
03985       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
03986       openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
03987    } else {
03988       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
03989       openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
03990    }
03991 }
03992 
03993 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
03994 {
03995    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03996    ast_verbose("MFC/R2 call end on channel %d\n", p->channel);
03997    ast_mutex_lock(&p->lock);
03998    p->mfcr2call = 0;
03999    ast_mutex_unlock(&p->lock);
04000 }
04001 
04002 static void dahdi_enable_ec(struct dahdi_pvt *p);
04003 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
04004 {
04005    struct dahdi_pvt *p = NULL;
04006    struct ast_channel *c = NULL;
04007    p = openr2_chan_get_client_data(r2chan);
04008    dahdi_enable_ec(p);
04009    p->mfcr2_call_accepted = 1;
04010    /* if it's an incoming call ... */
04011    if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
04012       ast_verbose("MFC/R2 call has been accepted on backward channel %d\n", openr2_chan_get_number(r2chan));
04013       /* If accept on offer is not set, it means at this point the PBX thread is already
04014          launched (was launched in the 'on call offered' handler) and therefore this callback
04015          is being executed already in the PBX thread rather than the monitor thread, don't launch
04016          any other thread, just disable the openr2 reading and answer the call if needed */
04017       if (!p->mfcr2_accept_on_offer) {
04018          openr2_chan_disable_read(r2chan);
04019          if (p->mfcr2_answer_pending) {
04020             ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
04021             dahdi_r2_answer(p);
04022          }
04023          return;
04024       }
04025       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
04026       if (c) {
04027          /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
04028             library to forget about it */
04029          openr2_chan_disable_read(r2chan);
04030          return;
04031       }
04032       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
04033       /* failed to create the channel, bail out and report it as an out of order line */
04034       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
04035       return;
04036    }
04037    /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
04038    ast_verbose("MFC/R2 call has been accepted on forward channel %d\n", p->channel);
04039    p->subs[SUB_REAL].needringing = 1;
04040    p->dialing = 0;
04041    /* chan_dahdi will take care of reading from now on in the PBX thread, tell the library to forget about it */
04042    openr2_chan_disable_read(r2chan);
04043 }
04044 
04045 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
04046 {
04047    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04048    ast_verbose("MFC/R2 call has been answered on channel %d\n", openr2_chan_get_number(r2chan));
04049    p->subs[SUB_REAL].needanswer = 1;
04050 }
04051 
04052 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
04053 {
04054    /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
04055 }
04056 
04057 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
04058 {
04059    switch (cause) {
04060    case OR2_CAUSE_BUSY_NUMBER:
04061       return AST_CAUSE_BUSY;
04062    case OR2_CAUSE_NETWORK_CONGESTION:
04063       return AST_CAUSE_CONGESTION;
04064    case OR2_CAUSE_OUT_OF_ORDER:
04065       return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
04066    case OR2_CAUSE_UNALLOCATED_NUMBER:
04067       return AST_CAUSE_UNREGISTERED;
04068    case OR2_CAUSE_NO_ANSWER:
04069       return AST_CAUSE_NO_ANSWER;
04070    case OR2_CAUSE_NORMAL_CLEARING:
04071       return AST_CAUSE_NORMAL_CLEARING;
04072    case OR2_CAUSE_UNSPECIFIED:
04073    default:
04074       return AST_CAUSE_NOTDEFINED;
04075    }
04076 }
04077 
04078 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
04079 {
04080    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04081    ast_verbose("MFC/R2 call disconnected on channel %d\n", openr2_chan_get_number(r2chan));
04082    ast_mutex_lock(&p->lock);
04083    if (!p->owner) {
04084       ast_mutex_unlock(&p->lock);
04085       /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
04086       dahdi_r2_disconnect_call(p, OR2_CAUSE_NORMAL_CLEARING);
04087       return;
04088    }
04089    /* when we have an owner we don't call dahdi_r2_disconnect_call here, that will
04090       be done in dahdi_hangup */
04091    if (p->owner->_state == AST_STATE_UP) {
04092       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04093       ast_mutex_unlock(&p->lock);
04094    } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
04095       /* being the forward side we must report what happened to the call to whoever requested it */
04096       switch (cause) {
04097       case OR2_CAUSE_BUSY_NUMBER:
04098          p->subs[SUB_REAL].needbusy = 1;
04099          break;
04100       case OR2_CAUSE_NETWORK_CONGESTION:
04101       case OR2_CAUSE_OUT_OF_ORDER:
04102       case OR2_CAUSE_UNALLOCATED_NUMBER:
04103       case OR2_CAUSE_NO_ANSWER:
04104       case OR2_CAUSE_UNSPECIFIED:
04105       case OR2_CAUSE_NORMAL_CLEARING:
04106          p->subs[SUB_REAL].needcongestion = 1;
04107          break;
04108       default:
04109          p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04110       }
04111       ast_mutex_unlock(&p->lock);
04112    } else {
04113       ast_mutex_unlock(&p->lock);
04114       /* being the backward side and not UP yet, we only need to request hangup */
04115       /* TODO: what about doing this same thing when were AST_STATE_UP? */
04116       ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
04117    }
04118 }
04119 
04120 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
04121 {
04122    switch (level) {
04123    case OR2_LOG_NOTICE:
04124       ast_verbose("%s", logmessage);
04125       break;
04126    case OR2_LOG_WARNING:
04127       ast_log(LOG_WARNING, "%s", logmessage);
04128       break;
04129    case OR2_LOG_ERROR:
04130       ast_log(LOG_ERROR, "%s", logmessage);
04131       break;
04132    case OR2_LOG_STACK_TRACE:
04133    case OR2_LOG_MF_TRACE:
04134    case OR2_LOG_CAS_TRACE:
04135    case OR2_LOG_DEBUG:
04136    case OR2_LOG_EX_DEBUG:
04137       ast_log(LOG_DEBUG, "%s", logmessage);
04138       break;
04139    default:
04140       ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
04141       ast_log(LOG_DEBUG, "%s", logmessage);
04142       break;
04143    }
04144 }
04145 
04146 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
04147 {
04148    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04149    ast_mutex_lock(&p->lock);
04150    p->remotelyblocked = 1;
04151    ast_mutex_unlock(&p->lock);
04152    ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
04153 }
04154 
04155 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
04156 {
04157    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04158    ast_mutex_lock(&p->lock);
04159    p->remotelyblocked = 0;
04160    ast_mutex_unlock(&p->lock);
04161    ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
04162 }
04163 
04164 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
04165    __attribute__((format (printf, 3, 0)));
04166 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
04167 {
04168 #define CONTEXT_TAG "Context - "
04169    char logmsg[256];
04170    char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
04171    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
04172    snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
04173    dahdi_r2_write_log(level, completemsg);
04174 #undef CONTEXT_TAG
04175 }
04176 
04177 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
04178    __attribute__((format (printf, 3, 0)));
04179 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
04180 {
04181 #define CHAN_TAG "Chan "
04182    char logmsg[256];
04183    char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
04184    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
04185    snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
04186    dahdi_r2_write_log(level, completemsg);
04187 }
04188 
04189 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
04190 {
04191    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04192    /* if 'immediate' is set, let's stop requesting DNIS */
04193    if (p->immediate) {
04194       return 0;
04195    }
04196    p->exten[p->mfcr2_dnis_index] = digit;
04197    p->rdnis[p->mfcr2_dnis_index] = digit;
04198    p->mfcr2_dnis_index++;
04199    p->exten[p->mfcr2_dnis_index] = 0;
04200    p->rdnis[p->mfcr2_dnis_index] = 0;
04201    /* if the DNIS is a match and cannot match more, stop requesting DNIS */
04202    if ((p->mfcr2_dnis_matched ||
04203        (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
04204        !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
04205       return 0;
04206    }
04207    /* otherwise keep going */
04208    return 1;
04209 }
04210 
04211 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
04212 {
04213    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04214    p->cid_num[p->mfcr2_ani_index] = digit;
04215    p->cid_name[p->mfcr2_ani_index] = digit;
04216    p->mfcr2_ani_index++;
04217    p->cid_num[p->mfcr2_ani_index] = 0;
04218    p->cid_name[p->mfcr2_ani_index] = 0;
04219 }
04220 
04221 static void dahdi_r2_on_billing_pulse_received(openr2_chan_t *r2chan)
04222 {
04223    ast_verbose("MFC/R2 billing pulse received on channel %d\n", openr2_chan_get_number(r2chan));
04224 }
04225 
04226 static openr2_event_interface_t dahdi_r2_event_iface = {
04227    .on_call_init = dahdi_r2_on_call_init,
04228    .on_call_offered = dahdi_r2_on_call_offered,
04229    .on_call_accepted = dahdi_r2_on_call_accepted,
04230    .on_call_answered = dahdi_r2_on_call_answered,
04231    .on_call_disconnect = dahdi_r2_on_call_disconnect,
04232    .on_call_end = dahdi_r2_on_call_end,
04233    .on_call_read = dahdi_r2_on_call_read,
04234    .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
04235    .on_os_error = dahdi_r2_on_os_error,
04236    .on_protocol_error = dahdi_r2_on_protocol_error,
04237    .on_line_blocked = dahdi_r2_on_line_blocked,
04238    .on_line_idle = dahdi_r2_on_line_idle,
04239    /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
04240    .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
04241    .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
04242    .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
04243    /* so far we do nothing with billing pulses */
04244    .on_billing_pulse_received = dahdi_r2_on_billing_pulse_received
04245 };
04246 
04247 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
04248 {
04249    return AST_ALAW(sample);
04250 }
04251 
04252 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
04253 {
04254    return AST_LIN2A(sample);
04255 }
04256 
04257 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
04258    dahdi_r2_alaw_to_linear,
04259    dahdi_r2_linear_to_alaw
04260 };
04261 
04262 #endif /* HAVE_OPENR2 */
04263 
04264 static void swap_subs(struct dahdi_pvt *p, int a, int b)
04265 {
04266    int tchan;
04267    int tinthreeway;
04268    struct ast_channel *towner;
04269 
04270    ast_debug(1, "Swapping %d and %d\n", a, b);
04271 
04272    tchan = p->subs[a].chan;
04273    towner = p->subs[a].owner;
04274    tinthreeway = p->subs[a].inthreeway;
04275 
04276    p->subs[a].chan = p->subs[b].chan;
04277    p->subs[a].owner = p->subs[b].owner;
04278    p->subs[a].inthreeway = p->subs[b].inthreeway;
04279 
04280    p->subs[b].chan = tchan;
04281    p->subs[b].owner = towner;
04282    p->subs[b].inthreeway = tinthreeway;
04283 
04284    if (p->subs[a].owner)
04285       ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
04286    if (p->subs[b].owner)
04287       ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
04288    wakeup_sub(p, a);
04289    wakeup_sub(p, b);
04290 }
04291 
04292 static int dahdi_open(char *fn)
04293 {
04294    int fd;
04295    int isnum;
04296    int chan = 0;
04297    int bs;
04298    int x;
04299    isnum = 1;
04300    for (x = 0; x < strlen(fn); x++) {
04301       if (!isdigit(fn[x])) {
04302          isnum = 0;
04303          break;
04304       }
04305    }
04306    if (isnum) {
04307       chan = atoi(fn);
04308       if (chan < 1) {
04309          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
04310          return -1;
04311       }
04312       fn = "/dev/dahdi/channel";
04313    }
04314    fd = open(fn, O_RDWR | O_NONBLOCK);
04315    if (fd < 0) {
04316       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
04317       return -1;
04318    }
04319    if (chan) {
04320       if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
04321          x = errno;
04322          close(fd);
04323          errno = x;
04324          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
04325          return -1;
04326       }
04327    }
04328    bs = READ_SIZE;
04329    if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
04330       ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
04331       x = errno;
04332       close(fd);
04333       errno = x;
04334       return -1;
04335    }
04336    return fd;
04337 }
04338 
04339 static void dahdi_close(int fd)
04340 {
04341    if (fd > 0)
04342       close(fd);
04343 }
04344 
04345 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
04346 {
04347    dahdi_close(chan_pvt->subs[sub_num].dfd);
04348    chan_pvt->subs[sub_num].dfd = -1;
04349 }
04350 
04351 #if defined(HAVE_PRI)
04352 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
04353 {
04354    dahdi_close(pri->pri.fds[fd_num]);
04355    pri->pri.fds[fd_num] = -1;
04356 }
04357 #endif   /* defined(HAVE_PRI) */
04358 
04359 #if defined(HAVE_SS7)
04360 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
04361 {
04362    dahdi_close(ss7->ss7.fds[fd_num]);
04363    ss7->ss7.fds[fd_num] = -1;
04364 }
04365 #endif   /* defined(HAVE_SS7) */
04366 
04367 static int dahdi_setlinear(int dfd, int linear)
04368 {
04369    return ioctl(dfd, DAHDI_SETLINEAR, &linear);
04370 }
04371 
04372 
04373 static int alloc_sub(struct dahdi_pvt *p, int x)
04374 {
04375    struct dahdi_bufferinfo bi;
04376    int res;
04377    if (p->subs[x].dfd >= 0) {
04378       ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
04379       return -1;
04380    }
04381 
04382    p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
04383    if (p->subs[x].dfd <= -1) {
04384       ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
04385       return -1;
04386    }
04387 
04388    res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
04389    if (!res) {
04390       bi.txbufpolicy = p->buf_policy;
04391       bi.rxbufpolicy = p->buf_policy;
04392       bi.numbufs = p->buf_no;
04393       res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
04394       if (res < 0) {
04395          ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
04396       }
04397    } else
04398       ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
04399 
04400    if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
04401       ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
04402       dahdi_close_sub(p, x);
04403       p->subs[x].dfd = -1;
04404       return -1;
04405    }
04406    ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
04407    return 0;
04408 }
04409 
04410 static int unalloc_sub(struct dahdi_pvt *p, int x)
04411 {
04412    if (!x) {
04413       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
04414       return -1;
04415    }
04416    ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
04417    dahdi_close_sub(p, x);
04418    p->subs[x].linear = 0;
04419    p->subs[x].chan = 0;
04420    p->subs[x].owner = NULL;
04421    p->subs[x].inthreeway = 0;
04422    p->polarity = POLARITY_IDLE;
04423    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
04424    return 0;
04425 }
04426 
04427 static int digit_to_dtmfindex(char digit)
04428 {
04429    if (isdigit(digit))
04430       return DAHDI_TONE_DTMF_BASE + (digit - '0');
04431    else if (digit >= 'A' && digit <= 'D')
04432       return DAHDI_TONE_DTMF_A + (digit - 'A');
04433    else if (digit >= 'a' && digit <= 'd')
04434       return DAHDI_TONE_DTMF_A + (digit - 'a');
04435    else if (digit == '*')
04436       return DAHDI_TONE_DTMF_s;
04437    else if (digit == '#')
04438       return DAHDI_TONE_DTMF_p;
04439    else
04440       return -1;
04441 }
04442 
04443 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
04444 {
04445    struct dahdi_pvt *pvt;
04446    int idx;
04447    int dtmf = -1;
04448    int res;
04449 
04450    pvt = chan->tech_pvt;
04451 
04452    ast_mutex_lock(&pvt->lock);
04453 
04454    idx = dahdi_get_index(chan, pvt, 0);
04455 
04456    if ((idx != SUB_REAL) || !pvt->owner)
04457       goto out;
04458 
04459 #ifdef HAVE_PRI
04460    switch (pvt->sig) {
04461    case SIG_PRI_LIB_HANDLE_CASES:
04462       res = sig_pri_digit_begin(pvt->sig_pvt, chan, digit);
04463       if (!res)
04464          goto out;
04465       break;
04466    default:
04467       break;
04468    }
04469 #endif
04470    if ((dtmf = digit_to_dtmfindex(digit)) == -1)
04471       goto out;
04472 
04473    if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
04474       struct dahdi_dialoperation zo = {
04475          .op = DAHDI_DIAL_OP_APPEND,
04476       };
04477 
04478       zo.dialstr[0] = 'T';
04479       zo.dialstr[1] = digit;
04480       zo.dialstr[2] = '\0';
04481       if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
04482          ast_log(LOG_WARNING, "Channel %s couldn't dial digit %c: %s\n",
04483             chan->name, digit, strerror(errno));
04484       else
04485          pvt->dialing = 1;
04486    } else {
04487       ast_debug(1, "Channel %s started VLDTMF digit '%c'\n",
04488          chan->name, digit);
04489       pvt->dialing = 1;
04490       pvt->begindigit = digit;
04491    }
04492 
04493 out:
04494    ast_mutex_unlock(&pvt->lock);
04495 
04496    return 0;
04497 }
04498 
04499 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
04500 {
04501    struct dahdi_pvt *pvt;
04502    int res = 0;
04503    int idx;
04504    int x;
04505 
04506    pvt = chan->tech_pvt;
04507 
04508    ast_mutex_lock(&pvt->lock);
04509 
04510    idx = dahdi_get_index(chan, pvt, 0);
04511 
04512    if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
04513       goto out;
04514 
04515 #ifdef HAVE_PRI
04516    /* This means that the digit was already sent via PRI signalling */
04517    if (dahdi_sig_pri_lib_handles(pvt->sig) && !pvt->begindigit) {
04518       goto out;
04519    }
04520 #endif
04521 
04522    if (pvt->begindigit) {
04523       x = -1;
04524       ast_debug(1, "Channel %s ending VLDTMF digit '%c'\n",
04525          chan->name, digit);
04526       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
04527       pvt->dialing = 0;
04528       pvt->begindigit = 0;
04529    }
04530 
04531 out:
04532    ast_mutex_unlock(&pvt->lock);
04533 
04534    return res;
04535 }
04536 
04537 static const char * const events[] = {
04538    "No event",
04539    "On hook",
04540    "Ring/Answered",
04541    "Wink/Flash",
04542    "Alarm",
04543    "No more alarm",
04544    "HDLC Abort",
04545    "HDLC Overrun",
04546    "HDLC Bad FCS",
04547    "Dial Complete",
04548    "Ringer On",
04549    "Ringer Off",
04550    "Hook Transition Complete",
04551    "Bits Changed",
04552    "Pulse Start",
04553    "Timer Expired",
04554    "Timer Ping",
04555    "Polarity Reversal",
04556    "Ring Begin",
04557 };
04558 
04559 static struct {
04560    int alarm;
04561    char *name;
04562 } alarms[] = {
04563    { DAHDI_ALARM_RED, "Red Alarm" },
04564    { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
04565    { DAHDI_ALARM_BLUE, "Blue Alarm" },
04566    { DAHDI_ALARM_RECOVER, "Recovering" },
04567    { DAHDI_ALARM_LOOPBACK, "Loopback" },
04568    { DAHDI_ALARM_NOTOPEN, "Not Open" },
04569    { DAHDI_ALARM_NONE, "None" },
04570 };
04571 
04572 static char *alarm2str(int alm)
04573 {
04574    int x;
04575    for (x = 0; x < ARRAY_LEN(alarms); x++) {
04576       if (alarms[x].alarm & alm)
04577          return alarms[x].name;
04578    }
04579    return alm ? "Unknown Alarm" : "No Alarm";
04580 }
04581 
04582 static const char *event2str(int event)
04583 {
04584    static char buf[256];
04585    if ((event < (ARRAY_LEN(events))) && (event > -1))
04586       return events[event];
04587    sprintf(buf, "Event %d", event); /* safe */
04588    return buf;
04589 }
04590 
04591 static char *dahdi_sig2str(int sig)
04592 {
04593    static char buf[256];
04594    switch (sig) {
04595    case SIG_EM:
04596       return "E & M Immediate";
04597    case SIG_EMWINK:
04598       return "E & M Wink";
04599    case SIG_EM_E1:
04600       return "E & M E1";
04601    case SIG_FEATD:
04602       return "Feature Group D (DTMF)";
04603    case SIG_FEATDMF:
04604       return "Feature Group D (MF)";
04605    case SIG_FEATDMF_TA:
04606       return "Feature Groud D (MF) Tandem Access";
04607    case SIG_FEATB:
04608       return "Feature Group B (MF)";
04609    case SIG_E911:
04610       return "E911 (MF)";
04611    case SIG_FGC_CAMA:
04612       return "FGC/CAMA (Dialpulse)";
04613    case SIG_FGC_CAMAMF:
04614       return "FGC/CAMA (MF)";
04615    case SIG_FXSLS:
04616       return "FXS Loopstart";
04617    case SIG_FXSGS:
04618       return "FXS Groundstart";
04619    case SIG_FXSKS:
04620       return "FXS Kewlstart";
04621    case SIG_FXOLS:
04622       return "FXO Loopstart";
04623    case SIG_FXOGS:
04624       return "FXO Groundstart";
04625    case SIG_FXOKS:
04626       return "FXO Kewlstart";
04627    case SIG_PRI:
04628       return "ISDN PRI";
04629    case SIG_BRI:
04630       return "ISDN BRI Point to Point";
04631    case SIG_BRI_PTMP:
04632       return "ISDN BRI Point to MultiPoint";
04633    case SIG_SS7:
04634       return "SS7";
04635    case SIG_MFCR2:
04636       return "MFC/R2";
04637    case SIG_SF:
04638       return "SF (Tone) Immediate";
04639    case SIG_SFWINK:
04640       return "SF (Tone) Wink";
04641    case SIG_SF_FEATD:
04642       return "SF (Tone) with Feature Group D (DTMF)";
04643    case SIG_SF_FEATDMF:
04644       return "SF (Tone) with Feature Group D (MF)";
04645    case SIG_SF_FEATB:
04646       return "SF (Tone) with Feature Group B (MF)";
04647    case 0:
04648       return "Pseudo";
04649    default:
04650       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
04651       return buf;
04652    }
04653 }
04654 
04655 #define sig2str dahdi_sig2str
04656 
04657 static int analog_lib_handles(int signalling, int radio, int oprmode)
04658 {
04659    switch (signalling) {
04660    case SIG_FXOLS:
04661    case SIG_FXOGS:
04662    case SIG_FXOKS:
04663    case SIG_FXSLS:
04664    case SIG_FXSGS:
04665    case SIG_FXSKS:
04666    case SIG_EMWINK:
04667    case SIG_EM:
04668    case SIG_EM_E1:
04669    case SIG_FEATD:
04670    case SIG_FEATDMF:
04671    case SIG_E911:
04672    case SIG_FGC_CAMA:
04673    case SIG_FGC_CAMAMF:
04674    case SIG_FEATB:
04675    case SIG_SFWINK:
04676    case SIG_SF:
04677    case SIG_SF_FEATD:
04678    case SIG_SF_FEATDMF:
04679    case SIG_FEATDMF_TA:
04680    case SIG_SF_FEATB:
04681       break;
04682    default:
04683       /* The rest of the function should cover the remainder of signalling types */
04684       return 0;
04685    }
04686 
04687    if (radio)
04688       return 0;
04689 
04690    if (oprmode)
04691       return 0;
04692 
04693    return 1;
04694 }
04695 
04696 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
04697 {
04698    /* If the conference already exists, and we're already in it
04699       don't bother doing anything */
04700    struct dahdi_confinfo zi;
04701 
04702    memset(&zi, 0, sizeof(zi));
04703    zi.chan = 0;
04704 
04705    if (slavechannel > 0) {
04706       /* If we have only one slave, do a digital mon */
04707       zi.confmode = DAHDI_CONF_DIGITALMON;
04708       zi.confno = slavechannel;
04709    } else {
04710       if (!idx) {
04711          /* Real-side and pseudo-side both participate in conference */
04712          zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
04713             DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
04714       } else
04715          zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
04716       zi.confno = p->confno;
04717    }
04718    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
04719       return 0;
04720    if (c->dfd < 0)
04721       return 0;
04722    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04723       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
04724       return -1;
04725    }
04726    if (slavechannel < 1) {
04727       p->confno = zi.confno;
04728    }
04729    c->curconf = zi;
04730    ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04731    return 0;
04732 }
04733 
04734 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
04735 {
04736    /* If they're listening to our channel, they're ours */
04737    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
04738       return 1;
04739    /* If they're a talker on our (allocated) conference, they're ours */
04740    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
04741       return 1;
04742    return 0;
04743 }
04744 
04745 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
04746 {
04747    struct dahdi_confinfo zi;
04748    if (/* Can't delete if there's no dfd */
04749       (c->dfd < 0) ||
04750       /* Don't delete from the conference if it's not our conference */
04751       !isourconf(p, c)
04752       /* Don't delete if we don't think it's conferenced at all (implied) */
04753       ) return 0;
04754    memset(&zi, 0, sizeof(zi));
04755    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04756       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
04757       return -1;
04758    }
04759    ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04760    memcpy(&c->curconf, &zi, sizeof(c->curconf));
04761    return 0;
04762 }
04763 
04764 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
04765 {
04766    int x;
04767    int useslavenative;
04768    struct dahdi_pvt *slave = NULL;
04769    /* Start out optimistic */
04770    useslavenative = 1;
04771    /* Update conference state in a stateless fashion */
04772    for (x = 0; x < 3; x++) {
04773       /* Any three-way calling makes slave native mode *definitely* out
04774          of the question */
04775       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
04776          useslavenative = 0;
04777    }
04778    /* If we don't have any 3-way calls, check to see if we have
04779       precisely one slave */
04780    if (useslavenative) {
04781       for (x = 0; x < MAX_SLAVES; x++) {
04782          if (p->slaves[x]) {
04783             if (slave) {
04784                /* Whoops already have a slave!  No
04785                   slave native and stop right away */
04786                slave = NULL;
04787                useslavenative = 0;
04788                break;
04789             } else {
04790                /* We have one slave so far */
04791                slave = p->slaves[x];
04792             }
04793          }
04794       }
04795    }
04796    /* If no slave, slave native definitely out */
04797    if (!slave)
04798       useslavenative = 0;
04799    else if (slave->law != p->law) {
04800       useslavenative = 0;
04801       slave = NULL;
04802    }
04803    if (out)
04804       *out = slave;
04805    return useslavenative;
04806 }
04807 
04808 static int reset_conf(struct dahdi_pvt *p)
04809 {
04810    p->confno = -1;
04811    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
04812    if (p->subs[SUB_REAL].dfd > -1) {
04813       struct dahdi_confinfo zi;
04814 
04815       memset(&zi, 0, sizeof(zi));
04816       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
04817          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
04818    }
04819    return 0;
04820 }
04821 
04822 static int update_conf(struct dahdi_pvt *p)
04823 {
04824    int needconf = 0;
04825    int x;
04826    int useslavenative;
04827    struct dahdi_pvt *slave = NULL;
04828 
04829    useslavenative = isslavenative(p, &slave);
04830    /* Start with the obvious, general stuff */
04831    for (x = 0; x < 3; x++) {
04832       /* Look for three way calls */
04833       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
04834          conf_add(p, &p->subs[x], x, 0);
04835          needconf++;
04836       } else {
04837          conf_del(p, &p->subs[x], x);
04838       }
04839    }
04840    /* If we have a slave, add him to our conference now. or DAX
04841       if this is slave native */
04842    for (x = 0; x < MAX_SLAVES; x++) {
04843       if (p->slaves[x]) {
04844          if (useslavenative)
04845             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
04846          else {
04847             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
04848             needconf++;
04849          }
04850       }
04851    }
04852    /* If we're supposed to be in there, do so now */
04853    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
04854       if (useslavenative)
04855          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
04856       else {
04857          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
04858          needconf++;
04859       }
04860    }
04861    /* If we have a master, add ourselves to his conference */
04862    if (p->master) {
04863       if (isslavenative(p->master, NULL)) {
04864          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
04865       } else {
04866          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
04867       }
04868    }
04869    if (!needconf) {
04870       /* Nobody is left (or should be left) in our conference.
04871          Kill it. */
04872       p->confno = -1;
04873    }
04874    ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
04875    return 0;
04876 }
04877 
04878 static void dahdi_enable_ec(struct dahdi_pvt *p)
04879 {
04880    int res;
04881    if (!p)
04882       return;
04883    if (p->echocanon) {
04884       ast_debug(1, "Echo cancellation already on\n");
04885       return;
04886    }
04887    if (p->digital) {
04888       ast_debug(1, "Echo cancellation isn't required on digital connection\n");
04889       return;
04890    }
04891    if (p->echocancel.head.tap_length) {
04892 #if defined(HAVE_PRI) || defined(HAVE_SS7)
04893       switch (p->sig) {
04894 #if defined(HAVE_PRI)
04895       case SIG_PRI_LIB_HANDLE_CASES:
04896          if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
04897             /*
04898              * PRI nobch pseudo channel.  Does not need ec anyway.
04899              * Does not handle ioctl(DAHDI_AUDIOMODE)
04900              */
04901             return;
04902          }
04903          /* Fall through */
04904 #endif   /* defined(HAVE_PRI) */
04905 #if defined(HAVE_SS7)
04906       case SIG_SS7:
04907 #endif   /* defined(HAVE_SS7) */
04908          {
04909             int x = 1;
04910 
04911             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
04912             if (res)
04913                ast_log(LOG_WARNING,
04914                   "Unable to enable audio mode on channel %d (%s)\n",
04915                   p->channel, strerror(errno));
04916          }
04917          break;
04918       default:
04919          break;
04920       }
04921 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
04922       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
04923       if (res) {
04924          ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
04925       } else {
04926          p->echocanon = 1;
04927          ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
04928       }
04929    } else
04930       ast_debug(1, "No echo cancellation requested\n");
04931 }
04932 
04933 static void dahdi_train_ec(struct dahdi_pvt *p)
04934 {
04935    int x;
04936    int res;
04937 
04938    if (p && p->echocanon && p->echotraining) {
04939       x = p->echotraining;
04940       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
04941       if (res)
04942          ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
04943       else
04944          ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
04945    } else {
04946       ast_debug(1, "No echo training requested\n");
04947    }
04948 }
04949 
04950 static void dahdi_disable_ec(struct dahdi_pvt *p)
04951 {
04952    int res;
04953 
04954    if (p->echocanon) {
04955       struct dahdi_echocanparams ecp = { .tap_length = 0 };
04956 
04957       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
04958 
04959       if (res)
04960          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
04961       else
04962          ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
04963    }
04964 
04965    p->echocanon = 0;
04966 }
04967 
04968 /* perform a dynamic range compression transform on the given sample */
04969 static int drc_sample(int sample, float drc)
04970 {
04971    float neg;
04972    float shallow, steep;
04973    float max = SHRT_MAX;
04974    
04975    neg = (sample < 0 ? -1 : 1);
04976    steep = drc*sample;
04977    shallow = neg*(max-max/drc)+(float)sample/drc;
04978    if (abs(steep) < abs(shallow)) {
04979       sample = steep;
04980    }
04981    else {
04982       sample = shallow;
04983    }
04984 
04985    return sample;
04986 }
04987 
04988 
04989 static void fill_txgain(struct dahdi_gains *g, float gain, float drc, int law)
04990 {
04991    int j;
04992    int k;
04993 
04994    float linear_gain = pow(10.0, gain / 20.0);
04995 
04996    switch (law) {
04997    case DAHDI_LAW_ALAW:
04998       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
04999          if (gain || drc) {
05000             k = AST_ALAW(j);
05001             if (drc) {
05002                k = drc_sample(k, drc);
05003             }
05004             k = (float)k*linear_gain;
05005             if (k > 32767) k = 32767;
05006             if (k < -32767) k = -32767;
05007             g->txgain[j] = AST_LIN2A(k);
05008          } else {
05009             g->txgain[j] = j;
05010          }
05011       }
05012       break;
05013    case DAHDI_LAW_MULAW:
05014       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
05015          if (gain || drc) {
05016             k = AST_MULAW(j);
05017             if (drc) {
05018                k = drc_sample(k, drc);
05019             }
05020             k = (float)k*linear_gain;
05021             if (k > 32767) k = 32767;
05022             if (k < -32767) k = -32767;
05023             g->txgain[j] = AST_LIN2MU(k);
05024 
05025          } else {
05026             g->txgain[j] = j;
05027          }
05028       }
05029       break;
05030    }
05031 }
05032 
05033 static void fill_rxgain(struct dahdi_gains *g, float gain, float drc, int law)
05034 {
05035    int j;
05036    int k;
05037    float linear_gain = pow(10.0, gain / 20.0);
05038 
05039    switch (law) {
05040    case DAHDI_LAW_ALAW:
05041       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
05042          if (gain || drc) {
05043             k = AST_ALAW(j);
05044             if (drc) {
05045                k = drc_sample(k, drc);
05046             }
05047             k = (float)k*linear_gain;
05048             if (k > 32767) k = 32767;
05049             if (k < -32767) k = -32767;
05050             g->rxgain[j] = AST_LIN2A(k);
05051          } else {
05052             g->rxgain[j] = j;
05053          }
05054       }
05055       break;
05056    case DAHDI_LAW_MULAW:
05057       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
05058          if (gain || drc) {
05059             k = AST_MULAW(j);
05060             if (drc) {
05061                k = drc_sample(k, drc);
05062             }
05063             k = (float)k*linear_gain;
05064             if (k > 32767) k = 32767;
05065             if (k < -32767) k = -32767;
05066             g->rxgain[j] = AST_LIN2MU(k);
05067          } else {
05068             g->rxgain[j] = j;
05069          }
05070       }
05071       break;
05072    }
05073 }
05074 
05075 static int set_actual_txgain(int fd, float gain, float drc, int law)
05076 {
05077    struct dahdi_gains g;
05078    int res;
05079 
05080    memset(&g, 0, sizeof(g));
05081    res = ioctl(fd, DAHDI_GETGAINS, &g);
05082    if (res) {
05083       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
05084       return res;
05085    }
05086 
05087    fill_txgain(&g, gain, drc, law);
05088 
05089    return ioctl(fd, DAHDI_SETGAINS, &g);
05090 }
05091 
05092 static int set_actual_rxgain(int fd, float gain, float drc, int law)
05093 {
05094    struct dahdi_gains g;
05095    int res;
05096 
05097    memset(&g, 0, sizeof(g));
05098    res = ioctl(fd, DAHDI_GETGAINS, &g);
05099    if (res) {
05100       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
05101       return res;
05102    }
05103 
05104    fill_rxgain(&g, gain, drc, law);
05105 
05106    return ioctl(fd, DAHDI_SETGAINS, &g);
05107 }
05108 
05109 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law)
05110 {
05111    return set_actual_txgain(fd, txgain, txdrc, law) | set_actual_rxgain(fd, rxgain, rxdrc, law);
05112 }
05113 
05114 static int bump_gains(struct dahdi_pvt *p)
05115 {
05116    int res;
05117 
05118    /* Bump receive gain by value stored in cid_rxgain */
05119    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain + p->cid_rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05120    if (res) {
05121       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
05122       return -1;
05123    }
05124 
05125    return 0;
05126 }
05127 
05128 static int restore_gains(struct dahdi_pvt *p)
05129 {
05130    int res;
05131 
05132    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05133    if (res) {
05134       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
05135       return -1;
05136    }
05137 
05138    return 0;
05139 }
05140 
05141 static inline int dahdi_set_hook(int fd, int hs)
05142 {
05143    int x, res;
05144 
05145    x = hs;
05146    res = ioctl(fd, DAHDI_HOOK, &x);
05147 
05148    if (res < 0) {
05149       if (errno == EINPROGRESS)
05150          return 0;
05151       ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
05152       /* will expectedly fail if phone is off hook during operation, such as during a restart */
05153    }
05154 
05155    return res;
05156 }
05157 
05158 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
05159 {
05160    int x, res;
05161 
05162    x = muted;
05163 #if defined(HAVE_PRI) || defined(HAVE_SS7)
05164    switch (p->sig) {
05165 #if defined(HAVE_PRI)
05166    case SIG_PRI_LIB_HANDLE_CASES:
05167       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
05168          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
05169          break;
05170       }
05171       /* Fall through */
05172 #endif   /* defined(HAVE_PRI) */
05173 #if defined(HAVE_SS7)
05174    case SIG_SS7:
05175 #endif   /* defined(HAVE_SS7) */
05176       {
05177          int y = 1;
05178 
05179          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
05180          if (res)
05181             ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n",
05182                p->channel, strerror(errno));
05183       }
05184       break;
05185    default:
05186       break;
05187    }
05188 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
05189    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
05190    if (res < 0)
05191       ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
05192    return res;
05193 }
05194 
05195 static int save_conference(struct dahdi_pvt *p)
05196 {
05197    struct dahdi_confinfo c;
05198    int res;
05199    if (p->saveconf.confmode) {
05200       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
05201       return -1;
05202    }
05203    p->saveconf.chan = 0;
05204    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
05205    if (res) {
05206       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
05207       p->saveconf.confmode = 0;
05208       return -1;
05209    }
05210    memset(&c, 0, sizeof(c));
05211    c.confmode = DAHDI_CONF_NORMAL;
05212    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
05213    if (res) {
05214       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
05215       return -1;
05216    }
05217    ast_debug(1, "Disabled conferencing\n");
05218    return 0;
05219 }
05220 
05221 static int restore_conference(struct dahdi_pvt *p)
05222 {
05223    int res;
05224    if (p->saveconf.confmode) {
05225       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
05226       p->saveconf.confmode = 0;
05227       if (res) {
05228          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
05229          return -1;
05230       }
05231       ast_debug(1, "Restored conferencing\n");
05232    }
05233    return 0;
05234 }
05235 
05236 static int send_cwcidspill(struct dahdi_pvt *p)
05237 {
05238    p->callwaitcas = 0;
05239    p->cidcwexpire = 0;
05240    p->cid_suppress_expire = 0;
05241    if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
05242       return -1;
05243    p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
05244    /* Make sure we account for the end */
05245    p->cidlen += READ_SIZE * 4;
05246    p->cidpos = 0;
05247    send_callerid(p);
05248    ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
05249    return 0;
05250 }
05251 
05252 static int has_voicemail(struct dahdi_pvt *p)
05253 {
05254    int new_msgs;
05255    struct ast_event *event;
05256    char *mailbox, *context;
05257 
05258    mailbox = context = ast_strdupa(p->mailbox);
05259    strsep(&context, "@");
05260    if (ast_strlen_zero(context))
05261       context = "default";
05262 
05263    event = ast_event_get_cached(AST_EVENT_MWI,
05264       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
05265       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
05266       AST_EVENT_IE_END);
05267 
05268    if (event) {
05269       new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
05270       ast_event_destroy(event);
05271    } else
05272       new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
05273 
05274    return new_msgs;
05275 }
05276 
05277 
05278 
05279 static int send_callerid(struct dahdi_pvt *p)
05280 {
05281    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
05282    int res;
05283    /* Take out of linear mode if necessary */
05284    if (p->subs[SUB_REAL].linear) {
05285       p->subs[SUB_REAL].linear = 0;
05286       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
05287    }
05288    while (p->cidpos < p->cidlen) {
05289       res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
05290       ast_debug(4, "writing callerid at pos %d of %d, res = %d\n", p->cidpos, p->cidlen, res);
05291       if (res < 0) {
05292          if (errno == EAGAIN)
05293             return 0;
05294          else {
05295             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
05296             return -1;
05297          }
05298       }
05299       if (!res)
05300          return 0;
05301       p->cidpos += res;
05302    }
05303    p->cid_suppress_expire = CALLWAITING_SUPPRESS_SAMPLES;
05304    ast_free(p->cidspill);
05305    p->cidspill = NULL;
05306    if (p->callwaitcas) {
05307       /* Wait for CID/CW to expire */
05308       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
05309       p->cid_suppress_expire = p->cidcwexpire;
05310    } else
05311       restore_conference(p);
05312    return 0;
05313 }
05314 
05315 static int dahdi_callwait(struct ast_channel *ast)
05316 {
05317    struct dahdi_pvt *p = ast->tech_pvt;
05318    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
05319    if (p->cidspill) {
05320       ast_log(LOG_WARNING, "Spill already exists?!?\n");
05321       ast_free(p->cidspill);
05322    }
05323 
05324    /*
05325     * SAS: Subscriber Alert Signal, 440Hz for 300ms
05326     * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
05327     */
05328    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
05329       return -1;
05330    save_conference(p);
05331    /* Silence */
05332    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
05333    if (!p->callwaitrings && p->callwaitingcallerid) {
05334       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
05335       p->callwaitcas = 1;
05336       p->cidlen = 2400 + 680 + READ_SIZE * 4;
05337    } else {
05338       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
05339       p->callwaitcas = 0;
05340       p->cidlen = 2400 + READ_SIZE * 4;
05341    }
05342    p->cidpos = 0;
05343    send_callerid(p);
05344 
05345    return 0;
05346 }
05347 
05348 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
05349 {
05350    struct dahdi_pvt *p = ast->tech_pvt;
05351    int x, res, mysig;
05352    char dest[256]; /* must be same length as p->dialdest */
05353 
05354    ast_mutex_lock(&p->lock);
05355    ast_copy_string(dest, rdest, sizeof(dest));
05356    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
05357    if ((ast->_state == AST_STATE_BUSY)) {
05358       p->subs[SUB_REAL].needbusy = 1;
05359       ast_mutex_unlock(&p->lock);
05360       return 0;
05361    }
05362    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05363       ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
05364       ast_mutex_unlock(&p->lock);
05365       return -1;
05366    }
05367    p->waitingfordt.tv_sec = 0;
05368    p->dialednone = 0;
05369    if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
05370    {
05371       /* Special pseudo -- automatically up */
05372       ast_setstate(ast, AST_STATE_UP);
05373       ast_mutex_unlock(&p->lock);
05374       return 0;
05375    }
05376    x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
05377    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
05378    if (res)
05379       ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
05380    p->outgoing = 1;
05381 
05382    if (IS_DIGITAL(ast->transfercapability)){
05383       set_actual_gain(p->subs[SUB_REAL].dfd, 0, 0, p->rxdrc, p->txdrc, p->law);
05384    } else {
05385       set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05386    }  
05387 
05388 #ifdef HAVE_PRI
05389    if (dahdi_sig_pri_lib_handles(p->sig)) {
05390       res = sig_pri_call(p->sig_pvt, ast, rdest, timeout,
05391          (p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW);
05392       ast_mutex_unlock(&p->lock);
05393       return res;
05394    }
05395 #endif
05396 
05397 #if defined(HAVE_SS7)
05398    if (p->sig == SIG_SS7) {
05399       res = sig_ss7_call(p->sig_pvt, ast, rdest);
05400       ast_mutex_unlock(&p->lock);
05401       return res;
05402    }
05403 #endif   /* defined(HAVE_SS7) */
05404 
05405    /* If this is analog signalling we can exit here */
05406    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
05407       p->callwaitrings = 0;
05408       res = analog_call(p->sig_pvt, ast, rdest, timeout);
05409       ast_mutex_unlock(&p->lock);
05410       return res;
05411    }
05412 
05413    mysig = p->outsigmod > -1 ? p->outsigmod : p->sig;
05414    switch (mysig) {
05415    case 0:
05416       /* Special pseudo -- automatically up*/
05417       ast_setstate(ast, AST_STATE_UP);
05418       break;
05419    case SIG_MFCR2:
05420       break;
05421    default:
05422       ast_debug(1, "not yet implemented\n");
05423       ast_mutex_unlock(&p->lock);
05424       return -1;
05425    }
05426 
05427 #ifdef HAVE_OPENR2
05428    if (p->mfcr2) {
05429       openr2_calling_party_category_t chancat;
05430       int callres = 0;
05431       char *c, *l;
05432 
05433       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
05434       p->dialdest[0] = '\0';
05435 
05436       c = strchr(dest, '/');
05437       if (c) {
05438          c++;
05439       } else {
05440          c = "";
05441       }
05442       if (!p->hidecallerid) {
05443          l = ast->connected.id.number.valid ? ast->connected.id.number.str : NULL;
05444       } else {
05445          l = NULL;
05446       }
05447       if (strlen(c) < p->stripmsd) {
05448          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
05449          ast_mutex_unlock(&p->lock);
05450          return -1;
05451       }
05452       p->dialing = 1;
05453       chancat = dahdi_r2_get_channel_category(ast);
05454       callres = openr2_chan_make_call(p->r2chan, l, (c + p->stripmsd), chancat);
05455       if (-1 == callres) {
05456          ast_mutex_unlock(&p->lock);
05457          ast_log(LOG_ERROR, "unable to make new MFC/R2 call!\n");
05458          return -1;
05459       }
05460       p->mfcr2_call_accepted = 0;
05461       p->mfcr2_progress = 0;
05462       ast_setstate(ast, AST_STATE_DIALING);
05463    }
05464 #endif /* HAVE_OPENR2 */
05465    ast_mutex_unlock(&p->lock);
05466    return 0;
05467 }
05468 
05469 /*!
05470  * \internal
05471  * \brief Insert the given chan_dahdi interface structure into the interface list.
05472  * \since 1.8
05473  *
05474  * \param pvt chan_dahdi private interface structure to insert.
05475  *
05476  * \details
05477  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05478  * Any duplicates are inserted after the existing entries.
05479  *
05480  * \note The new interface must not already be in the list.
05481  *
05482  * \return Nothing
05483  */
05484 static void dahdi_iflist_insert(struct dahdi_pvt *pvt)
05485 {
05486    struct dahdi_pvt *cur;
05487 
05488    pvt->which_iflist = DAHDI_IFLIST_MAIN;
05489 
05490    /* Find place in middle of list for the new interface. */
05491    for (cur = iflist; cur; cur = cur->next) {
05492       if (pvt->channel < cur->channel) {
05493          /* New interface goes before the current interface. */
05494          pvt->prev = cur->prev;
05495          pvt->next = cur;
05496          if (cur->prev) {
05497             /* Insert into the middle of the list. */
05498             cur->prev->next = pvt;
05499          } else {
05500             /* Insert at head of list. */
05501             iflist = pvt;
05502          }
05503          cur->prev = pvt;
05504          return;
05505       }
05506    }
05507 
05508    /* New interface goes onto the end of the list */
05509    pvt->prev = ifend;
05510    pvt->next = NULL;
05511    if (ifend) {
05512       ifend->next = pvt;
05513    }
05514    ifend = pvt;
05515    if (!iflist) {
05516       /* List was empty */
05517       iflist = pvt;
05518    }
05519 }
05520 
05521 /*!
05522  * \internal
05523  * \brief Extract the given chan_dahdi interface structure from the interface list.
05524  * \since 1.8
05525  *
05526  * \param pvt chan_dahdi private interface structure to extract.
05527  *
05528  * \note
05529  * The given interface structure can be either in the interface list or a stand alone
05530  * structure that has not been put in the list if the next and prev pointers are NULL.
05531  *
05532  * \return Nothing
05533  */
05534 static void dahdi_iflist_extract(struct dahdi_pvt *pvt)
05535 {
05536    /* Extract from the forward chain. */
05537    if (pvt->prev) {
05538       pvt->prev->next = pvt->next;
05539    } else if (iflist == pvt) {
05540       /* Node is at the head of the list. */
05541       iflist = pvt->next;
05542    }
05543 
05544    /* Extract from the reverse chain. */
05545    if (pvt->next) {
05546       pvt->next->prev = pvt->prev;
05547    } else if (ifend == pvt) {
05548       /* Node is at the end of the list. */
05549       ifend = pvt->prev;
05550    }
05551 
05552    /* Node is no longer in the list. */
05553    pvt->which_iflist = DAHDI_IFLIST_NONE;
05554    pvt->prev = NULL;
05555    pvt->next = NULL;
05556 }
05557 
05558 #if defined(HAVE_PRI)
05559 /*!
05560  * \internal
05561  * \brief Insert the given chan_dahdi interface structure into the no B channel list.
05562  * \since 1.8
05563  *
05564  * \param pri sig_pri span control structure holding no B channel list.
05565  * \param pvt chan_dahdi private interface structure to insert.
05566  *
05567  * \details
05568  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05569  * Any duplicates are inserted after the existing entries.
05570  *
05571  * \note The new interface must not already be in the list.
05572  *
05573  * \return Nothing
05574  */
05575 static void dahdi_nobch_insert(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05576 {
05577    struct dahdi_pvt *cur;
05578 
05579    pvt->which_iflist = DAHDI_IFLIST_NO_B_CHAN;
05580 
05581    /* Find place in middle of list for the new interface. */
05582    for (cur = pri->no_b_chan_iflist; cur; cur = cur->next) {
05583       if (pvt->channel < cur->channel) {
05584          /* New interface goes before the current interface. */
05585          pvt->prev = cur->prev;
05586          pvt->next = cur;
05587          if (cur->prev) {
05588             /* Insert into the middle of the list. */
05589             cur->prev->next = pvt;
05590          } else {
05591             /* Insert at head of list. */
05592             pri->no_b_chan_iflist = pvt;
05593          }
05594          cur->prev = pvt;
05595          return;
05596       }
05597    }
05598 
05599    /* New interface goes onto the end of the list */
05600    pvt->prev = pri->no_b_chan_end;
05601    pvt->next = NULL;
05602    if (pri->no_b_chan_end) {
05603       ((struct dahdi_pvt *) pri->no_b_chan_end)->next = pvt;
05604    }
05605    pri->no_b_chan_end = pvt;
05606    if (!pri->no_b_chan_iflist) {
05607       /* List was empty */
05608       pri->no_b_chan_iflist = pvt;
05609    }
05610 }
05611 #endif   /* defined(HAVE_PRI) */
05612 
05613 #if defined(HAVE_PRI)
05614 /*!
05615  * \internal
05616  * \brief Extract the given chan_dahdi interface structure from the no B channel list.
05617  * \since 1.8
05618  *
05619  * \param pri sig_pri span control structure holding no B channel list.
05620  * \param pvt chan_dahdi private interface structure to extract.
05621  *
05622  * \note
05623  * The given interface structure can be either in the interface list or a stand alone
05624  * structure that has not been put in the list if the next and prev pointers are NULL.
05625  *
05626  * \return Nothing
05627  */
05628 static void dahdi_nobch_extract(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05629 {
05630    /* Extract from the forward chain. */
05631    if (pvt->prev) {
05632       pvt->prev->next = pvt->next;
05633    } else if (pri->no_b_chan_iflist == pvt) {
05634       /* Node is at the head of the list. */
05635       pri->no_b_chan_iflist = pvt->next;
05636    }
05637 
05638    /* Extract from the reverse chain. */
05639    if (pvt->next) {
05640       pvt->next->prev = pvt->prev;
05641    } else if (pri->no_b_chan_end == pvt) {
05642       /* Node is at the end of the list. */
05643       pri->no_b_chan_end = pvt->prev;
05644    }
05645 
05646    /* Node is no longer in the list. */
05647    pvt->which_iflist = DAHDI_IFLIST_NONE;
05648    pvt->prev = NULL;
05649    pvt->next = NULL;
05650 }
05651 #endif   /* defined(HAVE_PRI) */
05652 
05653 #if defined(HAVE_PRI)
05654 /*!
05655  * \internal
05656  * \brief Unlink the channel interface from the PRI private pointer array.
05657  * \since 1.8
05658  *
05659  * \param pvt chan_dahdi private interface structure to unlink.
05660  *
05661  * \return Nothing
05662  */
05663 static void dahdi_unlink_pri_pvt(struct dahdi_pvt *pvt)
05664 {
05665    unsigned idx;
05666    struct sig_pri_span *pri;
05667 
05668    pri = pvt->pri;
05669    if (!pri) {
05670       /* Not PRI signaling so cannot be in a PRI private pointer array. */
05671       return;
05672    }
05673    ast_mutex_lock(&pri->lock);
05674    for (idx = 0; idx < pri->numchans; ++idx) {
05675       if (pri->pvts[idx] == pvt->sig_pvt) {
05676          pri->pvts[idx] = NULL;
05677          ast_mutex_unlock(&pri->lock);
05678          return;
05679       }
05680    }
05681    ast_mutex_unlock(&pri->lock);
05682 }
05683 #endif   /* defined(HAVE_PRI) */
05684 
05685 #if defined(HAVE_SS7)
05686 /*!
05687  * \internal
05688  * \brief Unlink the channel interface from the SS7 private pointer array.
05689  * \since 1.8
05690  *
05691  * \param pvt chan_dahdi private interface structure to unlink.
05692  *
05693  * \return Nothing
05694  */
05695 static void dahdi_unlink_ss7_pvt(struct dahdi_pvt *pvt)
05696 {
05697    unsigned idx;
05698    struct sig_ss7_linkset *ss7;
05699 
05700    ss7 = pvt->ss7;
05701    if (!ss7) {
05702       /* Not SS7 signaling so cannot be in a SS7 private pointer array. */
05703       return;
05704    }
05705    ast_mutex_lock(&ss7->lock);
05706    for (idx = 0; idx < ss7->numchans; ++idx) {
05707       if (ss7->pvts[idx] == pvt->sig_pvt) {
05708          ss7->pvts[idx] = NULL;
05709          ast_mutex_unlock(&ss7->lock);
05710          return;
05711       }
05712    }
05713    ast_mutex_unlock(&ss7->lock);
05714 }
05715 #endif   /* defined(HAVE_SS7) */
05716 
05717 static struct dahdi_pvt *find_next_iface_in_span(struct dahdi_pvt *cur)
05718 {
05719    if (cur->next && cur->next->span == cur->span) {
05720       return cur->next;
05721    } else if (cur->prev && cur->prev->span == cur->span) {
05722       return cur->prev;
05723    }
05724 
05725    return NULL;
05726 }
05727 
05728 static void destroy_dahdi_pvt(struct dahdi_pvt *pvt)
05729 {
05730    struct dahdi_pvt *p = pvt;
05731 
05732    if (p->manages_span_alarms) {
05733       struct dahdi_pvt *next = find_next_iface_in_span(p);
05734       if (next) {
05735          next->manages_span_alarms = 1;
05736       }
05737    }
05738 
05739    /* Remove channel from the list */
05740 #if defined(HAVE_PRI)
05741    dahdi_unlink_pri_pvt(p);
05742 #endif   /* defined(HAVE_PRI) */
05743 #if defined(HAVE_SS7)
05744    dahdi_unlink_ss7_pvt(p);
05745 #endif   /* defined(HAVE_SS7) */
05746    switch (pvt->which_iflist) {
05747    case DAHDI_IFLIST_NONE:
05748       break;
05749    case DAHDI_IFLIST_MAIN:
05750       dahdi_iflist_extract(p);
05751       break;
05752 #if defined(HAVE_PRI)
05753    case DAHDI_IFLIST_NO_B_CHAN:
05754       if (p->pri) {
05755          dahdi_nobch_extract(p->pri, p);
05756       }
05757       break;
05758 #endif   /* defined(HAVE_PRI) */
05759    }
05760 
05761    if (p->sig_pvt) {
05762       if (analog_lib_handles(p->sig, 0, 0)) {
05763          analog_delete(p->sig_pvt);
05764       }
05765       switch (p->sig) {
05766 #if defined(HAVE_PRI)
05767       case SIG_PRI_LIB_HANDLE_CASES:
05768          sig_pri_chan_delete(p->sig_pvt);
05769          break;
05770 #endif   /* defined(HAVE_PRI) */
05771 #if defined(HAVE_SS7)
05772       case SIG_SS7:
05773          sig_ss7_chan_delete(p->sig_pvt);
05774          break;
05775 #endif   /* defined(HAVE_SS7) */
05776       default:
05777          break;
05778       }
05779    }
05780    ast_free(p->cidspill);
05781    if (p->use_smdi)
05782       ast_smdi_interface_unref(p->smdi_iface);
05783    if (p->mwi_event_sub)
05784       ast_event_unsubscribe(p->mwi_event_sub);
05785    if (p->vars) {
05786       ast_variables_destroy(p->vars);
05787    }
05788    if (p->cc_params) {
05789       ast_cc_config_params_destroy(p->cc_params);
05790    }
05791    ast_mutex_destroy(&p->lock);
05792    dahdi_close_sub(p, SUB_REAL);
05793    if (p->owner)
05794       p->owner->tech_pvt = NULL;
05795    ast_free(p);
05796 }
05797 
05798 static void destroy_channel(struct dahdi_pvt *cur, int now)
05799 {
05800    int i;
05801 
05802    if (!now) {
05803       /* Do not destroy the channel now if it is owned by someone. */
05804       if (cur->owner) {
05805          return;
05806       }
05807       for (i = 0; i < 3; i++) {
05808          if (cur->subs[i].owner) {
05809             return;
05810          }
05811       }
05812    }
05813    destroy_dahdi_pvt(cur);
05814 }
05815 
05816 static void destroy_all_channels(void)
05817 {
05818    int chan;
05819 #if defined(HAVE_PRI)
05820    unsigned span;
05821    struct sig_pri_span *pri;
05822 #endif   /* defined(HAVE_PRI) */
05823    struct dahdi_pvt *p;
05824 
05825    while (num_restart_pending) {
05826       usleep(1);
05827    }
05828 
05829    ast_mutex_lock(&iflock);
05830    /* Destroy all the interfaces and free their memory */
05831    while (iflist) {
05832       p = iflist;
05833 
05834       chan = p->channel;
05835 #if defined(HAVE_PRI_SERVICE_MESSAGES)
05836       {
05837          char db_chan_name[20];
05838          char db_answer[5];
05839          char state;
05840          int why = -1;
05841 
05842          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, p->span, chan);
05843          if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
05844             sscanf(db_answer, "%1c:%30d", &state, &why);
05845          }
05846          if (!why) {
05847             /* SRVST persistence is not required */
05848             ast_db_del(db_chan_name, SRVST_DBKEY);
05849          }
05850       }
05851 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
05852       /* Free associated memory */
05853       destroy_dahdi_pvt(p);
05854       ast_verb(3, "Unregistered channel %d\n", chan);
05855    }
05856    ifcount = 0;
05857    ast_mutex_unlock(&iflock);
05858 
05859 #if defined(HAVE_PRI)
05860    /* Destroy all of the no B channel interface lists */
05861    for (span = 0; span < NUM_SPANS; ++span) {
05862       if (!pris[span].dchannels[0]) {
05863          break;
05864       }
05865       pri = &pris[span].pri;
05866       ast_mutex_lock(&pri->lock);
05867       while (pri->no_b_chan_iflist) {
05868          p = pri->no_b_chan_iflist;
05869 
05870          /* Free associated memory */
05871          destroy_dahdi_pvt(p);
05872       }
05873       ast_mutex_unlock(&pri->lock);
05874    }
05875 #endif   /* defined(HAVE_PRI) */
05876 }
05877 
05878 #if defined(HAVE_PRI)
05879 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
05880 
05881 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, const char *digits)
05882 {
05883    /* Data will be our digit string */
05884    struct dahdi_pvt *p;
05885 
05886    if (ast_strlen_zero(digits)) {
05887       ast_debug(1, "No digit string sent to application!\n");
05888       return -1;
05889    }
05890 
05891    p = (struct dahdi_pvt *)chan->tech_pvt;
05892 
05893    if (!p) {
05894       ast_debug(1, "Unable to find technology private\n");
05895       return -1;
05896    }
05897 
05898    pri_send_keypad_facility_exec(p->sig_pvt, digits);
05899 
05900    return 0;
05901 }
05902 #endif   /* defined(HAVE_PRI) */
05903 
05904 #if defined(HAVE_PRI)
05905 #if defined(HAVE_PRI_PROG_W_CAUSE)
05906 static char *dahdi_send_callrerouting_facility_app = "DAHDISendCallreroutingFacility";
05907 
05908 static int dahdi_send_callrerouting_facility_exec(struct ast_channel *chan, const char *data)
05909 {
05910    /* Data will be our digit string */
05911    struct dahdi_pvt *pvt;
05912    char *parse;
05913    int res;
05914    AST_DECLARE_APP_ARGS(args,
05915       AST_APP_ARG(destination);
05916       AST_APP_ARG(original);
05917       AST_APP_ARG(reason);
05918    );
05919 
05920    if (ast_strlen_zero(data)) {
05921       ast_log(LOG_DEBUG, "No data sent to application!\n");
05922       return -1;
05923    }
05924    if (chan->tech != &dahdi_tech) {
05925       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05926       return -1;
05927    }
05928    pvt = (struct dahdi_pvt *) chan->tech_pvt;
05929    if (!pvt) {
05930       ast_log(LOG_DEBUG, "Unable to find technology private\n");
05931       return -1;
05932    }
05933    switch (pvt->sig) {
05934    case SIG_PRI_LIB_HANDLE_CASES:
05935       break;
05936    default:
05937       ast_log(LOG_DEBUG, "callrerouting attempted on non-ISDN channel %s\n",
05938          chan->name);
05939       return -1;
05940    }
05941 
05942    parse = ast_strdupa(data);
05943    AST_STANDARD_APP_ARGS(args, parse);
05944 
05945    if (ast_strlen_zero(args.destination)) {
05946       ast_log(LOG_WARNING, "callrerouting facility requires at least destination number argument\n");
05947       return -1;
05948    }
05949 
05950    if (ast_strlen_zero(args.original)) {
05951       ast_log(LOG_WARNING, "Callrerouting Facility without original called number argument\n");
05952       args.original = NULL;
05953    }
05954 
05955    if (ast_strlen_zero(args.reason)) {
05956       ast_log(LOG_NOTICE, "Callrerouting Facility without diversion reason argument, defaulting to unknown\n");
05957       args.reason = NULL;
05958    }
05959 
05960    res = pri_send_callrerouting_facility_exec(pvt->sig_pvt, chan->_state,
05961       args.destination, args.original, args.reason);
05962    if (!res) {
05963       /*
05964        * Wait up to 5 seconds for a reply before hanging up this call
05965        * leg if the peer does not disconnect first.
05966        */
05967       ast_safe_sleep(chan, 5000);
05968    }
05969 
05970    return -1;
05971 }
05972 #endif   /* defined(HAVE_PRI_PROG_W_CAUSE) */
05973 #endif   /* defined(HAVE_PRI) */
05974 
05975 #if defined(HAVE_OPENR2)
05976 static const char * const dahdi_accept_r2_call_app = "DAHDIAcceptR2Call";
05977 
05978 static int dahdi_accept_r2_call_exec(struct ast_channel *chan, const char *data)
05979 {
05980    /* data is whether to accept with charge or no charge */
05981    openr2_call_mode_t accept_mode;
05982    int res, timeout, maxloops;
05983    struct ast_frame *f;
05984    struct dahdi_pvt *p;
05985    char *parse;
05986    AST_DECLARE_APP_ARGS(args,
05987          AST_APP_ARG(charge);
05988    );
05989 
05990    if (ast_strlen_zero(data)) {
05991       ast_log(LOG_DEBUG, "No data sent to application!\n");
05992       return -1;
05993    }
05994 
05995    if (chan->tech != &dahdi_tech) {
05996       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05997       return -1;
05998    }
05999 
06000    p = (struct dahdi_pvt *)chan->tech_pvt;
06001    if (!p) {
06002       ast_log(LOG_DEBUG, "Unable to find technology private!\n");
06003       return -1;
06004    }
06005 
06006    parse = ast_strdupa(data);
06007    AST_STANDARD_APP_ARGS(args, parse);
06008 
06009    if (ast_strlen_zero(args.charge)) {
06010       ast_log(LOG_WARNING, "DAHDIAcceptR2Call requires 'yes' or 'no' for the charge parameter\n");
06011       return -1;
06012    }
06013 
06014    ast_mutex_lock(&p->lock);
06015    if (!p->mfcr2 || !p->mfcr2call) {
06016       ast_mutex_unlock(&p->lock);
06017       ast_log(LOG_DEBUG, "Channel %s does not seems to be an R2 active channel!\n", chan->name);
06018       return -1;
06019    }
06020 
06021    if (p->mfcr2_call_accepted) {
06022       ast_mutex_unlock(&p->lock);
06023       ast_log(LOG_DEBUG, "MFC/R2 call already accepted on channel %s!\n", chan->name);
06024       return 0;
06025    }
06026    accept_mode = ast_true(args.charge) ? OR2_CALL_WITH_CHARGE : OR2_CALL_NO_CHARGE;
06027    if (openr2_chan_accept_call(p->r2chan, accept_mode)) {
06028       ast_mutex_unlock(&p->lock);
06029       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
06030       return -1;
06031    }
06032    ast_mutex_unlock(&p->lock);
06033 
06034    res = 0;
06035    timeout = 100;
06036    maxloops = 50; /* wait up to 5 seconds */
06037    /* we need to read() until the call is accepted */
06038    while (maxloops > 0) {
06039       maxloops--;
06040       if (ast_check_hangup(chan)) {
06041          break;
06042       }
06043       res = ast_waitfor(chan, timeout);
06044       if (res < 0) {
06045          ast_log(LOG_DEBUG, "ast_waitfor failed on channel %s, going out ...\n", chan->name);
06046          res = -1;
06047          break;
06048       }
06049       if (res == 0) {
06050          continue;
06051       }
06052       f = ast_read(chan);
06053       if (!f) {
06054          ast_log(LOG_DEBUG, "No frame read on channel %s, going out ...\n", chan->name);
06055          res = -1;
06056          break;
06057       }
06058       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
06059          ast_log(LOG_DEBUG, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
06060          ast_frfree(f);
06061          res = -1;
06062          break;
06063       }
06064       ast_frfree(f);
06065       ast_mutex_lock(&p->lock);
06066       if (p->mfcr2_call_accepted) {
06067          ast_mutex_unlock(&p->lock);
06068          ast_log(LOG_DEBUG, "Accepted MFC/R2 call!\n");
06069          break;
06070       }
06071       ast_mutex_unlock(&p->lock);
06072    }
06073    if (res == -1) {
06074       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
06075    }
06076    return res;
06077 }
06078 
06079 static openr2_call_disconnect_cause_t dahdi_ast_cause_to_r2_cause(int cause)
06080 {
06081    openr2_call_disconnect_cause_t r2cause = OR2_CAUSE_NORMAL_CLEARING;
06082    switch (cause) {
06083    case AST_CAUSE_USER_BUSY:
06084    case AST_CAUSE_CALL_REJECTED:
06085    case AST_CAUSE_INTERWORKING: /* I don't know wtf is this but is used sometimes when ekiga rejects a call */
06086       r2cause = OR2_CAUSE_BUSY_NUMBER;
06087       break;
06088 
06089    case AST_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06090    case AST_CAUSE_SWITCH_CONGESTION:
06091       r2cause = OR2_CAUSE_NETWORK_CONGESTION;
06092       break;
06093 
06094    case AST_CAUSE_UNALLOCATED:
06095       r2cause = OR2_CAUSE_UNALLOCATED_NUMBER;
06096       break;
06097 
06098    case AST_CAUSE_NETWORK_OUT_OF_ORDER:
06099    case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06100       r2cause = OR2_CAUSE_OUT_OF_ORDER;
06101       break;
06102 
06103    case AST_CAUSE_NO_ANSWER:
06104    case AST_CAUSE_NO_USER_RESPONSE:
06105       r2cause = OR2_CAUSE_NO_ANSWER;
06106       break;
06107 
06108    default:
06109       r2cause = OR2_CAUSE_NORMAL_CLEARING;
06110       break;
06111    }
06112    ast_log(LOG_DEBUG, "ast cause %d resulted in openr2 cause %d/%s\n",
06113          cause, r2cause, openr2_proto_get_disconnect_string(r2cause));
06114    return r2cause;
06115 }
06116 #endif
06117 
06118 static int revert_fax_buffers(struct dahdi_pvt *p, struct ast_channel *ast)
06119 {
06120    if (p->bufferoverrideinuse) {
06121       /* faxbuffers are in use, revert them */
06122       struct dahdi_bufferinfo bi = {
06123          .txbufpolicy = p->buf_policy,
06124          .rxbufpolicy = p->buf_policy,
06125          .bufsize = p->bufsize,
06126          .numbufs = p->buf_no
06127       };
06128       int bpres;
06129 
06130       if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
06131          ast_log(LOG_WARNING, "Channel '%s' unable to revert buffer policy: %s\n", ast->name, strerror(errno));
06132       }
06133       p->bufferoverrideinuse = 0;
06134       return bpres;
06135    }
06136 
06137    return -1;
06138 }
06139 
06140 static int dahdi_hangup(struct ast_channel *ast)
06141 {
06142    int res = 0;
06143    int idx,x;
06144    int law;
06145    /*static int restore_gains(struct dahdi_pvt *p);*/
06146    struct dahdi_pvt *p = ast->tech_pvt;
06147    struct dahdi_params par;
06148 
06149    ast_debug(1, "dahdi_hangup(%s)\n", ast->name);
06150    if (!ast->tech_pvt) {
06151       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
06152       return 0;
06153    }
06154 
06155    ast_mutex_lock(&p->lock);
06156    p->exten[0] = '\0';
06157    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06158       dahdi_confmute(p, 0);
06159       restore_gains(p);
06160       p->ignoredtmf = 0;
06161       p->waitingfordt.tv_sec = 0;
06162 
06163       res = analog_hangup(p->sig_pvt, ast);
06164       revert_fax_buffers(p, ast);
06165 
06166       goto hangup_out;
06167    } else {
06168       p->cid_num[0] = '\0';
06169       p->cid_name[0] = '\0';
06170       p->cid_subaddr[0] = '\0';
06171    }
06172 
06173 #if defined(HAVE_PRI)
06174    if (dahdi_sig_pri_lib_handles(p->sig)) {
06175       x = 1;
06176       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06177 
06178       dahdi_confmute(p, 0);
06179       p->muting = 0;
06180       restore_gains(p);
06181       if (p->dsp) {
06182          ast_dsp_free(p->dsp);
06183          p->dsp = NULL;
06184       }
06185       p->ignoredtmf = 0;
06186 
06187       /* Real channel, do some fixup */
06188       p->subs[SUB_REAL].owner = NULL;
06189       p->subs[SUB_REAL].needbusy = 0;
06190       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06191 
06192       p->owner = NULL;
06193       p->cid_tag[0] = '\0';
06194       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06195       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06196       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06197       p->outgoing = 0;
06198       p->digital = 0;
06199       p->faxhandled = 0;
06200       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06201 
06202       revert_fax_buffers(p, ast);
06203 
06204       p->law = p->law_default;
06205       law = p->law_default;
06206       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06207       if (res < 0) {
06208          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n",
06209             p->channel, strerror(errno));
06210       }
06211 
06212       sig_pri_hangup(p->sig_pvt, ast);
06213 
06214       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06215       dahdi_disable_ec(p);
06216 
06217       x = 0;
06218       ast_channel_setoption(ast, AST_OPTION_TDD, &x, sizeof(char), 0);
06219       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06220 
06221       p->rdnis[0] = '\0';
06222       update_conf(p);
06223       reset_conf(p);
06224 
06225       /* Restore data mode */
06226       x = 0;
06227       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06228 
06229       if (num_restart_pending == 0) {
06230          restart_monitor();
06231       }
06232       goto hangup_out;
06233    }
06234 #endif   /* defined(HAVE_PRI) */
06235 
06236 #if defined(HAVE_SS7)
06237    if (p->sig == SIG_SS7) {
06238       x = 1;
06239       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06240 
06241       dahdi_confmute(p, 0);
06242       p->muting = 0;
06243       restore_gains(p);
06244       if (p->dsp) {
06245          ast_dsp_free(p->dsp);
06246          p->dsp = NULL;
06247       }
06248       p->ignoredtmf = 0;
06249 
06250       /* Real channel, do some fixup */
06251       p->subs[SUB_REAL].owner = NULL;
06252       p->subs[SUB_REAL].needbusy = 0;
06253       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06254 
06255       p->owner = NULL;
06256       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06257       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06258       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06259       p->outgoing = 0;
06260       p->digital = 0;
06261       p->faxhandled = 0;
06262       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06263 
06264       revert_fax_buffers(p, ast);
06265 
06266       p->law = p->law_default;
06267       law = p->law_default;
06268       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06269       if (res < 0) {
06270          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n",
06271             p->channel, strerror(errno));
06272       }
06273 
06274       sig_ss7_hangup(p->sig_pvt, ast);
06275 
06276       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06277       dahdi_disable_ec(p);
06278 
06279       x = 0;
06280       ast_channel_setoption(ast, AST_OPTION_TDD, &x, sizeof(char), 0);
06281       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06282 
06283       update_conf(p);
06284       reset_conf(p);
06285 
06286       /* Restore data mode */
06287       x = 0;
06288       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06289 
06290       if (num_restart_pending == 0) {
06291          restart_monitor();
06292       }
06293       goto hangup_out;
06294    }
06295 #endif   /* defined(HAVE_SS7) */
06296 
06297    idx = dahdi_get_index(ast, p, 1);
06298 
06299    dahdi_confmute(p, 0);
06300    p->muting = 0;
06301    restore_gains(p);
06302    if (p->origcid_num) {
06303       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
06304       ast_free(p->origcid_num);
06305       p->origcid_num = NULL;
06306    }
06307    if (p->origcid_name) {
06308       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
06309       ast_free(p->origcid_name);
06310       p->origcid_name = NULL;
06311    }
06312    if (p->dsp)
06313       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
06314 
06315    ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
06316       p->channel, idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
06317    p->ignoredtmf = 0;
06318 
06319    if (idx > -1) {
06320       /* Real channel, do some fixup */
06321       p->subs[idx].owner = NULL;
06322       p->subs[idx].needanswer = 0;
06323       p->subs[idx].needflash = 0;
06324       p->subs[idx].needringing = 0;
06325       p->subs[idx].needbusy = 0;
06326       p->subs[idx].needcongestion = 0;
06327       p->subs[idx].linear = 0;
06328       p->polarity = POLARITY_IDLE;
06329       dahdi_setlinear(p->subs[idx].dfd, 0);
06330       if (idx == SUB_REAL) {
06331          if ((p->subs[SUB_CALLWAIT].dfd > -1) && (p->subs[SUB_THREEWAY].dfd > -1)) {
06332             ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
06333             if (p->subs[SUB_CALLWAIT].inthreeway) {
06334                /* We had flipped over to answer a callwait and now it's gone */
06335                ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
06336                /* Move to the call-wait, but un-own us until they flip back. */
06337                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06338                unalloc_sub(p, SUB_CALLWAIT);
06339                p->owner = NULL;
06340             } else {
06341                /* The three way hung up, but we still have a call wait */
06342                ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
06343                swap_subs(p, SUB_THREEWAY, SUB_REAL);
06344                unalloc_sub(p, SUB_THREEWAY);
06345                if (p->subs[SUB_REAL].inthreeway) {
06346                   /* This was part of a three way call.  Immediately make way for
06347                      another call */
06348                   ast_debug(1, "Call was complete, setting owner to former third call\n");
06349                   p->owner = p->subs[SUB_REAL].owner;
06350                } else {
06351                   /* This call hasn't been completed yet...  Set owner to NULL */
06352                   ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06353                   p->owner = NULL;
06354                }
06355                p->subs[SUB_REAL].inthreeway = 0;
06356             }
06357          } else if (p->subs[SUB_CALLWAIT].dfd > -1) {
06358             /* Move to the call-wait and switch back to them. */
06359             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06360             unalloc_sub(p, SUB_CALLWAIT);
06361             p->owner = p->subs[SUB_REAL].owner;
06362             if (p->owner->_state != AST_STATE_UP)
06363                p->subs[SUB_REAL].needanswer = 1;
06364             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
06365                ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
06366          } else if (p->subs[SUB_THREEWAY].dfd > -1) {
06367             swap_subs(p, SUB_THREEWAY, SUB_REAL);
06368             unalloc_sub(p, SUB_THREEWAY);
06369             if (p->subs[SUB_REAL].inthreeway) {
06370                /* This was part of a three way call.  Immediately make way for
06371                   another call */
06372                ast_debug(1, "Call was complete, setting owner to former third call\n");
06373                p->owner = p->subs[SUB_REAL].owner;
06374             } else {
06375                /* This call hasn't been completed yet...  Set owner to NULL */
06376                ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06377                p->owner = NULL;
06378             }
06379             p->subs[SUB_REAL].inthreeway = 0;
06380          }
06381       } else if (idx == SUB_CALLWAIT) {
06382          /* Ditch the holding callwait call, and immediately make it availabe */
06383          if (p->subs[SUB_CALLWAIT].inthreeway) {
06384             /* This is actually part of a three way, placed on hold.  Place the third part
06385                on music on hold now */
06386             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
06387                ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
06388                   S_OR(p->mohsuggest, NULL),
06389                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06390             }
06391             p->subs[SUB_THREEWAY].inthreeway = 0;
06392             /* Make it the call wait now */
06393             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
06394             unalloc_sub(p, SUB_THREEWAY);
06395          } else
06396             unalloc_sub(p, SUB_CALLWAIT);
06397       } else if (idx == SUB_THREEWAY) {
06398          if (p->subs[SUB_CALLWAIT].inthreeway) {
06399             /* The other party of the three way call is currently in a call-wait state.
06400                Start music on hold for them, and take the main guy out of the third call */
06401             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
06402                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
06403                   S_OR(p->mohsuggest, NULL),
06404                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06405             }
06406             p->subs[SUB_CALLWAIT].inthreeway = 0;
06407          }
06408          p->subs[SUB_REAL].inthreeway = 0;
06409          /* If this was part of a three way call index, let us make
06410             another three way call */
06411          unalloc_sub(p, SUB_THREEWAY);
06412       } else {
06413          /* This wasn't any sort of call, but how are we an index? */
06414          ast_log(LOG_WARNING, "Index found but not any type of call?\n");
06415       }
06416    }
06417 
06418    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
06419       p->owner = NULL;
06420       p->ringt = 0;
06421       p->distinctivering = 0;
06422       p->confirmanswer = 0;
06423       p->outgoing = 0;
06424       p->digital = 0;
06425       p->faxhandled = 0;
06426       p->pulsedial = 0;
06427       if (p->dsp) {
06428          ast_dsp_free(p->dsp);
06429          p->dsp = NULL;
06430       }
06431 
06432       revert_fax_buffers(p, ast);
06433 
06434       p->law = p->law_default;
06435       law = p->law_default;
06436       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06437       if (res < 0)
06438          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
06439       /* Perform low level hangup if no owner left */
06440 #ifdef HAVE_OPENR2
06441       if (p->mfcr2 && p->mfcr2call && openr2_chan_get_direction(p->r2chan) != OR2_DIR_STOPPED) {
06442          ast_log(LOG_DEBUG, "disconnecting MFC/R2 call on chan %d\n", p->channel);
06443          /* If it's an incoming call, check the mfcr2_forced_release setting */
06444          if (openr2_chan_get_direction(p->r2chan) == OR2_DIR_BACKWARD && p->mfcr2_forced_release) {
06445             dahdi_r2_disconnect_call(p, OR2_CAUSE_FORCED_RELEASE);
06446          } else {
06447             const char *r2causestr = pbx_builtin_getvar_helper(ast, "MFCR2_CAUSE");
06448             int r2cause_user = r2causestr ? atoi(r2causestr) : 0;
06449             openr2_call_disconnect_cause_t r2cause = r2cause_user ? dahdi_ast_cause_to_r2_cause(r2cause_user)
06450                                                              : dahdi_ast_cause_to_r2_cause(ast->hangupcause);
06451             dahdi_r2_disconnect_call(p, r2cause);
06452          }
06453       } else if (p->mfcr2call) {
06454          ast_log(LOG_DEBUG, "Clearing call request on channel %d\n", p->channel);
06455          /* since ast_request() was called but not ast_call() we have not yet dialed
06456          and the openr2 stack will not call on_call_end callback, we need to unset
06457          the mfcr2call flag and bump the monitor count so the monitor thread can take
06458          care of this channel events from now on */
06459          p->mfcr2call = 0;
06460       }
06461 #endif
06462       switch (p->sig) {
06463       case SIG_SS7:
06464       case SIG_MFCR2:
06465       case SIG_PRI_LIB_HANDLE_CASES:
06466       case 0:
06467          break;
06468       default:
06469          res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
06470          break;
06471       }
06472       if (res < 0) {
06473          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
06474       }
06475       switch (p->sig) {
06476       case SIG_FXOGS:
06477       case SIG_FXOLS:
06478       case SIG_FXOKS:
06479          memset(&par, 0, sizeof(par));
06480          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
06481          if (!res) {
06482             struct analog_pvt *analog_p = p->sig_pvt;
06483 #if 0
06484             ast_debug(1, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
06485 #endif
06486             /* If they're off hook, try playing congestion */
06487             if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
06488                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
06489             else
06490                tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06491             analog_p->fxsoffhookstate = par.rxisoffhook;
06492          }
06493          break;
06494       case SIG_FXSGS:
06495       case SIG_FXSLS:
06496       case SIG_FXSKS:
06497          /* Make sure we're not made available for at least two seconds assuming
06498          we were actually used for an inbound or outbound call. */
06499          if (ast->_state != AST_STATE_RESERVED) {
06500             time(&p->guardtime);
06501             p->guardtime += 2;
06502          }
06503          break;
06504       default:
06505          tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06506          break;
06507       }
06508       if (p->sig)
06509          dahdi_disable_ec(p);
06510       x = 0;
06511       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
06512       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
06513       p->didtdd = 0;
06514       p->callwaitcas = 0;
06515       p->callwaiting = p->permcallwaiting;
06516       p->hidecallerid = p->permhidecallerid;
06517       p->waitingfordt.tv_sec = 0;
06518       p->dialing = 0;
06519       p->rdnis[0] = '\0';
06520       update_conf(p);
06521       reset_conf(p);
06522       /* Restore data mode */
06523       switch (p->sig) {
06524       case SIG_PRI_LIB_HANDLE_CASES:
06525       case SIG_SS7:
06526          x = 0;
06527          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
06528          break;
06529       default:
06530          break;
06531       }
06532       if (num_restart_pending == 0)
06533          restart_monitor();
06534    }
06535 
06536    p->callwaitingrepeat = 0;
06537    p->cidcwexpire = 0;
06538    p->cid_suppress_expire = 0;
06539    p->oprmode = 0;
06540 hangup_out:
06541    ast->tech_pvt = NULL;
06542    ast_free(p->cidspill);
06543    p->cidspill = NULL;
06544 
06545    ast_mutex_unlock(&p->lock);
06546    ast_verb(3, "Hungup '%s'\n", ast->name);
06547 
06548    ast_mutex_lock(&iflock);
06549    if (p->restartpending) {
06550       num_restart_pending--;
06551    }
06552 
06553    if (p->destroy) {
06554       destroy_channel(p, 0);
06555    }
06556    ast_mutex_unlock(&iflock);
06557 
06558    ast_module_unref(ast_module_info->self);
06559    return 0;
06560 }
06561 
06562 static int dahdi_answer(struct ast_channel *ast)
06563 {
06564    struct dahdi_pvt *p = ast->tech_pvt;
06565    int res = 0;
06566    int idx;
06567    ast_setstate(ast, AST_STATE_UP);/*! \todo XXX this is redundantly set by the analog and PRI submodules! */
06568    ast_mutex_lock(&p->lock);
06569    idx = dahdi_get_index(ast, p, 0);
06570    if (idx < 0)
06571       idx = SUB_REAL;
06572    /* nothing to do if a radio channel */
06573    if ((p->radio || (p->oprmode < 0))) {
06574       ast_mutex_unlock(&p->lock);
06575       return 0;
06576    }
06577 
06578    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06579       res = analog_answer(p->sig_pvt, ast);
06580       ast_mutex_unlock(&p->lock);
06581       return res;
06582    }
06583 
06584    switch (p->sig) {
06585 #if defined(HAVE_PRI)
06586    case SIG_PRI_LIB_HANDLE_CASES:
06587       res = sig_pri_answer(p->sig_pvt, ast);
06588       break;
06589 #endif   /* defined(HAVE_PRI) */
06590 #if defined(HAVE_SS7)
06591    case SIG_SS7:
06592       res = sig_ss7_answer(p->sig_pvt, ast);
06593       break;
06594 #endif   /* defined(HAVE_SS7) */
06595 #ifdef HAVE_OPENR2
06596    case SIG_MFCR2:
06597       if (!p->mfcr2_call_accepted) {
06598          /* The call was not accepted on offer nor the user, so it must be accepted now before answering,
06599             openr2_chan_answer_call will be called when the callback on_call_accepted is executed */
06600          p->mfcr2_answer_pending = 1;
06601          if (p->mfcr2_charge_calls) {
06602             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge before answering on chan %d\n", p->channel);
06603             openr2_chan_accept_call(p->r2chan, OR2_CALL_WITH_CHARGE);
06604          } else {
06605             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge before answering on chan %d\n", p->channel);
06606             openr2_chan_accept_call(p->r2chan, OR2_CALL_NO_CHARGE);
06607          }
06608       } else {
06609          ast_log(LOG_DEBUG, "Answering MFC/R2 call on chan %d\n", p->channel);
06610          dahdi_r2_answer(p);
06611       }
06612       break;
06613 #endif
06614    case 0:
06615       ast_mutex_unlock(&p->lock);
06616       return 0;
06617    default:
06618       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
06619       res = -1;
06620       break;
06621    }
06622    ast_mutex_unlock(&p->lock);
06623    return res;
06624 }
06625 
06626 static void disable_dtmf_detect(struct dahdi_pvt *p)
06627 {
06628    int val = 0;
06629 
06630    p->ignoredtmf = 1;
06631 
06632    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06633 
06634    if (!p->hardwaredtmf && p->dsp) {
06635       p->dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
06636       ast_dsp_set_features(p->dsp, p->dsp_features);
06637    }
06638 }
06639 
06640 static void enable_dtmf_detect(struct dahdi_pvt *p)
06641 {
06642    int val = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
06643 
06644    if (p->channel == CHAN_PSEUDO)
06645       return;
06646 
06647    p->ignoredtmf = 0;
06648 
06649    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06650 
06651    if (!p->hardwaredtmf && p->dsp) {
06652       p->dsp_features |= DSP_FEATURE_DIGIT_DETECT;
06653       ast_dsp_set_features(p->dsp, p->dsp_features);
06654    }
06655 }
06656 
06657 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
06658 {
06659    char *cp;
06660    struct dahdi_pvt *p = chan->tech_pvt;
06661 
06662    /* all supported options require data */
06663    if (!p || !data || (*datalen < 1)) {
06664       errno = EINVAL;
06665       return -1;
06666    }
06667 
06668    switch (option) {
06669    case AST_OPTION_DIGIT_DETECT:
06670       cp = (char *) data;
06671       *cp = p->ignoredtmf ? 0 : 1;
06672       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06673       break;
06674    case AST_OPTION_FAX_DETECT:
06675       cp = (char *) data;
06676       *cp = (p->dsp_features & DSP_FEATURE_FAX_DETECT) ? 0 : 1;
06677       ast_debug(1, "Reporting fax tone detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06678       break;
06679    case AST_OPTION_CC_AGENT_TYPE:
06680 #if defined(HAVE_PRI)
06681 #if defined(HAVE_PRI_CCSS)
06682       if (dahdi_sig_pri_lib_handles(p->sig)) {
06683          ast_copy_string((char *) data, dahdi_pri_cc_type, *datalen);
06684          break;
06685       }
06686 #endif   /* defined(HAVE_PRI_CCSS) */
06687 #endif   /* defined(HAVE_PRI) */
06688       return -1;
06689    default:
06690       return -1;
06691    }
06692 
06693    errno = 0;
06694 
06695    return 0;
06696 }
06697 
06698 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen)
06699 {
06700    char *cp;
06701    signed char *scp;
06702    int x;
06703    int idx;
06704    struct dahdi_pvt *p = chan->tech_pvt, *pp;
06705    struct oprmode *oprmode;
06706 
06707 
06708    /* all supported options require data */
06709    if (!p || !data || (datalen < 1)) {
06710       errno = EINVAL;
06711       return -1;
06712    }
06713 
06714    switch (option) {
06715    case AST_OPTION_TXGAIN:
06716       scp = (signed char *) data;
06717       idx = dahdi_get_index(chan, p, 0);
06718       if (idx < 0) {
06719          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
06720          return -1;
06721       }
06722       ast_debug(1, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
06723       return set_actual_txgain(p->subs[idx].dfd, p->txgain + (float) *scp, p->txdrc, p->law);
06724    case AST_OPTION_RXGAIN:
06725       scp = (signed char *) data;
06726       idx = dahdi_get_index(chan, p, 0);
06727       if (idx < 0) {
06728          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
06729          return -1;
06730       }
06731       ast_debug(1, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
06732       return set_actual_rxgain(p->subs[idx].dfd, p->rxgain + (float) *scp, p->rxdrc, p->law);
06733    case AST_OPTION_TONE_VERIFY:
06734       if (!p->dsp)
06735          break;
06736       cp = (char *) data;
06737       switch (*cp) {
06738       case 1:
06739          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
06740          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
06741          break;
06742       case 2:
06743          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
06744          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
06745          break;
06746       default:
06747          ast_debug(1, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
06748          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
06749          break;
06750       }
06751       break;
06752    case AST_OPTION_TDD:
06753       /* turn on or off TDD */
06754       cp = (char *) data;
06755       p->mate = 0;
06756       if (!*cp) { /* turn it off */
06757          ast_debug(1, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
06758          if (p->tdd)
06759             tdd_free(p->tdd);
06760          p->tdd = 0;
06761          break;
06762       }
06763       ast_debug(1, "Set option TDD MODE, value: %s(%d) on %s\n",
06764          (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
06765       dahdi_disable_ec(p);
06766       /* otherwise, turn it on */
06767       if (!p->didtdd) { /* if havent done it yet */
06768          unsigned char mybuf[41000];/*! \todo XXX This is an abuse of the stack!! */
06769          unsigned char *buf;
06770          int size, res, fd, len;
06771          struct pollfd fds[1];
06772 
06773          buf = mybuf;
06774          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
06775          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
06776          len = 40000;
06777          idx = dahdi_get_index(chan, p, 0);
06778          if (idx < 0) {
06779             ast_log(LOG_WARNING, "No index in TDD?\n");
06780             return -1;
06781          }
06782          fd = p->subs[idx].dfd;
06783          while (len) {
06784             if (ast_check_hangup(chan))
06785                return -1;
06786             size = len;
06787             if (size > READ_SIZE)
06788                size = READ_SIZE;
06789             fds[0].fd = fd;
06790             fds[0].events = POLLPRI | POLLOUT;
06791             fds[0].revents = 0;
06792             res = poll(fds, 1, -1);
06793             if (!res) {
06794                ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
06795                continue;
06796             }
06797             /* if got exception */
06798             if (fds[0].revents & POLLPRI)
06799                return -1;
06800             if (!(fds[0].revents & POLLOUT)) {
06801                ast_debug(1, "write fd not ready on channel %d\n", p->channel);
06802                continue;
06803             }
06804             res = write(fd, buf, size);
06805             if (res != size) {
06806                if (res == -1) return -1;
06807                ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
06808                break;
06809             }
06810             len -= size;
06811             buf += size;
06812          }
06813          p->didtdd = 1; /* set to have done it now */
06814       }
06815       if (*cp == 2) { /* Mate mode */
06816          if (p->tdd)
06817             tdd_free(p->tdd);
06818          p->tdd = 0;
06819          p->mate = 1;
06820          break;
06821       }
06822       if (!p->tdd) { /* if we don't have one yet */
06823          p->tdd = tdd_new(); /* allocate one */
06824       }
06825       break;
06826    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
06827       if (!p->dsp)
06828          break;
06829       cp = (char *) data;
06830       ast_debug(1, "Set option RELAX DTMF, value: %s(%d) on %s\n",
06831          *cp ? "ON" : "OFF", (int) *cp, chan->name);
06832       ast_dsp_set_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
06833       break;
06834    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
06835 #if defined(HAVE_PRI)
06836       if (dahdi_sig_pri_lib_handles(p->sig)
06837          && ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
06838          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
06839          break;
06840       }
06841 #endif   /* defined(HAVE_PRI) */
06842 
06843       cp = (char *) data;
06844       if (!*cp) {
06845          ast_debug(1, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
06846          x = 0;
06847          dahdi_disable_ec(p);
06848       } else {
06849          ast_debug(1, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
06850          x = 1;
06851       }
06852       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x) == -1)
06853          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", p->channel, x, strerror(errno));
06854       break;
06855    case AST_OPTION_OPRMODE:  /* Operator services mode */
06856       oprmode = (struct oprmode *) data;
06857       /* We don't support operator mode across technologies */
06858       if (strcasecmp(chan->tech->type, oprmode->peer->tech->type)) {
06859          ast_log(LOG_NOTICE, "Operator mode not supported on %s to %s calls.\n",
06860                chan->tech->type, oprmode->peer->tech->type);
06861          errno = EINVAL;
06862          return -1;
06863       }
06864       pp = oprmode->peer->tech_pvt;
06865       p->oprmode = pp->oprmode = 0;
06866       /* setup peers */
06867       p->oprpeer = pp;
06868       pp->oprpeer = p;
06869       /* setup modes, if any */
06870       if (oprmode->mode)
06871       {
06872          pp->oprmode = oprmode->mode;
06873          p->oprmode = -oprmode->mode;
06874       }
06875       ast_debug(1, "Set Operator Services mode, value: %d on %s/%s\n",
06876          oprmode->mode, chan->name,oprmode->peer->name);
06877       break;
06878    case AST_OPTION_ECHOCAN:
06879       cp = (char *) data;
06880       if (*cp) {
06881          ast_debug(1, "Enabling echo cancellation on %s\n", chan->name);
06882          dahdi_enable_ec(p);
06883       } else {
06884          ast_debug(1, "Disabling echo cancellation on %s\n", chan->name);
06885          dahdi_disable_ec(p);
06886       }
06887       break;
06888    case AST_OPTION_DIGIT_DETECT:
06889       cp = (char *) data;
06890       ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
06891       if (*cp) {
06892          enable_dtmf_detect(p);
06893       } else {
06894          disable_dtmf_detect(p);
06895       }
06896       break;
06897    case AST_OPTION_FAX_DETECT:
06898       cp = (char *) data;
06899       if (p->dsp) {
06900          ast_debug(1, "%sabling fax tone detection on %s\n", *cp ? "En" : "Dis", chan->name);
06901          if (*cp) {
06902             p->dsp_features |= DSP_FEATURE_FAX_DETECT;
06903          } else {
06904             p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
06905          }
06906          ast_dsp_set_features(p->dsp, p->dsp_features);
06907       }
06908       break;
06909    default:
06910       return -1;
06911    }
06912    errno = 0;
06913 
06914    return 0;
06915 }
06916 
06917 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
06918 {
06919    struct dahdi_pvt *p = chan->tech_pvt;
06920    int res = 0;
06921 
06922    if (!p) {
06923       /* No private structure! */
06924       *buf = '\0';
06925       return -1;
06926    }
06927 
06928    if (!strcasecmp(data, "rxgain")) {
06929       ast_mutex_lock(&p->lock);
06930       snprintf(buf, len, "%f", p->rxgain);
06931       ast_mutex_unlock(&p->lock);
06932    } else if (!strcasecmp(data, "txgain")) {
06933       ast_mutex_lock(&p->lock);
06934       snprintf(buf, len, "%f", p->txgain);
06935       ast_mutex_unlock(&p->lock);
06936    } else if (!strcasecmp(data, "dahdi_channel")) {
06937       ast_mutex_lock(&p->lock);
06938       snprintf(buf, len, "%d", p->channel);
06939       ast_mutex_unlock(&p->lock);
06940    } else if (!strcasecmp(data, "dahdi_span")) {
06941       ast_mutex_lock(&p->lock);
06942       snprintf(buf, len, "%d", p->span);
06943       ast_mutex_unlock(&p->lock);
06944    } else if (!strcasecmp(data, "dahdi_type")) {
06945       ast_mutex_lock(&p->lock);
06946       switch (p->sig) {
06947 #if defined(HAVE_OPENR2)
06948       case SIG_MFCR2:
06949          ast_copy_string(buf, "mfc/r2", len);
06950          break;
06951 #endif   /* defined(HAVE_OPENR2) */
06952 #if defined(HAVE_PRI)
06953       case SIG_PRI_LIB_HANDLE_CASES:
06954          ast_copy_string(buf, "pri", len);
06955          break;
06956 #endif   /* defined(HAVE_PRI) */
06957       case 0:
06958          ast_copy_string(buf, "pseudo", len);
06959          break;
06960 #if defined(HAVE_SS7)
06961       case SIG_SS7:
06962          ast_copy_string(buf, "ss7", len);
06963          break;
06964 #endif   /* defined(HAVE_SS7) */
06965       default:
06966          /* The only thing left is analog ports. */
06967          ast_copy_string(buf, "analog", len);
06968          break;
06969       }
06970       ast_mutex_unlock(&p->lock);
06971 #if defined(HAVE_PRI)
06972 #if defined(HAVE_PRI_REVERSE_CHARGE)
06973    } else if (!strcasecmp(data, "reversecharge")) {
06974       ast_mutex_lock(&p->lock);
06975       switch (p->sig) {
06976       case SIG_PRI_LIB_HANDLE_CASES:
06977          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->reverse_charging_indication);
06978          break;
06979       default:
06980          *buf = '\0';
06981          res = -1;
06982          break;
06983       }
06984       ast_mutex_unlock(&p->lock);
06985 #endif
06986 #if defined(HAVE_PRI_SETUP_KEYPAD)
06987    } else if (!strcasecmp(data, "keypad_digits")) {
06988       ast_mutex_lock(&p->lock);
06989       switch (p->sig) {
06990       case SIG_PRI_LIB_HANDLE_CASES:
06991          ast_copy_string(buf, ((struct sig_pri_chan *) p->sig_pvt)->keypad_digits,
06992             len);
06993          break;
06994       default:
06995          *buf = '\0';
06996          res = -1;
06997          break;
06998       }
06999       ast_mutex_unlock(&p->lock);
07000 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
07001    } else if (!strcasecmp(data, "no_media_path")) {
07002       ast_mutex_lock(&p->lock);
07003       switch (p->sig) {
07004       case SIG_PRI_LIB_HANDLE_CASES:
07005          /*
07006           * TRUE if the call is on hold or is call waiting because
07007           * there is no media path available.
07008           */
07009          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel);
07010          break;
07011       default:
07012          *buf = '\0';
07013          res = -1;
07014          break;
07015       }
07016       ast_mutex_unlock(&p->lock);
07017 #endif   /* defined(HAVE_PRI) */
07018    } else {
07019       *buf = '\0';
07020       res = -1;
07021    }
07022 
07023    return res;
07024 }
07025 
07026 
07027 static int parse_buffers_policy(const char *parse, int *num_buffers, int *policy)
07028 {
07029    int res;
07030    char policy_str[21] = "";
07031 
07032    if ((res = sscanf(parse, "%30d,%20s", num_buffers, policy_str)) != 2) {
07033       ast_log(LOG_WARNING, "Parsing buffer string '%s' failed.\n", parse);
07034       return 1;
07035    }
07036    if (*num_buffers < 0) {
07037       ast_log(LOG_WARNING, "Invalid buffer count given '%d'.\n", *num_buffers);
07038       return -1;
07039    }
07040    if (!strcasecmp(policy_str, "full")) {
07041       *policy = DAHDI_POLICY_WHEN_FULL;
07042    } else if (!strcasecmp(policy_str, "immediate")) {
07043       *policy = DAHDI_POLICY_IMMEDIATE;
07044 #if defined(HAVE_DAHDI_HALF_FULL)
07045    } else if (!strcasecmp(policy_str, "half")) {
07046       *policy = DAHDI_POLICY_HALF_FULL;
07047 #endif
07048    } else {
07049       ast_log(LOG_WARNING, "Invalid policy name given '%s'.\n", policy_str);
07050       return -1;
07051    }
07052 
07053    return 0;
07054 }
07055 
07056 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value)
07057 {
07058    struct dahdi_pvt *p = chan->tech_pvt;
07059    int res = 0;
07060 
07061    if (!p) {
07062       /* No private structure! */
07063       return -1;
07064    }
07065 
07066    if (!strcasecmp(data, "buffers")) {
07067       int num_bufs, policy;
07068 
07069       if (!(parse_buffers_policy(value, &num_bufs, &policy))) {
07070          struct dahdi_bufferinfo bi = {
07071             .txbufpolicy = policy,
07072             .rxbufpolicy = policy,
07073             .bufsize = p->bufsize,
07074             .numbufs = num_bufs,
07075          };
07076          int bpres;
07077 
07078          if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07079             ast_log(LOG_WARNING, "Channel '%d' unable to override buffer policy: %s\n", p->channel, strerror(errno));
07080          } else {
07081             p->bufferoverrideinuse = 1;
07082          }
07083       } else {
07084          res = -1;
07085       }
07086    } else if (!strcasecmp(data, "echocan_mode")) {
07087       if (!strcasecmp(value, "on")) {
07088          ast_mutex_lock(&p->lock);
07089          dahdi_enable_ec(p);
07090          ast_mutex_unlock(&p->lock);
07091       } else if (!strcasecmp(value, "off")) {
07092          ast_mutex_lock(&p->lock);
07093          dahdi_disable_ec(p);
07094          ast_mutex_unlock(&p->lock);
07095 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07096       } else if (!strcasecmp(value, "fax")) {
07097          int blah = 1;
07098 
07099          ast_mutex_lock(&p->lock);
07100          if (!p->echocanon) {
07101             dahdi_enable_ec(p);
07102          }
07103          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
07104             ast_log(LOG_WARNING, "Unable to place echocan into fax mode on channel %d: %s\n", p->channel, strerror(errno));
07105          }
07106          ast_mutex_unlock(&p->lock);
07107       } else if (!strcasecmp(value, "voice")) {
07108          int blah = 0;
07109 
07110          ast_mutex_lock(&p->lock);
07111          if (!p->echocanon) {
07112             dahdi_enable_ec(p);
07113          }
07114          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
07115             ast_log(LOG_WARNING, "Unable to place echocan into voice mode on channel %d: %s\n", p->channel, strerror(errno));
07116          }
07117          ast_mutex_unlock(&p->lock);
07118 #endif
07119       } else {
07120          ast_log(LOG_WARNING, "Unsupported value '%s' provided for '%s' item.\n", value, data);
07121          res = -1;
07122       }
07123    } else {
07124       res = -1;
07125    }
07126 
07127    return res;
07128 }
07129 
07130 static void dahdi_unlink(struct dahdi_pvt *slave, struct dahdi_pvt *master, int needlock)
07131 {
07132    /* Unlink a specific slave or all slaves/masters from a given master */
07133    int x;
07134    int hasslaves;
07135    if (!master)
07136       return;
07137    if (needlock) {
07138       ast_mutex_lock(&master->lock);
07139       if (slave) {
07140          while (ast_mutex_trylock(&slave->lock)) {
07141             DEADLOCK_AVOIDANCE(&master->lock);
07142          }
07143       }
07144    }
07145    hasslaves = 0;
07146    for (x = 0; x < MAX_SLAVES; x++) {
07147       if (master->slaves[x]) {
07148          if (!slave || (master->slaves[x] == slave)) {
07149             /* Take slave out of the conference */
07150             ast_debug(1, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
07151             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
07152             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
07153             master->slaves[x]->master = NULL;
07154             master->slaves[x] = NULL;
07155          } else
07156             hasslaves = 1;
07157       }
07158       if (!hasslaves)
07159          master->inconference = 0;
07160    }
07161    if (!slave) {
07162       if (master->master) {
07163          /* Take master out of the conference */
07164          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
07165          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
07166          hasslaves = 0;
07167          for (x = 0; x < MAX_SLAVES; x++) {
07168             if (master->master->slaves[x] == master)
07169                master->master->slaves[x] = NULL;
07170             else if (master->master->slaves[x])
07171                hasslaves = 1;
07172          }
07173          if (!hasslaves)
07174             master->master->inconference = 0;
07175       }
07176       master->master = NULL;
07177    }
07178    update_conf(master);
07179    if (needlock) {
07180       if (slave)
07181          ast_mutex_unlock(&slave->lock);
07182       ast_mutex_unlock(&master->lock);
07183    }
07184 }
07185 
07186 static void dahdi_link(struct dahdi_pvt *slave, struct dahdi_pvt *master) {
07187    int x;
07188    if (!slave || !master) {
07189       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
07190       return;
07191    }
07192    for (x = 0; x < MAX_SLAVES; x++) {
07193       if (!master->slaves[x]) {
07194          master->slaves[x] = slave;
07195          break;
07196       }
07197    }
07198    if (x >= MAX_SLAVES) {
07199       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
07200       master->slaves[MAX_SLAVES - 1] = slave;
07201    }
07202    if (slave->master)
07203       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
07204    slave->master = master;
07205 
07206    ast_debug(1, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
07207 }
07208 
07209 static enum ast_bridge_result dahdi_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
07210 {
07211    struct ast_channel *who;
07212    struct dahdi_pvt *p0, *p1, *op0, *op1;
07213    struct dahdi_pvt *master = NULL, *slave = NULL;
07214    struct ast_frame *f;
07215    int inconf = 0;
07216    int nothingok = 1;
07217    int ofd0, ofd1;
07218    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
07219    int os0 = -1, os1 = -1;
07220    int priority = 0;
07221    struct ast_channel *oc0, *oc1;
07222    enum ast_bridge_result res;
07223 #ifdef PRI_2BCT
07224    int triedtopribridge = 0;
07225    q931_call *q931c0;
07226    q931_call *q931c1;
07227 #endif
07228 
07229    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
07230       There is code below to handle it properly until DTMF is actually seen,
07231       but due to currently unresolved issues it's ignored...
07232    */
07233 
07234    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
07235       return AST_BRIDGE_FAILED_NOWARN;
07236 
07237    ast_channel_lock(c0);
07238    while (ast_channel_trylock(c1)) {
07239       CHANNEL_DEADLOCK_AVOIDANCE(c0);
07240    }
07241 
07242    p0 = c0->tech_pvt;
07243    p1 = c1->tech_pvt;
07244    /* cant do pseudo-channels here */
07245    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
07246       ast_channel_unlock(c0);
07247       ast_channel_unlock(c1);
07248       return AST_BRIDGE_FAILED_NOWARN;
07249    }
07250 
07251    oi0 = dahdi_get_index(c0, p0, 0);
07252    oi1 = dahdi_get_index(c1, p1, 0);
07253    if ((oi0 < 0) || (oi1 < 0)) {
07254       ast_channel_unlock(c0);
07255       ast_channel_unlock(c1);
07256       return AST_BRIDGE_FAILED;
07257    }
07258 
07259    op0 = p0 = c0->tech_pvt;
07260    op1 = p1 = c1->tech_pvt;
07261    ofd0 = c0->fds[0];
07262    ofd1 = c1->fds[0];
07263    oc0 = p0->owner;
07264    oc1 = p1->owner;
07265 
07266    if (ast_mutex_trylock(&p0->lock)) {
07267       /* Don't block, due to potential for deadlock */
07268       ast_channel_unlock(c0);
07269       ast_channel_unlock(c1);
07270       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
07271       return AST_BRIDGE_RETRY;
07272    }
07273    if (ast_mutex_trylock(&p1->lock)) {
07274       /* Don't block, due to potential for deadlock */
07275       ast_mutex_unlock(&p0->lock);
07276       ast_channel_unlock(c0);
07277       ast_channel_unlock(c1);
07278       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
07279       return AST_BRIDGE_RETRY;
07280    }
07281 
07282    if ((p0->callwaiting && p0->callwaitingcallerid)
07283       || (p1->callwaiting && p1->callwaitingcallerid)) {
07284       /*
07285        * Call Waiting Caller ID requires DTMF detection to know if it
07286        * can send the CID spill.
07287        *
07288        * For now, don't attempt to native bridge if either channel
07289        * needs DTMF detection.  There is code below to handle it
07290        * properly until DTMF is actually seen, but due to currently
07291        * unresolved issues it's ignored...
07292        */
07293       ast_mutex_unlock(&p0->lock);
07294       ast_mutex_unlock(&p1->lock);
07295       ast_channel_unlock(c0);
07296       ast_channel_unlock(c1);
07297       return AST_BRIDGE_FAILED_NOWARN;
07298    }
07299 
07300 #if defined(HAVE_PRI)
07301    if ((dahdi_sig_pri_lib_handles(p0->sig)
07302          && ((struct sig_pri_chan *) p0->sig_pvt)->no_b_channel)
07303       || (dahdi_sig_pri_lib_handles(p1->sig)
07304          && ((struct sig_pri_chan *) p1->sig_pvt)->no_b_channel)) {
07305       /*
07306        * PRI nobch channels (hold and call waiting) are equivalent to
07307        * pseudo channels and cannot be done here.
07308        */
07309       ast_mutex_unlock(&p0->lock);
07310       ast_mutex_unlock(&p1->lock);
07311       ast_channel_unlock(c0);
07312       ast_channel_unlock(c1);
07313       return AST_BRIDGE_FAILED_NOWARN;
07314    }
07315 #endif   /* defined(HAVE_PRI) */
07316 
07317    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07318       if (p0->owner && p1->owner) {
07319          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
07320          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
07321             master = p0;
07322             slave = p1;
07323             inconf = 1;
07324          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
07325             master = p1;
07326             slave = p0;
07327             inconf = 1;
07328          } else {
07329             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
07330             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
07331                p0->channel,
07332                oi0, (p0->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07333                p0->subs[SUB_REAL].inthreeway, p0->channel,
07334                oi0, (p1->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07335                p1->subs[SUB_REAL].inthreeway);
07336          }
07337          nothingok = 0;
07338       }
07339    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
07340       if (p1->subs[SUB_THREEWAY].inthreeway) {
07341          master = p1;
07342          slave = p0;
07343          nothingok = 0;
07344       }
07345    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
07346       if (p0->subs[SUB_THREEWAY].inthreeway) {
07347          master = p0;
07348          slave = p1;
07349          nothingok = 0;
07350       }
07351    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
07352       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise,
07353          don't put us in anything */
07354       if (p1->subs[SUB_CALLWAIT].inthreeway) {
07355          master = p1;
07356          slave = p0;
07357          nothingok = 0;
07358       }
07359    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
07360       /* Same as previous */
07361       if (p0->subs[SUB_CALLWAIT].inthreeway) {
07362          master = p0;
07363          slave = p1;
07364          nothingok = 0;
07365       }
07366    }
07367    ast_debug(1, "master: %d, slave: %d, nothingok: %d\n",
07368       master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
07369    if (master && slave) {
07370       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
07371          in an active threeway call with a channel that is ringing, we should
07372          indicate ringing. */
07373       if ((oi1 == SUB_THREEWAY) &&
07374          p1->subs[SUB_THREEWAY].inthreeway &&
07375          p1->subs[SUB_REAL].owner &&
07376          p1->subs[SUB_REAL].inthreeway &&
07377          (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07378          ast_debug(1,
07379             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
07380             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
07381          tone_zone_play_tone(p0->subs[oi0].dfd, DAHDI_TONE_RINGTONE);
07382          os1 = p1->subs[SUB_REAL].owner->_state;
07383       } else {
07384          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
07385             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
07386          tone_zone_play_tone(p0->subs[oi0].dfd, -1);
07387       }
07388       if ((oi0 == SUB_THREEWAY) &&
07389          p0->subs[SUB_THREEWAY].inthreeway &&
07390          p0->subs[SUB_REAL].owner &&
07391          p0->subs[SUB_REAL].inthreeway &&
07392          (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07393          ast_debug(1,
07394             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
07395             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
07396          tone_zone_play_tone(p1->subs[oi1].dfd, DAHDI_TONE_RINGTONE);
07397          os0 = p0->subs[SUB_REAL].owner->_state;
07398       } else {
07399          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
07400             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
07401          tone_zone_play_tone(p1->subs[oi1].dfd, -1);
07402       }
07403       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07404          if (!p0->echocanbridged || !p1->echocanbridged) {
07405             /* Disable echo cancellation if appropriate */
07406             dahdi_disable_ec(p0);
07407             dahdi_disable_ec(p1);
07408          }
07409       }
07410       dahdi_link(slave, master);
07411       master->inconference = inconf;
07412    } else if (!nothingok)
07413       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
07414 
07415    update_conf(p0);
07416    update_conf(p1);
07417    t0 = p0->subs[SUB_REAL].inthreeway;
07418    t1 = p1->subs[SUB_REAL].inthreeway;
07419 
07420    ast_mutex_unlock(&p0->lock);
07421    ast_mutex_unlock(&p1->lock);
07422 
07423    ast_channel_unlock(c0);
07424    ast_channel_unlock(c1);
07425 
07426    /* Native bridge failed */
07427    if ((!master || !slave) && !nothingok) {
07428       dahdi_enable_ec(p0);
07429       dahdi_enable_ec(p1);
07430       return AST_BRIDGE_FAILED;
07431    }
07432 
07433    ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
07434 
07435    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07436       disable_dtmf_detect(op0);
07437 
07438    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07439       disable_dtmf_detect(op1);
07440 
07441    for (;;) {
07442       struct ast_channel *c0_priority[2] = {c0, c1};
07443       struct ast_channel *c1_priority[2] = {c1, c0};
07444 
07445       /* Here's our main loop...  Start by locking things, looking for private parts,
07446          and then balking if anything is wrong */
07447 
07448       ast_channel_lock(c0);
07449       while (ast_channel_trylock(c1)) {
07450          CHANNEL_DEADLOCK_AVOIDANCE(c0);
07451       }
07452 
07453       p0 = c0->tech_pvt;
07454       p1 = c1->tech_pvt;
07455 
07456       if (op0 == p0)
07457          i0 = dahdi_get_index(c0, p0, 1);
07458       if (op1 == p1)
07459          i1 = dahdi_get_index(c1, p1, 1);
07460 
07461       ast_channel_unlock(c0);
07462       ast_channel_unlock(c1);
07463 
07464       if (!timeoutms ||
07465          (op0 != p0) ||
07466          (op1 != p1) ||
07467          (ofd0 != c0->fds[0]) ||
07468          (ofd1 != c1->fds[0]) ||
07469          (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
07470          (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
07471          (oc0 != p0->owner) ||
07472          (oc1 != p1->owner) ||
07473          (t0 != p0->subs[SUB_REAL].inthreeway) ||
07474          (t1 != p1->subs[SUB_REAL].inthreeway) ||
07475          (oi0 != i0) ||
07476          (oi1 != i1)) {
07477          ast_debug(1, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
07478             op0->channel, oi0, op1->channel, oi1);
07479          res = AST_BRIDGE_RETRY;
07480          goto return_from_bridge;
07481       }
07482 
07483 #ifdef PRI_2BCT
07484       if (!triedtopribridge) {
07485          triedtopribridge = 1;
07486          if (p0->pri && p0->pri == p1->pri && p0->pri->transfer) {
07487             ast_mutex_lock(&p0->pri->lock);
07488             switch (p0->sig) {
07489             case SIG_PRI_LIB_HANDLE_CASES:
07490                q931c0 = ((struct sig_pri_chan *) (p0->sig_pvt))->call;
07491                break;
07492             default:
07493                q931c0 = NULL;
07494                break;
07495             }
07496             switch (p1->sig) {
07497             case SIG_PRI_LIB_HANDLE_CASES:
07498                q931c1 = ((struct sig_pri_chan *) (p1->sig_pvt))->call;
07499                break;
07500             default:
07501                q931c1 = NULL;
07502                break;
07503             }
07504             if (q931c0 && q931c1) {
07505                pri_channel_bridge(q931c0, q931c1);
07506             }
07507             ast_mutex_unlock(&p0->pri->lock);
07508          }
07509       }
07510 #endif
07511 
07512       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
07513       if (!who) {
07514          ast_debug(1, "Ooh, empty read...\n");
07515          continue;
07516       }
07517       f = ast_read(who);
07518       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
07519          *fo = f;
07520          *rc = who;
07521          res = AST_BRIDGE_COMPLETE;
07522          goto return_from_bridge;
07523       }
07524       if (f->frametype == AST_FRAME_DTMF) {
07525          if ((who == c0) && p0->pulsedial) {
07526             ast_write(c1, f);
07527          } else if ((who == c1) && p1->pulsedial) {
07528             ast_write(c0, f);
07529          } else {
07530             *fo = f;
07531             *rc = who;
07532             res = AST_BRIDGE_COMPLETE;
07533             goto return_from_bridge;
07534          }
07535       }
07536       ast_frfree(f);
07537 
07538       /* Swap who gets priority */
07539       priority = !priority;
07540    }
07541 
07542 return_from_bridge:
07543    if (op0 == p0)
07544       dahdi_enable_ec(p0);
07545 
07546    if (op1 == p1)
07547       dahdi_enable_ec(p1);
07548 
07549    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07550       enable_dtmf_detect(op0);
07551 
07552    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07553       enable_dtmf_detect(op1);
07554 
07555    dahdi_unlink(slave, master, 1);
07556 
07557    return res;
07558 }
07559 
07560 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07561 {
07562    struct dahdi_pvt *p = newchan->tech_pvt;
07563    int x;
07564 
07565    ast_mutex_lock(&p->lock);
07566 
07567    ast_debug(1, "New owner for channel %d is %s\n", p->channel, newchan->name);
07568    if (p->owner == oldchan) {
07569       p->owner = newchan;
07570    }
07571    for (x = 0; x < 3; x++) {
07572       if (p->subs[x].owner == oldchan) {
07573          if (!x) {
07574             dahdi_unlink(NULL, p, 0);
07575          }
07576          p->subs[x].owner = newchan;
07577       }
07578    }
07579    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
07580       analog_fixup(oldchan, newchan, p->sig_pvt);
07581 #if defined(HAVE_PRI)
07582    } else if (dahdi_sig_pri_lib_handles(p->sig)) {
07583       sig_pri_fixup(oldchan, newchan, p->sig_pvt);
07584 #endif   /* defined(HAVE_PRI) */
07585 #if defined(HAVE_SS7)
07586    } else if (p->sig == SIG_SS7) {
07587       sig_ss7_fixup(oldchan, newchan, p->sig_pvt);
07588 #endif   /* defined(HAVE_SS7) */
07589    }
07590    update_conf(p);
07591 
07592    ast_mutex_unlock(&p->lock);
07593 
07594    if (newchan->_state == AST_STATE_RINGING) {
07595       dahdi_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
07596    }
07597    return 0;
07598 }
07599 
07600 static int dahdi_ring_phone(struct dahdi_pvt *p)
07601 {
07602    int x;
07603    int res;
07604    /* Make sure our transmit state is on hook */
07605    x = 0;
07606    x = DAHDI_ONHOOK;
07607    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07608    do {
07609       x = DAHDI_RING;
07610       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07611       if (res) {
07612          switch (errno) {
07613          case EBUSY:
07614          case EINTR:
07615             /* Wait just in case */
07616             usleep(10000);
07617             continue;
07618          case EINPROGRESS:
07619             res = 0;
07620             break;
07621          default:
07622             ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
07623             res = 0;
07624          }
07625       }
07626    } while (res);
07627    return res;
07628 }
07629 
07630 static void *analog_ss_thread(void *data);
07631 
07632 static int attempt_transfer(struct dahdi_pvt *p)
07633 {
07634    /* In order to transfer, we need at least one of the channels to
07635       actually be in a call bridge.  We can't conference two applications
07636       together (but then, why would we want to?) */
07637    if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
07638       /* The three-way person we're about to transfer to could still be in MOH, so
07639          stop if now if appropriate */
07640       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
07641          ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
07642       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
07643          ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
07644       }
07645       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
07646          tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, DAHDI_TONE_RINGTONE);
07647       }
07648        if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
07649          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07650                ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
07651          return -1;
07652       }
07653       /* Orphan the channel after releasing the lock */
07654       ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07655       unalloc_sub(p, SUB_THREEWAY);
07656    } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
07657       ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
07658       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
07659          ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
07660       }
07661       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
07662          tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
07663       }
07664       if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
07665          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07666                ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
07667          return -1;
07668       }
07669       /* Three-way is now the REAL */
07670       swap_subs(p, SUB_THREEWAY, SUB_REAL);
07671       ast_channel_unlock(p->subs[SUB_REAL].owner);
07672       unalloc_sub(p, SUB_THREEWAY);
07673       /* Tell the caller not to hangup */
07674       return 1;
07675    } else {
07676       ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
07677          p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
07678       p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07679       return -1;
07680    }
07681    return 0;
07682 }
07683 
07684 static int check_for_conference(struct dahdi_pvt *p)
07685 {
07686    struct dahdi_confinfo ci;
07687    /* Fine if we already have a master, etc */
07688    if (p->master || (p->confno > -1))
07689       return 0;
07690    memset(&ci, 0, sizeof(ci));
07691    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
07692       ast_log(LOG_WARNING, "Failed to get conference info on channel %d: %s\n", p->channel, strerror(errno));
07693       return 0;
07694    }
07695    /* If we have no master and don't have a confno, then
07696       if we're in a conference, it's probably a MeetMe room or
07697       some such, so don't let us 3-way out! */
07698    if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
07699       ast_verb(3, "Avoiding 3-way call when in an external conference\n");
07700       return 1;
07701    }
07702    return 0;
07703 }
07704 
07705 /*! Checks channel for alarms
07706  * \param p a channel to check for alarms.
07707  * \returns the alarms on the span to which the channel belongs, or alarms on
07708  *          the channel if no span alarms.
07709  */
07710 static int get_alarms(struct dahdi_pvt *p)
07711 {
07712    int res;
07713    struct dahdi_spaninfo zi;
07714    struct dahdi_params params;
07715 
07716    memset(&zi, 0, sizeof(zi));
07717    zi.spanno = p->span;
07718 
07719    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SPANSTAT, &zi)) >= 0) {
07720       if (zi.alarms != DAHDI_ALARM_NONE)
07721          return zi.alarms;
07722    } else {
07723       ast_log(LOG_WARNING, "Unable to determine alarm on channel %d: %s\n", p->channel, strerror(errno));
07724       return 0;
07725    }
07726 
07727    /* No alarms on the span. Check for channel alarms. */
07728    memset(&params, 0, sizeof(params));
07729    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &params)) >= 0)
07730       return params.chan_alarms;
07731 
07732    ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
07733 
07734    return DAHDI_ALARM_NONE;
07735 }
07736 
07737 static void dahdi_handle_dtmf(struct ast_channel *ast, int idx, struct ast_frame **dest)
07738 {
07739    struct dahdi_pvt *p = ast->tech_pvt;
07740    struct ast_frame *f = *dest;
07741 
07742    ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
07743       f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
07744       f->subclass.integer, f->subclass.integer, ast->name);
07745 
07746    if (p->confirmanswer) {
07747       if (f->frametype == AST_FRAME_DTMF_END) {
07748          ast_debug(1, "Confirm answer on %s!\n", ast->name);
07749          /* Upon receiving a DTMF digit, consider this an answer confirmation instead
07750             of a DTMF digit */
07751          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07752          p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07753          /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
07754          p->confirmanswer = 0;
07755       } else {
07756          p->subs[idx].f.frametype = AST_FRAME_NULL;
07757          p->subs[idx].f.subclass.integer = 0;
07758       }
07759       *dest = &p->subs[idx].f;
07760    } else if (p->callwaitcas) {
07761       if (f->frametype == AST_FRAME_DTMF_END) {
07762          if ((f->subclass.integer == 'A') || (f->subclass.integer == 'D')) {
07763             ast_debug(1, "Got some DTMF, but it's for the CAS\n");
07764             ast_free(p->cidspill);
07765             p->cidspill = NULL;
07766             send_cwcidspill(p);
07767          }
07768          p->callwaitcas = 0;
07769       }
07770       p->subs[idx].f.frametype = AST_FRAME_NULL;
07771       p->subs[idx].f.subclass.integer = 0;
07772       *dest = &p->subs[idx].f;
07773    } else if (f->subclass.integer == 'f') {
07774       if (f->frametype == AST_FRAME_DTMF_END) {
07775          /* Fax tone -- Handle and return NULL */
07776          if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
07777             /* If faxbuffers are configured, use them for the fax transmission */
07778             if (p->usefaxbuffers && !p->bufferoverrideinuse) {
07779                struct dahdi_bufferinfo bi = {
07780                   .txbufpolicy = p->faxbuf_policy,
07781                   .bufsize = p->bufsize,
07782                   .numbufs = p->faxbuf_no
07783                };
07784                int res;
07785 
07786                if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07787                   ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
07788                } else {
07789                   p->bufferoverrideinuse = 1;
07790                }
07791             }
07792             p->faxhandled = 1;
07793             if (p->dsp) {
07794                p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
07795                ast_dsp_set_features(p->dsp, p->dsp_features);
07796                ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
07797             }
07798             if (strcmp(ast->exten, "fax")) {
07799                const char *target_context = S_OR(ast->macrocontext, ast->context);
07800 
07801                /* We need to unlock 'ast' here because ast_exists_extension has the
07802                 * potential to start autoservice on the channel. Such action is prone
07803                 * to deadlock.
07804                 */
07805                ast_mutex_unlock(&p->lock);
07806                ast_channel_unlock(ast);
07807                if (ast_exists_extension(ast, target_context, "fax", 1,
07808                   S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07809                   ast_channel_lock(ast);
07810                   ast_mutex_lock(&p->lock);
07811                   ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
07812                   /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
07813                   pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07814                   if (ast_async_goto(ast, target_context, "fax", 1))
07815                      ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07816                } else {
07817                   ast_channel_lock(ast);
07818                   ast_mutex_lock(&p->lock);
07819                   ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
07820                }
07821             } else {
07822                ast_debug(1, "Already in a fax extension, not redirecting\n");
07823             }
07824          } else {
07825             ast_debug(1, "Fax already handled\n");
07826          }
07827          dahdi_confmute(p, 0);
07828       }
07829       p->subs[idx].f.frametype = AST_FRAME_NULL;
07830       p->subs[idx].f.subclass.integer = 0;
07831       *dest = &p->subs[idx].f;
07832    }
07833 }
07834 
07835 static void handle_alarms(struct dahdi_pvt *p, int alms)
07836 {
07837    const char *alarm_str;
07838 
07839 #if defined(HAVE_PRI)
07840    if (dahdi_sig_pri_lib_handles(p->sig) && sig_pri_is_alarm_ignored(p->pri)) {
07841       return;
07842    }
07843 #endif   /* defined(HAVE_PRI) */
07844 
07845    alarm_str = alarm2str(alms);
07846    if (report_alarms & REPORT_CHANNEL_ALARMS) {
07847       ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm_str);
07848       manager_event(EVENT_FLAG_SYSTEM, "Alarm",
07849                  "Alarm: %s\r\n"
07850                  "Channel: %d\r\n",
07851                  alarm_str, p->channel);
07852    }
07853 
07854    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
07855       ast_log(LOG_WARNING, "Detected alarm on span %d: %s\n", p->span, alarm_str);
07856       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarm",
07857                  "Alarm: %s\r\n"
07858                  "Span: %d\r\n",
07859                  alarm_str, p->span);
07860    }
07861 }
07862 
07863 static struct ast_frame *dahdi_handle_event(struct ast_channel *ast)
07864 {
07865    int res, x;
07866    int idx, mysig;
07867    char *c;
07868    struct dahdi_pvt *p = ast->tech_pvt;
07869    pthread_t threadid;
07870    struct ast_channel *chan;
07871    struct ast_frame *f;
07872 
07873    idx = dahdi_get_index(ast, p, 0);
07874    if (idx < 0) {
07875       return &ast_null_frame;
07876    }
07877    mysig = p->sig;
07878    if (p->outsigmod > -1)
07879       mysig = p->outsigmod;
07880    p->subs[idx].f.frametype = AST_FRAME_NULL;
07881    p->subs[idx].f.subclass.integer = 0;
07882    p->subs[idx].f.datalen = 0;
07883    p->subs[idx].f.samples = 0;
07884    p->subs[idx].f.mallocd = 0;
07885    p->subs[idx].f.offset = 0;
07886    p->subs[idx].f.src = "dahdi_handle_event";
07887    p->subs[idx].f.data.ptr = NULL;
07888    f = &p->subs[idx].f;
07889 
07890    if (p->fake_event) {
07891       res = p->fake_event;
07892       p->fake_event = 0;
07893    } else
07894       res = dahdi_get_event(p->subs[idx].dfd);
07895 
07896    ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, idx);
07897 
07898    if (res & (DAHDI_EVENT_PULSEDIGIT | DAHDI_EVENT_DTMFUP)) {
07899       p->pulsedial = (res & DAHDI_EVENT_PULSEDIGIT) ? 1 : 0;
07900       ast_debug(1, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
07901 #if defined(HAVE_PRI)
07902       if (dahdi_sig_pri_lib_handles(p->sig)
07903          && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
07904          && p->pri
07905          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07906          /* absorb event */
07907       } else
07908 #endif   /* defined(HAVE_PRI) */
07909       {
07910          /* Unmute conference */
07911          dahdi_confmute(p, 0);
07912          p->subs[idx].f.frametype = AST_FRAME_DTMF_END;
07913          p->subs[idx].f.subclass.integer = res & 0xff;
07914          dahdi_handle_dtmf(ast, idx, &f);
07915       }
07916       return f;
07917    }
07918 
07919    if (res & DAHDI_EVENT_DTMFDOWN) {
07920       ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
07921 #if defined(HAVE_PRI)
07922       if (dahdi_sig_pri_lib_handles(p->sig)
07923          && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
07924          && p->pri
07925          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07926          /* absorb event */
07927       } else
07928 #endif   /* defined(HAVE_PRI) */
07929       {
07930          /* Mute conference */
07931          dahdi_confmute(p, 1);
07932          p->subs[idx].f.frametype = AST_FRAME_DTMF_BEGIN;
07933          p->subs[idx].f.subclass.integer = res & 0xff;
07934          dahdi_handle_dtmf(ast, idx, &f);
07935       }
07936       return &p->subs[idx].f;
07937    }
07938 
07939    switch (res) {
07940    case DAHDI_EVENT_EC_DISABLED:
07941       ast_verb(3, "Channel %d echo canceler disabled.\n", p->channel);
07942       p->echocanon = 0;
07943       break;
07944 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07945    case DAHDI_EVENT_TX_CED_DETECTED:
07946       ast_verb(3, "Channel %d detected a CED tone towards the network.\n", p->channel);
07947       break;
07948    case DAHDI_EVENT_RX_CED_DETECTED:
07949       ast_verb(3, "Channel %d detected a CED tone from the network.\n", p->channel);
07950       break;
07951    case DAHDI_EVENT_EC_NLP_DISABLED:
07952       ast_verb(3, "Channel %d echo canceler disabled its NLP.\n", p->channel);
07953       break;
07954    case DAHDI_EVENT_EC_NLP_ENABLED:
07955       ast_verb(3, "Channel %d echo canceler enabled its NLP.\n", p->channel);
07956       break;
07957 #endif
07958    case DAHDI_EVENT_BITSCHANGED:
07959 #ifdef HAVE_OPENR2
07960       if (p->sig != SIG_MFCR2) {
07961          ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07962       } else {
07963          ast_log(LOG_DEBUG, "bits changed in chan %d\n", p->channel);
07964          openr2_chan_handle_cas(p->r2chan);
07965       }
07966 #else
07967       ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07968 #endif
07969       break;
07970    case DAHDI_EVENT_PULSE_START:
07971       /* Stop tone if there's a pulse start and the PBX isn't started */
07972       if (!ast->pbx)
07973          tone_zone_play_tone(p->subs[idx].dfd, -1);
07974       break;
07975    case DAHDI_EVENT_DIALCOMPLETE:
07976       /* DAHDI has completed dialing all digits sent using DAHDI_DIAL. */
07977 #if defined(HAVE_PRI)
07978       if (dahdi_sig_pri_lib_handles(p->sig)) {
07979          if (p->inalarm) {
07980             break;
07981          }
07982          if (ioctl(p->subs[idx].dfd, DAHDI_DIALING, &x) == -1) {
07983             ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n", ast->name,
07984                strerror(errno));
07985             return NULL;
07986          }
07987          if (x) {
07988             /* Still dialing in DAHDI driver */
07989             break;
07990          }
07991          /*
07992           * The ast channel is locked and the private may be locked more
07993           * than once.
07994           */
07995          sig_pri_dial_complete(p->sig_pvt, ast);
07996          break;
07997       }
07998 #endif   /* defined(HAVE_PRI) */
07999 #ifdef HAVE_OPENR2
08000       if ((p->sig & SIG_MFCR2) && p->r2chan && ast->_state != AST_STATE_UP) {
08001          /* we don't need to do anything for this event for R2 signaling
08002             if the call is being setup */
08003          break;
08004       }
08005 #endif
08006       if (p->inalarm) break;
08007       if ((p->radio || (p->oprmode < 0))) break;
08008       if (ioctl(p->subs[idx].dfd,DAHDI_DIALING,&x) == -1) {
08009          ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n",ast->name, strerror(errno));
08010          return NULL;
08011       }
08012       if (!x) { /* if not still dialing in driver */
08013          dahdi_enable_ec(p);
08014          if (p->echobreak) {
08015             dahdi_train_ec(p);
08016             ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
08017             p->dop.op = DAHDI_DIAL_OP_REPLACE;
08018             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08019             p->echobreak = 0;
08020          } else {
08021             p->dialing = 0;
08022             if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
08023                /* if thru with dialing after offhook */
08024                if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
08025                   ast_setstate(ast, AST_STATE_UP);
08026                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08027                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08028                   break;
08029                } else { /* if to state wait for offhook to dial rest */
08030                   /* we now wait for off hook */
08031                   ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
08032                }
08033             }
08034             if (ast->_state == AST_STATE_DIALING) {
08035                if ((p->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
08036                   ast_debug(1, "Done dialing, but waiting for progress detection before doing more...\n");
08037                } else if (p->confirmanswer || (!p->dialednone
08038                   && ((mysig == SIG_EM) || (mysig == SIG_EM_E1)
08039                      || (mysig == SIG_EMWINK) || (mysig == SIG_FEATD)
08040                      || (mysig == SIG_FEATDMF_TA) || (mysig == SIG_FEATDMF)
08041                      || (mysig == SIG_E911) || (mysig == SIG_FGC_CAMA)
08042                      || (mysig == SIG_FGC_CAMAMF) || (mysig == SIG_FEATB)
08043                      || (mysig == SIG_SF) || (mysig == SIG_SFWINK)
08044                      || (mysig == SIG_SF_FEATD) || (mysig == SIG_SF_FEATDMF)
08045                      || (mysig == SIG_SF_FEATB)))) {
08046                   ast_setstate(ast, AST_STATE_RINGING);
08047                } else if (!p->answeronpolarityswitch) {
08048                   ast_setstate(ast, AST_STATE_UP);
08049                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08050                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08051                   /* If aops=0 and hops=1, this is necessary */
08052                   p->polarity = POLARITY_REV;
08053                } else {
08054                   /* Start clean, so we can catch the change to REV polarity when party answers */
08055                   p->polarity = POLARITY_IDLE;
08056                }
08057             }
08058          }
08059       }
08060       break;
08061    case DAHDI_EVENT_ALARM:
08062       switch (p->sig) {
08063 #if defined(HAVE_PRI)
08064       case SIG_PRI_LIB_HANDLE_CASES:
08065          sig_pri_chan_alarm_notify(p->sig_pvt, 0);
08066          break;
08067 #endif   /* defined(HAVE_PRI) */
08068 #if defined(HAVE_SS7)
08069       case SIG_SS7:
08070          sig_ss7_set_alarm(p->sig_pvt, 1);
08071          break;
08072 #endif   /* defined(HAVE_SS7) */
08073       default:
08074          p->inalarm = 1;
08075          break;
08076       }
08077       res = get_alarms(p);
08078       handle_alarms(p, res);
08079 #ifdef HAVE_PRI
08080       if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
08081          /* fall through intentionally */
08082       } else {
08083          break;
08084       }
08085 #endif
08086 #if defined(HAVE_SS7)
08087       if (p->sig == SIG_SS7)
08088          break;
08089 #endif   /* defined(HAVE_SS7) */
08090 #ifdef HAVE_OPENR2
08091       if (p->sig == SIG_MFCR2)
08092          break;
08093 #endif
08094    case DAHDI_EVENT_ONHOOK:
08095       if (p->radio) {
08096          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08097          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08098          break;
08099       }
08100       if (p->oprmode < 0)
08101       {
08102          if (p->oprmode != -1) break;
08103          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
08104          {
08105             /* Make sure it starts ringing */
08106             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08107             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RING);
08108             save_conference(p->oprpeer);
08109             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08110          }
08111          break;
08112       }
08113       switch (p->sig) {
08114       case SIG_FXOLS:
08115       case SIG_FXOGS:
08116       case SIG_FXOKS:
08117          /* Check for some special conditions regarding call waiting */
08118          if (idx == SUB_REAL) {
08119             /* The normal line was hung up */
08120             if (p->subs[SUB_CALLWAIT].owner) {
08121                /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
08122                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
08123                ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
08124                unalloc_sub(p, SUB_CALLWAIT);
08125 #if 0
08126                p->subs[idx].needanswer = 0;
08127                p->subs[idx].needringing = 0;
08128 #endif
08129                p->callwaitingrepeat = 0;
08130                p->cidcwexpire = 0;
08131                p->cid_suppress_expire = 0;
08132                p->owner = NULL;
08133                /* Don't start streaming audio yet if the incoming call isn't up yet */
08134                if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
08135                   p->dialing = 1;
08136                dahdi_ring_phone(p);
08137             } else if (p->subs[SUB_THREEWAY].owner) {
08138                unsigned int mssinceflash;
08139                /* Here we have to retain the lock on both the main channel, the 3-way channel, and
08140                   the private structure -- not especially easy or clean */
08141                while (p->subs[SUB_THREEWAY].owner && ast_channel_trylock(p->subs[SUB_THREEWAY].owner)) {
08142                   /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
08143                   DLA_UNLOCK(&p->lock);
08144                   CHANNEL_DEADLOCK_AVOIDANCE(ast);
08145                   /* We can grab ast and p in that order, without worry.  We should make sure
08146                      nothing seriously bad has happened though like some sort of bizarre double
08147                      masquerade! */
08148                   DLA_LOCK(&p->lock);
08149                   if (p->owner != ast) {
08150                      ast_log(LOG_WARNING, "This isn't good...\n");
08151                      return NULL;
08152                   }
08153                }
08154                if (!p->subs[SUB_THREEWAY].owner) {
08155                   ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
08156                   return NULL;
08157                }
08158                mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
08159                ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
08160                if (mssinceflash < MIN_MS_SINCE_FLASH) {
08161                   /* It hasn't been long enough since the last flashook.  This is probably a bounce on
08162                      hanging up.  Hangup both channels now */
08163                   if (p->subs[SUB_THREEWAY].owner)
08164                      ast_queue_hangup_with_cause(p->subs[SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
08165                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08166                   ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
08167                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08168                } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
08169                   if (p->transfer) {
08170                      /* In any case this isn't a threeway call anymore */
08171                      p->subs[SUB_REAL].inthreeway = 0;
08172                      p->subs[SUB_THREEWAY].inthreeway = 0;
08173                      /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
08174                      if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
08175                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08176                         /* Swap subs and dis-own channel */
08177                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
08178                         p->owner = NULL;
08179                         /* Ring the phone */
08180                         dahdi_ring_phone(p);
08181                      } else {
08182                         if ((res = attempt_transfer(p)) < 0) {
08183                            p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08184                            if (p->subs[SUB_THREEWAY].owner)
08185                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08186                         } else if (res) {
08187                            /* Don't actually hang up at this point */
08188                            if (p->subs[SUB_THREEWAY].owner)
08189                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08190                            break;
08191                         }
08192                      }
08193                   } else {
08194                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08195                      if (p->subs[SUB_THREEWAY].owner)
08196                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08197                   }
08198                } else {
08199                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08200                   /* Swap subs and dis-own channel */
08201                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08202                   p->owner = NULL;
08203                   /* Ring the phone */
08204                   dahdi_ring_phone(p);
08205                }
08206             }
08207          } else {
08208             ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", idx);
08209          }
08210          /* Fall through */
08211       default:
08212          dahdi_disable_ec(p);
08213          return NULL;
08214       }
08215       break;
08216    case DAHDI_EVENT_RINGOFFHOOK:
08217       if (p->inalarm) break;
08218       if (p->oprmode < 0)
08219       {
08220          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
08221          {
08222             /* Make sure it stops ringing */
08223             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08224             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, -1);
08225             restore_conference(p->oprpeer);
08226          }
08227          break;
08228       }
08229       if (p->radio)
08230       {
08231          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08232          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08233          break;
08234       }
08235       /* for E911, its supposed to wait for offhook then dial
08236          the second half of the dial string */
08237       if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
08238          c = strchr(p->dialdest, '/');
08239          if (c)
08240             c++;
08241          else
08242             c = p->dialdest;
08243          if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
08244          else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
08245          if (strlen(p->dop.dialstr) > 4) {
08246             memset(p->echorest, 'w', sizeof(p->echorest) - 1);
08247             strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
08248             p->echorest[sizeof(p->echorest) - 1] = '\0';
08249             p->echobreak = 1;
08250             p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
08251          } else
08252             p->echobreak = 0;
08253          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
08254             int saveerr = errno;
08255 
08256             x = DAHDI_ONHOOK;
08257             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
08258             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
08259             return NULL;
08260             }
08261          p->dialing = 1;
08262          return &p->subs[idx].f;
08263       }
08264       switch (p->sig) {
08265       case SIG_FXOLS:
08266       case SIG_FXOGS:
08267       case SIG_FXOKS:
08268          switch (ast->_state) {
08269          case AST_STATE_RINGING:
08270             dahdi_enable_ec(p);
08271             dahdi_train_ec(p);
08272             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08273             p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08274             /* Make sure it stops ringing */
08275             p->subs[SUB_REAL].needringing = 0;
08276             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
08277             ast_debug(1, "channel %d answered\n", p->channel);
08278 
08279             /* Cancel any running CallerID spill */
08280             ast_free(p->cidspill);
08281             p->cidspill = NULL;
08282             restore_conference(p);
08283 
08284             p->dialing = 0;
08285             p->callwaitcas = 0;
08286             if (p->confirmanswer) {
08287                /* Ignore answer if "confirm answer" is enabled */
08288                p->subs[idx].f.frametype = AST_FRAME_NULL;
08289                p->subs[idx].f.subclass.integer = 0;
08290             } else if (!ast_strlen_zero(p->dop.dialstr)) {
08291                /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
08292                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08293                if (res < 0) {
08294                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08295                   p->dop.dialstr[0] = '\0';
08296                   return NULL;
08297                } else {
08298                   ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
08299                   p->subs[idx].f.frametype = AST_FRAME_NULL;
08300                   p->subs[idx].f.subclass.integer = 0;
08301                   p->dialing = 1;
08302                }
08303                p->dop.dialstr[0] = '\0';
08304                ast_setstate(ast, AST_STATE_DIALING);
08305             } else
08306                ast_setstate(ast, AST_STATE_UP);
08307             return &p->subs[idx].f;
08308          case AST_STATE_DOWN:
08309             ast_setstate(ast, AST_STATE_RING);
08310             ast->rings = 1;
08311             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08312             p->subs[idx].f.subclass.integer = AST_CONTROL_OFFHOOK;
08313             ast_debug(1, "channel %d picked up\n", p->channel);
08314             return &p->subs[idx].f;
08315          case AST_STATE_UP:
08316             /* Make sure it stops ringing */
08317             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
08318             /* Okay -- probably call waiting*/
08319             if (ast_bridged_channel(p->owner))
08320                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08321             p->subs[idx].needunhold = 1;
08322             break;
08323          case AST_STATE_RESERVED:
08324             /* Start up dialtone */
08325             if (has_voicemail(p))
08326                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
08327             else
08328                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
08329             break;
08330          default:
08331             ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
08332          }
08333          break;
08334       case SIG_FXSLS:
08335       case SIG_FXSGS:
08336       case SIG_FXSKS:
08337          if (ast->_state == AST_STATE_RING) {
08338             p->ringt = p->ringt_base;
08339          }
08340 
08341          /* If we get a ring then we cannot be in
08342           * reversed polarity. So we reset to idle */
08343          ast_debug(1, "Setting IDLE polarity due "
08344             "to ring. Old polarity was %d\n",
08345             p->polarity);
08346          p->polarity = POLARITY_IDLE;
08347 
08348          /* Fall through */
08349       case SIG_EM:
08350       case SIG_EM_E1:
08351       case SIG_EMWINK:
08352       case SIG_FEATD:
08353       case SIG_FEATDMF:
08354       case SIG_FEATDMF_TA:
08355       case SIG_E911:
08356       case SIG_FGC_CAMA:
08357       case SIG_FGC_CAMAMF:
08358       case SIG_FEATB:
08359       case SIG_SF:
08360       case SIG_SFWINK:
08361       case SIG_SF_FEATD:
08362       case SIG_SF_FEATDMF:
08363       case SIG_SF_FEATB:
08364          if (ast->_state == AST_STATE_PRERING)
08365             ast_setstate(ast, AST_STATE_RING);
08366          if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
08367             ast_debug(1, "Ring detected\n");
08368             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08369             p->subs[idx].f.subclass.integer = AST_CONTROL_RING;
08370          } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
08371             ast_debug(1, "Line answered\n");
08372             if (p->confirmanswer) {
08373                p->subs[idx].f.frametype = AST_FRAME_NULL;
08374                p->subs[idx].f.subclass.integer = 0;
08375             } else {
08376                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08377                p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08378                ast_setstate(ast, AST_STATE_UP);
08379             }
08380          } else if (ast->_state != AST_STATE_RING)
08381             ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
08382          break;
08383       default:
08384          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08385       }
08386       break;
08387    case DAHDI_EVENT_RINGBEGIN:
08388       switch (p->sig) {
08389       case SIG_FXSLS:
08390       case SIG_FXSGS:
08391       case SIG_FXSKS:
08392          if (ast->_state == AST_STATE_RING) {
08393             p->ringt = p->ringt_base;
08394          }
08395          break;
08396       }
08397       break;
08398    case DAHDI_EVENT_RINGERON:
08399       break;
08400    case DAHDI_EVENT_NOALARM:
08401       switch (p->sig) {
08402 #if defined(HAVE_PRI)
08403       case SIG_PRI_LIB_HANDLE_CASES:
08404          sig_pri_chan_alarm_notify(p->sig_pvt, 1);
08405          break;
08406 #endif   /* defined(HAVE_PRI) */
08407 #if defined(HAVE_SS7)
08408       case SIG_SS7:
08409          sig_ss7_set_alarm(p->sig_pvt, 0);
08410          break;
08411 #endif   /* defined(HAVE_SS7) */
08412       default:
08413          p->inalarm = 0;
08414          break;
08415       }
08416       handle_clear_alarms(p);
08417       break;
08418    case DAHDI_EVENT_WINKFLASH:
08419       if (p->inalarm) break;
08420       if (p->radio) break;
08421       if (p->oprmode < 0) break;
08422       if (p->oprmode > 1)
08423       {
08424          struct dahdi_params par;
08425 
08426          memset(&par, 0, sizeof(par));
08427          if (ioctl(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par) != -1)
08428          {
08429             if (!par.rxisoffhook)
08430             {
08431                /* Make sure it stops ringing */
08432                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08433                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RING);
08434                save_conference(p);
08435                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08436             }
08437          }
08438          break;
08439       }
08440       /* Remember last time we got a flash-hook */
08441       p->flashtime = ast_tvnow();
08442       switch (mysig) {
08443       case SIG_FXOLS:
08444       case SIG_FXOGS:
08445       case SIG_FXOKS:
08446          ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
08447             idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
08448 
08449          /* Cancel any running CallerID spill */
08450          ast_free(p->cidspill);
08451          p->cidspill = NULL;
08452          restore_conference(p);
08453          p->callwaitcas = 0;
08454 
08455          if (idx != SUB_REAL) {
08456             ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", idx, p->channel);
08457             goto winkflashdone;
08458          }
08459 
08460          if (p->subs[SUB_CALLWAIT].owner) {
08461             /* Swap to call-wait */
08462             swap_subs(p, SUB_REAL, SUB_CALLWAIT);
08463             tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
08464             p->owner = p->subs[SUB_REAL].owner;
08465             ast_debug(1, "Making %s the new owner\n", p->owner->name);
08466             if (p->owner->_state == AST_STATE_RINGING) {
08467                ast_setstate(p->owner, AST_STATE_UP);
08468                p->subs[SUB_REAL].needanswer = 1;
08469             }
08470             p->callwaitingrepeat = 0;
08471             p->cidcwexpire = 0;
08472             p->cid_suppress_expire = 0;
08473             /* Start music on hold if appropriate */
08474             if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
08475                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
08476                   S_OR(p->mohsuggest, NULL),
08477                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08478             }
08479             p->subs[SUB_CALLWAIT].needhold = 1;
08480             if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
08481                ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
08482                   S_OR(p->mohsuggest, NULL),
08483                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08484             }
08485             p->subs[SUB_REAL].needunhold = 1;
08486          } else if (!p->subs[SUB_THREEWAY].owner) {
08487             if (!p->threewaycalling) {
08488                /* Just send a flash if no 3-way calling */
08489                p->subs[SUB_REAL].needflash = 1;
08490                goto winkflashdone;
08491             } else if (!check_for_conference(p)) {
08492                char cid_num[256];
08493                char cid_name[256];
08494 
08495                cid_num[0] = 0;
08496                cid_name[0] = 0;
08497                if (p->dahditrcallerid && p->owner) {
08498                   if (p->owner->caller.id.number.valid
08499                      && p->owner->caller.id.number.str) {
08500                      ast_copy_string(cid_num, p->owner->caller.id.number.str,
08501                         sizeof(cid_num));
08502                   }
08503                   if (p->owner->caller.id.name.valid
08504                      && p->owner->caller.id.name.str) {
08505                      ast_copy_string(cid_name, p->owner->caller.id.name.str,
08506                         sizeof(cid_name));
08507                   }
08508                }
08509                /* XXX This section needs much more error checking!!! XXX */
08510                /* Start a 3-way call if feasible */
08511                if (!((ast->pbx) ||
08512                   (ast->_state == AST_STATE_UP) ||
08513                   (ast->_state == AST_STATE_RING))) {
08514                   ast_debug(1, "Flash when call not up or ringing\n");
08515                   goto winkflashdone;
08516                }
08517                if (alloc_sub(p, SUB_THREEWAY)) {
08518                   ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
08519                   goto winkflashdone;
08520                }
08521 
08522                /*
08523                 * Make new channel
08524                 *
08525                 * We cannot hold the p or ast locks while creating a new
08526                 * channel.
08527                 */
08528                ast_mutex_unlock(&p->lock);
08529                ast_channel_unlock(ast);
08530                chan = dahdi_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, NULL);
08531                ast_channel_lock(ast);
08532                ast_mutex_lock(&p->lock);
08533                if (p->dahditrcallerid) {
08534                   if (!p->origcid_num)
08535                      p->origcid_num = ast_strdup(p->cid_num);
08536                   if (!p->origcid_name)
08537                      p->origcid_name = ast_strdup(p->cid_name);
08538                   ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
08539                   ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
08540                }
08541                /* Swap things around between the three-way and real call */
08542                swap_subs(p, SUB_THREEWAY, SUB_REAL);
08543                /* Disable echo canceller for better dialing */
08544                dahdi_disable_ec(p);
08545                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALRECALL);
08546                if (res)
08547                   ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
08548                p->owner = chan;
08549                if (!chan) {
08550                   ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
08551                } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
08552                   ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
08553                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
08554                   dahdi_enable_ec(p);
08555                   ast_hangup(chan);
08556                } else {
08557                   ast_verb(3, "Started three way call on channel %d\n", p->channel);
08558 
08559                   /* Start music on hold if appropriate */
08560                   if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
08561                      ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
08562                         S_OR(p->mohsuggest, NULL),
08563                         !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08564                   }
08565                   p->subs[SUB_THREEWAY].needhold = 1;
08566                }
08567             }
08568          } else {
08569             /* Already have a 3 way call */
08570             if (p->subs[SUB_THREEWAY].inthreeway) {
08571                /* Call is already up, drop the last person */
08572                ast_debug(1, "Got flash with three way call up, dropping last call on %d\n", p->channel);
08573                /* If the primary call isn't answered yet, use it */
08574                if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
08575                   /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
08576                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08577                   p->owner = p->subs[SUB_REAL].owner;
08578                }
08579                /* Drop the last call and stop the conference */
08580                ast_verb(3, "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
08581                p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08582                p->subs[SUB_REAL].inthreeway = 0;
08583                p->subs[SUB_THREEWAY].inthreeway = 0;
08584             } else {
08585                /* Lets see what we're up to */
08586                if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
08587                   (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
08588                   int otherindex = SUB_THREEWAY;
08589 
08590                   ast_verb(3, "Building conference call with %s and %s\n",
08591                      p->subs[SUB_THREEWAY].owner->name,
08592                      p->subs[SUB_REAL].owner->name);
08593                   /* Put them in the threeway, and flip */
08594                   p->subs[SUB_THREEWAY].inthreeway = 1;
08595                   p->subs[SUB_REAL].inthreeway = 1;
08596                   if (ast->_state == AST_STATE_UP) {
08597                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
08598                      otherindex = SUB_REAL;
08599                   }
08600                   if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
08601                      ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
08602                   p->subs[otherindex].needunhold = 1;
08603                   p->owner = p->subs[SUB_REAL].owner;
08604                } else {
08605                   ast_verb(3, "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
08606                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08607                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08608                   p->owner = p->subs[SUB_REAL].owner;
08609                   if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
08610                      ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
08611                   p->subs[SUB_REAL].needunhold = 1;
08612                   dahdi_enable_ec(p);
08613                }
08614             }
08615          }
08616 winkflashdone:
08617          update_conf(p);
08618          break;
08619       case SIG_EM:
08620       case SIG_EM_E1:
08621       case SIG_FEATD:
08622       case SIG_SF:
08623       case SIG_SFWINK:
08624       case SIG_SF_FEATD:
08625       case SIG_FXSLS:
08626       case SIG_FXSGS:
08627          if (p->dialing)
08628             ast_debug(1, "Ignoring wink on channel %d\n", p->channel);
08629          else
08630             ast_debug(1, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
08631          break;
08632       case SIG_FEATDMF_TA:
08633          switch (p->whichwink) {
08634          case 0:
08635             ast_debug(1, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->caller.ani2,
08636                S_COR(p->owner->caller.ani.number.valid,
08637                   p->owner->caller.ani.number.str, ""));
08638             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#",
08639                p->owner->caller.ani2,
08640                S_COR(p->owner->caller.ani.number.valid,
08641                   p->owner->caller.ani.number.str, ""));
08642             break;
08643          case 1:
08644             ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
08645             break;
08646          case 2:
08647             ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
08648             return NULL;
08649          }
08650          p->whichwink++;
08651          /* Fall through */
08652       case SIG_FEATDMF:
08653       case SIG_E911:
08654       case SIG_FGC_CAMAMF:
08655       case SIG_FGC_CAMA:
08656       case SIG_FEATB:
08657       case SIG_SF_FEATDMF:
08658       case SIG_SF_FEATB:
08659       case SIG_EMWINK:
08660          /* FGD MF and EMWINK *Must* wait for wink */
08661          if (!ast_strlen_zero(p->dop.dialstr)) {
08662             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08663             if (res < 0) {
08664                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08665                p->dop.dialstr[0] = '\0';
08666                return NULL;
08667             } else
08668                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08669          }
08670          p->dop.dialstr[0] = '\0';
08671          break;
08672       default:
08673          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08674       }
08675       break;
08676    case DAHDI_EVENT_HOOKCOMPLETE:
08677       if (p->inalarm) break;
08678       if ((p->radio || (p->oprmode < 0))) break;
08679       if (p->waitingfordt.tv_sec) break;
08680       switch (mysig) {
08681       case SIG_FXSLS:  /* only interesting for FXS */
08682       case SIG_FXSGS:
08683       case SIG_FXSKS:
08684       case SIG_EM:
08685       case SIG_EM_E1:
08686       case SIG_EMWINK:
08687       case SIG_FEATD:
08688       case SIG_SF:
08689       case SIG_SFWINK:
08690       case SIG_SF_FEATD:
08691          if (!ast_strlen_zero(p->dop.dialstr)) {
08692             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08693             if (res < 0) {
08694                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08695                p->dop.dialstr[0] = '\0';
08696                return NULL;
08697             } else
08698                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08699          }
08700          p->dop.dialstr[0] = '\0';
08701          p->dop.op = DAHDI_DIAL_OP_REPLACE;
08702          break;
08703       case SIG_FEATDMF:
08704       case SIG_FEATDMF_TA:
08705       case SIG_E911:
08706       case SIG_FGC_CAMA:
08707       case SIG_FGC_CAMAMF:
08708       case SIG_FEATB:
08709       case SIG_SF_FEATDMF:
08710       case SIG_SF_FEATB:
08711          ast_debug(1, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
08712          break;
08713       default:
08714          break;
08715       }
08716       break;
08717    case DAHDI_EVENT_POLARITY:
08718       /*
08719        * If we get a Polarity Switch event, check to see
08720        * if we should change the polarity state and
08721        * mark the channel as UP or if this is an indication
08722        * of remote end disconnect.
08723        */
08724       if (p->polarity == POLARITY_IDLE) {
08725          p->polarity = POLARITY_REV;
08726          if (p->answeronpolarityswitch &&
08727             ((ast->_state == AST_STATE_DIALING) ||
08728             (ast->_state == AST_STATE_RINGING))) {
08729             ast_debug(1, "Answering on polarity switch!\n");
08730             ast_setstate(p->owner, AST_STATE_UP);
08731             if (p->hanguponpolarityswitch) {
08732                p->polaritydelaytv = ast_tvnow();
08733             }
08734          } else
08735             ast_debug(1, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
08736       }
08737       /* Removed else statement from here as it was preventing hangups from ever happening*/
08738       /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
08739       if (p->hanguponpolarityswitch &&
08740          (p->polarityonanswerdelay > 0) &&
08741          (p->polarity == POLARITY_REV) &&
08742          ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
08743          /* Added log_debug information below to provide a better indication of what is going on */
08744          ast_debug(1, "Polarity Reversal event occured - DEBUG 1: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %" PRIi64 "\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
08745 
08746          if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
08747             ast_debug(1, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
08748             ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
08749             p->polarity = POLARITY_IDLE;
08750          } else
08751             ast_debug(1, "Polarity Reversal detected but NOT hanging up (too close to answer event) on channel %d, state %d\n", p->channel, ast->_state);
08752 
08753       } else {
08754          p->polarity = POLARITY_IDLE;
08755          ast_debug(1, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
08756       }
08757       /* Added more log_debug information below to provide a better indication of what is going on */
08758       ast_debug(1, "Polarity Reversal event occured - DEBUG 2: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %" PRIi64 "\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
08759       break;
08760    default:
08761       ast_debug(1, "Dunno what to do with event %d on channel %d\n", res, p->channel);
08762    }
08763    return &p->subs[idx].f;
08764 }
08765 
08766 static struct ast_frame *__dahdi_exception(struct ast_channel *ast)
08767 {
08768    int res;
08769    int idx;
08770    struct ast_frame *f;
08771    int usedindex = -1;
08772    struct dahdi_pvt *p = ast->tech_pvt;
08773 
08774    if ((idx = dahdi_get_index(ast, p, 0)) < 0) {
08775       idx = SUB_REAL;
08776    }
08777 
08778    p->subs[idx].f.frametype = AST_FRAME_NULL;
08779    p->subs[idx].f.datalen = 0;
08780    p->subs[idx].f.samples = 0;
08781    p->subs[idx].f.mallocd = 0;
08782    p->subs[idx].f.offset = 0;
08783    p->subs[idx].f.subclass.integer = 0;
08784    p->subs[idx].f.delivery = ast_tv(0,0);
08785    p->subs[idx].f.src = "dahdi_exception";
08786    p->subs[idx].f.data.ptr = NULL;
08787 
08788 
08789    if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
08790       /* If nobody owns us, absorb the event appropriately, otherwise
08791          we loop indefinitely.  This occurs when, during call waiting, the
08792          other end hangs up our channel so that it no longer exists, but we
08793          have neither FLASH'd nor ONHOOK'd to signify our desire to
08794          change to the other channel. */
08795       if (p->fake_event) {
08796          res = p->fake_event;
08797          p->fake_event = 0;
08798       } else
08799          res = dahdi_get_event(p->subs[SUB_REAL].dfd);
08800       /* Switch to real if there is one and this isn't something really silly... */
08801       if ((res != DAHDI_EVENT_RINGEROFF) && (res != DAHDI_EVENT_RINGERON) &&
08802          (res != DAHDI_EVENT_HOOKCOMPLETE)) {
08803          ast_debug(1, "Restoring owner of channel %d on event %d\n", p->channel, res);
08804          p->owner = p->subs[SUB_REAL].owner;
08805          if (p->owner && ast_bridged_channel(p->owner))
08806             ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08807          p->subs[SUB_REAL].needunhold = 1;
08808       }
08809       switch (res) {
08810       case DAHDI_EVENT_ONHOOK:
08811          dahdi_disable_ec(p);
08812          if (p->owner) {
08813             ast_verb(3, "Channel %s still has call, ringing phone\n", p->owner->name);
08814             dahdi_ring_phone(p);
08815             p->callwaitingrepeat = 0;
08816             p->cidcwexpire = 0;
08817             p->cid_suppress_expire = 0;
08818          } else
08819             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08820          update_conf(p);
08821          break;
08822       case DAHDI_EVENT_RINGOFFHOOK:
08823          dahdi_enable_ec(p);
08824          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08825          if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
08826             p->subs[SUB_REAL].needanswer = 1;
08827             p->dialing = 0;
08828          }
08829          break;
08830       case DAHDI_EVENT_HOOKCOMPLETE:
08831       case DAHDI_EVENT_RINGERON:
08832       case DAHDI_EVENT_RINGEROFF:
08833          /* Do nothing */
08834          break;
08835       case DAHDI_EVENT_WINKFLASH:
08836          p->flashtime = ast_tvnow();
08837          if (p->owner) {
08838             ast_verb(3, "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
08839             if (p->owner->_state != AST_STATE_UP) {
08840                /* Answer if necessary */
08841                usedindex = dahdi_get_index(p->owner, p, 0);
08842                if (usedindex > -1) {
08843                   p->subs[usedindex].needanswer = 1;
08844                }
08845                ast_setstate(p->owner, AST_STATE_UP);
08846             }
08847             p->callwaitingrepeat = 0;
08848             p->cidcwexpire = 0;
08849             p->cid_suppress_expire = 0;
08850             if (ast_bridged_channel(p->owner))
08851                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08852             p->subs[SUB_REAL].needunhold = 1;
08853          } else
08854             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08855          update_conf(p);
08856          break;
08857       default:
08858          ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
08859       }
08860       f = &p->subs[idx].f;
08861       return f;
08862    }
08863    if (!(p->radio || (p->oprmode < 0)))
08864       ast_debug(1, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
08865    /* If it's not us, return NULL immediately */
08866    if (ast != p->owner) {
08867       if (p->owner) {
08868          ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
08869       }
08870       f = &p->subs[idx].f;
08871       return f;
08872    }
08873 
08874    f = dahdi_handle_event(ast);
08875    if (!f) {
08876       const char *name = ast_strdupa(ast->name);
08877 
08878       /* Tell the CDR this DAHDI device hung up */
08879       ast_mutex_unlock(&p->lock);
08880       ast_channel_unlock(ast);
08881       ast_set_hangupsource(ast, name, 0);
08882       ast_channel_lock(ast);
08883       ast_mutex_lock(&p->lock);
08884    }
08885    return f;
08886 }
08887 
08888 static struct ast_frame *dahdi_exception(struct ast_channel *ast)
08889 {
08890    struct dahdi_pvt *p = ast->tech_pvt;
08891    struct ast_frame *f;
08892    ast_mutex_lock(&p->lock);
08893    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08894       struct analog_pvt *analog_p = p->sig_pvt;
08895       f = analog_exception(analog_p, ast);
08896    } else {
08897       f = __dahdi_exception(ast);
08898    }
08899    ast_mutex_unlock(&p->lock);
08900    return f;
08901 }
08902 
08903 static struct ast_frame *dahdi_read(struct ast_channel *ast)
08904 {
08905    struct dahdi_pvt *p;
08906    int res;
08907    int idx;
08908    void *readbuf;
08909    struct ast_frame *f;
08910 
08911    /*
08912     * For analog channels, we must do deadlock avoidance because
08913     * analog ports can have more than one Asterisk channel using
08914     * the same private structure.
08915     */
08916    p = ast->tech_pvt;
08917    while (ast_mutex_trylock(&p->lock)) {
08918       CHANNEL_DEADLOCK_AVOIDANCE(ast);
08919 
08920       /*
08921        * For PRI channels, we must refresh the private pointer because
08922        * the call could move to another B channel while the Asterisk
08923        * channel is unlocked.
08924        */
08925       p = ast->tech_pvt;
08926    }
08927 
08928    idx = dahdi_get_index(ast, p, 0);
08929 
08930    /* Hang up if we don't really exist */
08931    if (idx < 0)   {
08932       ast_log(LOG_WARNING, "We don't exist?\n");
08933       ast_mutex_unlock(&p->lock);
08934       return NULL;
08935    }
08936 
08937    if ((p->radio || (p->oprmode < 0)) && p->inalarm) {
08938       ast_mutex_unlock(&p->lock);
08939       return NULL;
08940    }
08941 
08942    p->subs[idx].f.frametype = AST_FRAME_NULL;
08943    p->subs[idx].f.datalen = 0;
08944    p->subs[idx].f.samples = 0;
08945    p->subs[idx].f.mallocd = 0;
08946    p->subs[idx].f.offset = 0;
08947    p->subs[idx].f.subclass.integer = 0;
08948    p->subs[idx].f.delivery = ast_tv(0,0);
08949    p->subs[idx].f.src = "dahdi_read";
08950    p->subs[idx].f.data.ptr = NULL;
08951 
08952    /* make sure it sends initial key state as first frame */
08953    if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
08954    {
08955       struct dahdi_params ps;
08956 
08957       memset(&ps, 0, sizeof(ps));
08958       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
08959          ast_mutex_unlock(&p->lock);
08960          return NULL;
08961       }
08962       p->firstradio = 1;
08963       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08964       if (ps.rxisoffhook)
08965       {
08966          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08967       }
08968       else
08969       {
08970          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08971       }
08972       ast_mutex_unlock(&p->lock);
08973       return &p->subs[idx].f;
08974    }
08975    if (p->ringt > 0) {
08976       if (!(--p->ringt)) {
08977          ast_mutex_unlock(&p->lock);
08978          return NULL;
08979       }
08980    }
08981 
08982 #ifdef HAVE_OPENR2
08983    if (p->mfcr2) {
08984       openr2_chan_process_event(p->r2chan);
08985       if (OR2_DIR_FORWARD == openr2_chan_get_direction(p->r2chan)) {
08986          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_PROGRESS }, };
08987          /* if the call is already accepted and we already delivered AST_CONTROL_RINGING
08988           * now enqueue a progress frame to bridge the media up */
08989          if (p->mfcr2_call_accepted &&
08990              !p->mfcr2_progress && 
08991              ast->_state == AST_STATE_RINGING) {
08992             ast_log(LOG_DEBUG, "Enqueuing progress frame after R2 accept in chan %d\n", p->channel);
08993             ast_queue_frame(p->owner, &f);
08994             p->mfcr2_progress = 1;
08995          }
08996       }
08997    }
08998 #endif
08999 
09000    if (p->subs[idx].needringing) {
09001       /* Send ringing frame if requested */
09002       p->subs[idx].needringing = 0;
09003       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09004       p->subs[idx].f.subclass.integer = AST_CONTROL_RINGING;
09005       ast_setstate(ast, AST_STATE_RINGING);
09006       ast_mutex_unlock(&p->lock);
09007       return &p->subs[idx].f;
09008    }
09009 
09010    if (p->subs[idx].needbusy) {
09011       /* Send busy frame if requested */
09012       p->subs[idx].needbusy = 0;
09013       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09014       p->subs[idx].f.subclass.integer = AST_CONTROL_BUSY;
09015       ast_mutex_unlock(&p->lock);
09016       return &p->subs[idx].f;
09017    }
09018 
09019    if (p->subs[idx].needcongestion) {
09020       /* Send congestion frame if requested */
09021       p->subs[idx].needcongestion = 0;
09022       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09023       p->subs[idx].f.subclass.integer = AST_CONTROL_CONGESTION;
09024       ast_mutex_unlock(&p->lock);
09025       return &p->subs[idx].f;
09026    }
09027 
09028    if (p->subs[idx].needanswer) {
09029       /* Send answer frame if requested */
09030       p->subs[idx].needanswer = 0;
09031       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09032       p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
09033       ast_mutex_unlock(&p->lock);
09034       return &p->subs[idx].f;
09035    }
09036 #ifdef HAVE_OPENR2
09037    if (p->mfcr2 && openr2_chan_get_read_enabled(p->r2chan)) {
09038       /* openr2 took care of reading and handling any event
09039         (needanswer, needbusy etc), if we continue we will read()
09040         twice, lets just return a null frame. This should only
09041         happen when openr2 is dialing out */
09042       ast_mutex_unlock(&p->lock);
09043       return &ast_null_frame;
09044    }
09045 #endif
09046 
09047    if (p->subs[idx].needflash) {
09048       /* Send answer frame if requested */
09049       p->subs[idx].needflash = 0;
09050       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09051       p->subs[idx].f.subclass.integer = AST_CONTROL_FLASH;
09052       ast_mutex_unlock(&p->lock);
09053       return &p->subs[idx].f;
09054    }
09055 
09056    if (p->subs[idx].needhold) {
09057       /* Send answer frame if requested */
09058       p->subs[idx].needhold = 0;
09059       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09060       p->subs[idx].f.subclass.integer = AST_CONTROL_HOLD;
09061       ast_mutex_unlock(&p->lock);
09062       ast_debug(1, "Sending hold on '%s'\n", ast->name);
09063       return &p->subs[idx].f;
09064    }
09065 
09066    if (p->subs[idx].needunhold) {
09067       /* Send answer frame if requested */
09068       p->subs[idx].needunhold = 0;
09069       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09070       p->subs[idx].f.subclass.integer = AST_CONTROL_UNHOLD;
09071       ast_mutex_unlock(&p->lock);
09072       ast_debug(1, "Sending unhold on '%s'\n", ast->name);
09073       return &p->subs[idx].f;
09074    }
09075 
09076    /*
09077     * If we have a fake_event, fake an exception to handle it only
09078     * if this channel owns the private.
09079     */
09080    if (p->fake_event && p->owner == ast) {
09081       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09082          struct analog_pvt *analog_p = p->sig_pvt;
09083 
09084          f = analog_exception(analog_p, ast);
09085       } else {
09086          f = __dahdi_exception(ast);
09087       }
09088       ast_mutex_unlock(&p->lock);
09089       return f;
09090    }
09091 
09092    if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
09093       if (!p->subs[idx].linear) {
09094          p->subs[idx].linear = 1;
09095          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09096          if (res)
09097             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, idx);
09098       }
09099    } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
09100       (ast->rawreadformat == AST_FORMAT_ALAW)) {
09101       if (p->subs[idx].linear) {
09102          p->subs[idx].linear = 0;
09103          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09104          if (res)
09105             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, idx);
09106       }
09107    } else {
09108       ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
09109       ast_mutex_unlock(&p->lock);
09110       return NULL;
09111    }
09112    readbuf = ((unsigned char *)p->subs[idx].buffer) + AST_FRIENDLY_OFFSET;
09113    CHECK_BLOCKING(ast);
09114    res = read(p->subs[idx].dfd, readbuf, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
09115    ast_clear_flag(ast, AST_FLAG_BLOCKING);
09116    /* Check for hangup */
09117    if (res < 0) {
09118       f = NULL;
09119       if (res == -1) {
09120          if (errno == EAGAIN) {
09121             /* Return "NULL" frame if there is nobody there */
09122             ast_mutex_unlock(&p->lock);
09123             return &p->subs[idx].f;
09124          } else if (errno == ELAST) {
09125             if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09126                struct analog_pvt *analog_p = p->sig_pvt;
09127                f = analog_exception(analog_p, ast);
09128             } else {
09129                f = __dahdi_exception(ast);
09130             }
09131          } else
09132             ast_log(LOG_WARNING, "dahdi_rec: %s\n", strerror(errno));
09133       }
09134       ast_mutex_unlock(&p->lock);
09135       return f;
09136    }
09137    if (res != (p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE)) {
09138       ast_debug(1, "Short read (%d/%d), must be an event...\n", res, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
09139       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09140          struct analog_pvt *analog_p = p->sig_pvt;
09141          f = analog_exception(analog_p, ast);
09142       } else {
09143          f = __dahdi_exception(ast);
09144       }
09145       ast_mutex_unlock(&p->lock);
09146       return f;
09147    }
09148    if (p->tdd) { /* if in TDD mode, see if we receive that */
09149       int c;
09150 
09151       c = tdd_feed(p->tdd,readbuf,READ_SIZE);
09152       if (c < 0) {
09153          ast_debug(1,"tdd_feed failed\n");
09154          ast_mutex_unlock(&p->lock);
09155          return NULL;
09156       }
09157       if (c) { /* if a char to return */
09158          p->subs[idx].f.subclass.integer = 0;
09159          p->subs[idx].f.frametype = AST_FRAME_TEXT;
09160          p->subs[idx].f.mallocd = 0;
09161          p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
09162          p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET;
09163          p->subs[idx].f.datalen = 1;
09164          *((char *) p->subs[idx].f.data.ptr) = c;
09165          ast_mutex_unlock(&p->lock);
09166          return &p->subs[idx].f;
09167       }
09168    }
09169    if (idx == SUB_REAL) {
09170       /* Ensure the CW timers decrement only on a single subchannel */
09171       if (p->cidcwexpire) {
09172          if (!--p->cidcwexpire) {
09173             /* Expired CID/CW */
09174             ast_verb(3, "CPE does not support Call Waiting Caller*ID.\n");
09175             restore_conference(p);
09176          }
09177       }
09178       if (p->cid_suppress_expire) {
09179          --p->cid_suppress_expire;
09180       }
09181       if (p->callwaitingrepeat) {
09182          if (!--p->callwaitingrepeat) {
09183             /* Expired, Repeat callwaiting tone */
09184             ++p->callwaitrings;
09185             dahdi_callwait(ast);
09186          }
09187       }
09188    }
09189    if (p->subs[idx].linear) {
09190       p->subs[idx].f.datalen = READ_SIZE * 2;
09191    } else
09192       p->subs[idx].f.datalen = READ_SIZE;
09193 
09194    /* Handle CallerID Transmission */
09195    if ((p->owner == ast) && p->cidspill) {
09196       send_callerid(p);
09197    }
09198 
09199    p->subs[idx].f.frametype = AST_FRAME_VOICE;
09200    p->subs[idx].f.subclass.codec = ast->rawreadformat;
09201    p->subs[idx].f.samples = READ_SIZE;
09202    p->subs[idx].f.mallocd = 0;
09203    p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
09204    p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[idx].buffer[0]);
09205 #if 0
09206    ast_debug(1, "Read %d of voice on %s\n", p->subs[idx].f.datalen, ast->name);
09207 #endif
09208    if (p->dialing ||  p->radio || /* Transmitting something */
09209       (idx && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
09210       ((idx == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
09211       ) {
09212       /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
09213          don't send anything */
09214       p->subs[idx].f.frametype = AST_FRAME_NULL;
09215       p->subs[idx].f.subclass.integer = 0;
09216       p->subs[idx].f.samples = 0;
09217       p->subs[idx].f.mallocd = 0;
09218       p->subs[idx].f.offset = 0;
09219       p->subs[idx].f.data.ptr = NULL;
09220       p->subs[idx].f.datalen= 0;
09221    }
09222    if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress || p->waitingfordt.tv_sec) && !idx) {
09223       /* Perform busy detection etc on the dahdi line */
09224       int mute;
09225 
09226       f = ast_dsp_process(ast, p->dsp, &p->subs[idx].f);
09227 
09228       /* Check if DSP code thinks we should be muting this frame and mute the conference if so */
09229       mute = ast_dsp_was_muted(p->dsp);
09230       if (p->muting != mute) {
09231          p->muting = mute;
09232          dahdi_confmute(p, mute);
09233       }
09234 
09235       if (f) {
09236          if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_BUSY)) {
09237             if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
09238                /* Treat this as a "hangup" instead of a "busy" on the assumption that
09239                   a busy */
09240                ast_frfree(f);
09241                f = NULL;
09242             }
09243          } else if (f->frametype == AST_FRAME_DTMF_BEGIN
09244             || f->frametype == AST_FRAME_DTMF_END) {
09245 #ifdef HAVE_PRI
09246             if (dahdi_sig_pri_lib_handles(p->sig)
09247                && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
09248                && p->pri
09249                && ((!p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING))
09250                   || (p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)))) {
09251                /* Don't accept in-band DTMF when in overlap dial mode */
09252                ast_debug(1, "Absorbing inband %s DTMF digit: 0x%02X '%c' on %s\n",
09253                   f->frametype == AST_FRAME_DTMF_BEGIN ? "begin" : "end",
09254                   f->subclass.integer, f->subclass.integer, ast->name);
09255 
09256                f->frametype = AST_FRAME_NULL;
09257                f->subclass.integer = 0;
09258             }
09259 #endif
09260             /* DSP clears us of being pulse */
09261             p->pulsedial = 0;
09262          } else if (p->waitingfordt.tv_sec) {
09263             if (ast_tvdiff_ms(ast_tvnow(), p->waitingfordt) >= p->waitfordialtone ) {
09264                p->waitingfordt.tv_sec = 0;
09265                ast_log(LOG_WARNING, "Never saw dialtone on channel %d\n", p->channel);
09266                ast_frfree(f);
09267                f = NULL;
09268             } else if (f->frametype == AST_FRAME_VOICE) {
09269                f->frametype = AST_FRAME_NULL;
09270                f->subclass.integer = 0;
09271                if ((ast_dsp_get_tstate(p->dsp) == DSP_TONE_STATE_DIALTONE || ast_dsp_get_tstate(p->dsp) == DSP_TONE_STATE_RINGING) && ast_dsp_get_tcount(p->dsp) > 9) {
09272                   p->waitingfordt.tv_sec = 0;
09273                   p->dsp_features &= ~DSP_FEATURE_WAITDIALTONE;
09274                   ast_dsp_set_features(p->dsp, p->dsp_features);
09275                   ast_log(LOG_DEBUG, "Got 10 samples of dialtone!\n");
09276                   if (!ast_strlen_zero(p->dop.dialstr)) { /* Dial deferred digits */
09277                      res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
09278                      if (res < 0) {
09279                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
09280                         p->dop.dialstr[0] = '\0';
09281                         ast_mutex_unlock(&p->lock);
09282                         ast_frfree(f);
09283                         return NULL;
09284                      } else {
09285                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
09286                         p->dialing = 1;
09287                         p->dop.dialstr[0] = '\0';
09288                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
09289                         ast_setstate(ast, AST_STATE_DIALING);
09290                      }
09291                   }
09292                }
09293             }
09294          }
09295       }
09296    } else
09297       f = &p->subs[idx].f;
09298 
09299    if (f) {
09300       switch (f->frametype) {
09301       case AST_FRAME_DTMF_BEGIN:
09302       case AST_FRAME_DTMF_END:
09303          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09304             analog_handle_dtmf(p->sig_pvt, ast, idx, &f);
09305          } else {
09306             dahdi_handle_dtmf(ast, idx, &f);
09307          }
09308          break;
09309       case AST_FRAME_VOICE:
09310          if (p->cidspill || p->cid_suppress_expire) {
09311             /* We are/were sending a caller id spill.  Suppress any echo. */
09312             p->subs[idx].f.frametype = AST_FRAME_NULL;
09313             p->subs[idx].f.subclass.integer = 0;
09314             p->subs[idx].f.samples = 0;
09315             p->subs[idx].f.mallocd = 0;
09316             p->subs[idx].f.offset = 0;
09317             p->subs[idx].f.data.ptr = NULL;
09318             p->subs[idx].f.datalen= 0;
09319          }
09320          break;
09321       default:
09322          break;
09323       }
09324    }
09325 
09326    ast_mutex_unlock(&p->lock);
09327    return f;
09328 }
09329 
09330 static int my_dahdi_write(struct dahdi_pvt *p, unsigned char *buf, int len, int idx, int linear)
09331 {
09332    int sent=0;
09333    int size;
09334    int res;
09335    int fd;
09336    fd = p->subs[idx].dfd;
09337    while (len) {
09338       size = len;
09339       if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
09340          size = (linear ? READ_SIZE * 2 : READ_SIZE);
09341       res = write(fd, buf, size);
09342       if (res != size) {
09343          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
09344          return sent;
09345       }
09346       len -= size;
09347       buf += size;
09348    }
09349    return sent;
09350 }
09351 
09352 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame)
09353 {
09354    struct dahdi_pvt *p = ast->tech_pvt;
09355    int res;
09356    int idx;
09357    idx = dahdi_get_index(ast, p, 0);
09358    if (idx < 0) {
09359       ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
09360       return -1;
09361    }
09362 
09363    /* Write a frame of (presumably voice) data */
09364    if (frame->frametype != AST_FRAME_VOICE) {
09365       if (frame->frametype != AST_FRAME_IMAGE)
09366          ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
09367       return 0;
09368    }
09369    if ((frame->subclass.codec != AST_FORMAT_SLINEAR) &&
09370       (frame->subclass.codec != AST_FORMAT_ULAW) &&
09371       (frame->subclass.codec != AST_FORMAT_ALAW)) {
09372       ast_log(LOG_WARNING, "Cannot handle frames in %s format\n", ast_getformatname(frame->subclass.codec));
09373       return -1;
09374    }
09375    if (p->dialing) {
09376       ast_debug(1, "Dropping frame since I'm still dialing on %s...\n",ast->name);
09377       return 0;
09378    }
09379    if (!p->owner) {
09380       ast_debug(1, "Dropping frame since there is no active owner on %s...\n",ast->name);
09381       return 0;
09382    }
09383    if (p->cidspill) {
09384       ast_debug(1, "Dropping frame since I've still got a callerid spill on %s...\n",
09385          ast->name);
09386       return 0;
09387    }
09388    /* Return if it's not valid data */
09389    if (!frame->data.ptr || !frame->datalen)
09390       return 0;
09391 
09392    if (frame->subclass.codec == AST_FORMAT_SLINEAR) {
09393       if (!p->subs[idx].linear) {
09394          p->subs[idx].linear = 1;
09395          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09396          if (res)
09397             ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
09398       }
09399       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 1);
09400    } else {
09401       /* x-law already */
09402       if (p->subs[idx].linear) {
09403          p->subs[idx].linear = 0;
09404          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09405          if (res)
09406             ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
09407       }
09408       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 0);
09409    }
09410    if (res < 0) {
09411       ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
09412       return -1;
09413    }
09414    return 0;
09415 }
09416 
09417 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
09418 {
09419    struct dahdi_pvt *p = chan->tech_pvt;
09420    int res=-1;
09421    int idx;
09422    int func = DAHDI_FLASH;
09423 
09424    ast_mutex_lock(&p->lock);
09425    ast_debug(1, "Requested indication %d on channel %s\n", condition, chan->name);
09426    switch (p->sig) {
09427 #if defined(HAVE_PRI)
09428    case SIG_PRI_LIB_HANDLE_CASES:
09429       res = sig_pri_indicate(p->sig_pvt, chan, condition, data, datalen);
09430       ast_mutex_unlock(&p->lock);
09431       return res;
09432 #endif   /* defined(HAVE_PRI) */
09433 #if defined(HAVE_SS7)
09434    case SIG_SS7:
09435       res = sig_ss7_indicate(p->sig_pvt, chan, condition, data, datalen);
09436       ast_mutex_unlock(&p->lock);
09437       return res;
09438 #endif   /* defined(HAVE_SS7) */
09439    default:
09440       break;
09441    }
09442 #ifdef HAVE_OPENR2
09443    if (p->mfcr2 && !p->mfcr2_call_accepted) {
09444       ast_mutex_unlock(&p->lock);
09445       /* if this is an R2 call and the call is not yet accepted, we don't want the
09446          tone indications to mess up with the MF tones */
09447       return 0;
09448    }
09449 #endif
09450    idx = dahdi_get_index(chan, p, 0);
09451    if (idx == SUB_REAL) {
09452       switch (condition) {
09453       case AST_CONTROL_BUSY:
09454          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_BUSY);
09455          break;
09456       case AST_CONTROL_RINGING:
09457          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_RINGTONE);
09458 
09459          if (chan->_state != AST_STATE_UP) {
09460             if ((chan->_state != AST_STATE_RING) ||
09461                ((p->sig != SIG_FXSKS) &&
09462              (p->sig != SIG_FXSLS) &&
09463              (p->sig != SIG_FXSGS)))
09464             ast_setstate(chan, AST_STATE_RINGING);
09465          }
09466          break;
09467       case AST_CONTROL_INCOMPLETE:
09468          ast_debug(1, "Received AST_CONTROL_INCOMPLETE on %s\n", chan->name);
09469          /* act as a progress or proceeding, allowing the caller to enter additional numbers */
09470          res = 0;
09471          break;
09472       case AST_CONTROL_PROCEEDING:
09473          ast_debug(1, "Received AST_CONTROL_PROCEEDING on %s\n", chan->name);
09474          /* don't continue in ast_indicate */
09475          res = 0;
09476          break;
09477       case AST_CONTROL_PROGRESS:
09478          ast_debug(1, "Received AST_CONTROL_PROGRESS on %s\n", chan->name);
09479          /* don't continue in ast_indicate */
09480          res = 0;
09481          break;
09482       case AST_CONTROL_CONGESTION:
09483          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
09484          switch (chan->hangupcause) {
09485          case AST_CAUSE_USER_BUSY:
09486          case AST_CAUSE_NORMAL_CLEARING:
09487          case 0:/* Cause has not been set. */
09488             /* Supply a more appropriate cause. */
09489             chan->hangupcause = AST_CAUSE_CONGESTION;
09490             break;
09491          default:
09492             break;
09493          }
09494          break;
09495       case AST_CONTROL_HOLD:
09496          ast_moh_start(chan, data, p->mohinterpret);
09497          break;
09498       case AST_CONTROL_UNHOLD:
09499          ast_moh_stop(chan);
09500          break;
09501       case AST_CONTROL_RADIO_KEY:
09502          if (p->radio)
09503             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
09504          res = 0;
09505          break;
09506       case AST_CONTROL_RADIO_UNKEY:
09507          if (p->radio)
09508             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_RINGOFF);
09509          res = 0;
09510          break;
09511       case AST_CONTROL_FLASH:
09512          /* flash hookswitch */
09513          if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
09514             /* Clear out the dial buffer */
09515             p->dop.dialstr[0] = '\0';
09516             if ((ioctl(p->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
09517                ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
09518                   chan->name, strerror(errno));
09519             } else
09520                res = 0;
09521          } else
09522             res = 0;
09523          break;
09524       case AST_CONTROL_SRCUPDATE:
09525          res = 0;
09526          break;
09527       case -1:
09528          res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09529          break;
09530       }
09531    } else {
09532       res = 0;
09533    }
09534    ast_mutex_unlock(&p->lock);
09535    return res;
09536 }
09537 
09538 #if defined(HAVE_PRI)
09539 static struct ast_str *create_channel_name(struct dahdi_pvt *i, int is_outgoing, char *address)
09540 #else
09541 static struct ast_str *create_channel_name(struct dahdi_pvt *i)
09542 #endif   /* defined(HAVE_PRI) */
09543 {
09544    struct ast_str *chan_name;
09545    int x, y;
09546 
09547    /* Create the new channel name tail. */
09548    if (!(chan_name = ast_str_create(32))) {
09549       return NULL;
09550    }
09551    if (i->channel == CHAN_PSEUDO) {
09552       ast_str_set(&chan_name, 0, "pseudo-%ld", ast_random());
09553 #if defined(HAVE_PRI)
09554    } else if (i->pri) {
09555       ast_mutex_lock(&i->pri->lock);
09556       y = ++i->pri->new_chan_seq;
09557       if (is_outgoing) {
09558          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, address, y);
09559          address[0] = '\0';
09560       } else if (ast_strlen_zero(i->cid_subaddr)) {
09561          /* Put in caller-id number only since there is no subaddress. */
09562          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, i->cid_num, y);
09563       } else {
09564          /* Put in caller-id number and subaddress. */
09565          ast_str_set(&chan_name, 0, "i%d/%s:%s-%x", i->pri->span, i->cid_num,
09566             i->cid_subaddr, y);
09567       }
09568       ast_mutex_unlock(&i->pri->lock);
09569 #endif   /* defined(HAVE_PRI) */
09570    } else {
09571       y = 1;
09572       do {
09573          ast_str_set(&chan_name, 0, "%d-%d", i->channel, y);
09574          for (x = 0; x < 3; ++x) {
09575             if (i->subs[x].owner && !strcasecmp(ast_str_buffer(chan_name),
09576                i->subs[x].owner->name + 6)) {
09577                break;
09578             }
09579          }
09580          ++y;
09581       } while (x < 3);
09582    }
09583    return chan_name;
09584 }
09585 
09586 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid)
09587 {
09588    struct ast_channel *tmp;
09589    format_t deflaw;
09590    int x;
09591    int features;
09592    struct ast_str *chan_name;
09593    struct ast_variable *v;
09594    char *dashptr;
09595    char device_name[AST_CHANNEL_NAME];
09596 
09597    if (i->subs[idx].owner) {
09598       ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[idx]);
09599       return NULL;
09600    }
09601 
09602 #if defined(HAVE_PRI)
09603    /*
09604     * The dnid has been stuffed with the called-number[:subaddress]
09605     * by dahdi_request() for outgoing calls.
09606     */
09607    chan_name = create_channel_name(i, i->outgoing, i->dnid);
09608 #else
09609    chan_name = create_channel_name(i);
09610 #endif   /* defined(HAVE_PRI) */
09611    if (!chan_name) {
09612       return NULL;
09613    }
09614 
09615    tmp = ast_channel_alloc(0, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "DAHDI/%s", ast_str_buffer(chan_name));
09616    ast_free(chan_name);
09617    if (!tmp)
09618       return NULL;
09619    tmp->tech = &dahdi_tech;
09620 #if defined(HAVE_PRI)
09621    if (i->pri) {
09622       ast_cc_copy_config_params(i->cc_params, i->pri->cc_params);
09623    }
09624 #endif   /* defined(HAVE_PRI) */
09625    ast_channel_cc_params_init(tmp, i->cc_params);
09626    if (law) {
09627       i->law = law;
09628       if (law == DAHDI_LAW_ALAW) {
09629          deflaw = AST_FORMAT_ALAW;
09630       } else {
09631          deflaw = AST_FORMAT_ULAW;
09632       }
09633    } else {
09634       switch (i->sig) {
09635       case SIG_PRI_LIB_HANDLE_CASES:
09636          /* Make sure companding law is known. */
09637          i->law = (i->law_default == DAHDI_LAW_ALAW)
09638             ? DAHDI_LAW_ALAW : DAHDI_LAW_MULAW;
09639          break;
09640       default:
09641          i->law = i->law_default;
09642          break;
09643       }
09644       if (i->law_default == DAHDI_LAW_ALAW) {
09645          deflaw = AST_FORMAT_ALAW;
09646       } else {
09647          deflaw = AST_FORMAT_ULAW;
09648       }
09649    }
09650    ast_channel_set_fd(tmp, 0, i->subs[idx].dfd);
09651    tmp->nativeformats = deflaw;
09652    /* Start out assuming ulaw since it's smaller :) */
09653    tmp->rawreadformat = deflaw;
09654    tmp->readformat = deflaw;
09655    tmp->rawwriteformat = deflaw;
09656    tmp->writeformat = deflaw;
09657    i->subs[idx].linear = 0;
09658    dahdi_setlinear(i->subs[idx].dfd, i->subs[idx].linear);
09659    features = 0;
09660    if (idx == SUB_REAL) {
09661       if (i->busydetect && CANBUSYDETECT(i))
09662          features |= DSP_FEATURE_BUSY_DETECT;
09663       if ((i->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(i))
09664          features |= DSP_FEATURE_CALL_PROGRESS;
09665       if ((i->waitfordialtone) && CANPROGRESSDETECT(i))
09666          features |= DSP_FEATURE_WAITDIALTONE;
09667       if ((!i->outgoing && (i->callprogress & CALLPROGRESS_FAX_INCOMING)) ||
09668          (i->outgoing && (i->callprogress & CALLPROGRESS_FAX_OUTGOING))) {
09669          features |= DSP_FEATURE_FAX_DETECT;
09670       }
09671       x = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
09672       if (ioctl(i->subs[idx].dfd, DAHDI_TONEDETECT, &x)) {
09673          i->hardwaredtmf = 0;
09674          features |= DSP_FEATURE_DIGIT_DETECT;
09675       } else if (NEED_MFDETECT(i)) {
09676          i->hardwaredtmf = 1;
09677          features |= DSP_FEATURE_DIGIT_DETECT;
09678       }
09679    }
09680    if (features) {
09681       if (i->dsp) {
09682          ast_debug(1, "Already have a dsp on %s?\n", tmp->name);
09683       } else {
09684          if (i->channel != CHAN_PSEUDO)
09685             i->dsp = ast_dsp_new();
09686          else
09687             i->dsp = NULL;
09688          if (i->dsp) {
09689             i->dsp_features = features;
09690 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09691             /* We cannot do progress detection until receive PROGRESS message */
09692             if (i->outgoing && (dahdi_sig_pri_lib_handles(i->sig) || (i->sig == SIG_SS7))) {
09693                /* Remember requested DSP features, don't treat
09694                   talking as ANSWER */
09695                i->dsp_features = features & ~DSP_PROGRESS_TALK;
09696                features = 0;
09697             }
09698 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09699             ast_dsp_set_features(i->dsp, features);
09700             ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
09701             if (!ast_strlen_zero(progzone))
09702                ast_dsp_set_call_progress_zone(i->dsp, progzone);
09703             if (i->busydetect && CANBUSYDETECT(i)) {
09704                ast_dsp_set_busy_count(i->dsp, i->busycount);
09705                ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
09706             }
09707          }
09708       }
09709    }
09710 
09711    if (state == AST_STATE_RING)
09712       tmp->rings = 1;
09713    tmp->tech_pvt = i;
09714    if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
09715       /* Only FXO signalled stuff can be picked up */
09716       tmp->callgroup = i->callgroup;
09717       tmp->pickupgroup = i->pickupgroup;
09718    }
09719    if (!ast_strlen_zero(i->parkinglot))
09720       ast_string_field_set(tmp, parkinglot, i->parkinglot);
09721    if (!ast_strlen_zero(i->language))
09722       ast_string_field_set(tmp, language, i->language);
09723    if (!i->owner)
09724       i->owner = tmp;
09725    if (!ast_strlen_zero(i->accountcode))
09726       ast_string_field_set(tmp, accountcode, i->accountcode);
09727    if (i->amaflags)
09728       tmp->amaflags = i->amaflags;
09729    i->subs[idx].owner = tmp;
09730    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
09731    if (!analog_lib_handles(i->sig, i->radio, i->oprmode)) {
09732       ast_string_field_set(tmp, call_forward, i->call_forward);
09733    }
09734    /* If we've been told "no ADSI" then enforce it */
09735    if (!i->adsi)
09736       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
09737    if (!ast_strlen_zero(i->exten))
09738       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
09739    if (!ast_strlen_zero(i->rdnis)) {
09740       tmp->redirecting.from.number.valid = 1;
09741       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
09742    }
09743    if (!ast_strlen_zero(i->dnid)) {
09744       tmp->dialed.number.str = ast_strdup(i->dnid);
09745    }
09746 
09747    /* Don't use ast_set_callerid() here because it will
09748     * generate a needless NewCallerID event */
09749 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09750    if (!ast_strlen_zero(i->cid_ani)) {
09751       tmp->caller.ani.number.valid = 1;
09752       tmp->caller.ani.number.str = ast_strdup(i->cid_ani);
09753    } else if (!ast_strlen_zero(i->cid_num)) {
09754       tmp->caller.ani.number.valid = 1;
09755       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09756    }
09757 #else
09758    if (!ast_strlen_zero(i->cid_num)) {
09759       tmp->caller.ani.number.valid = 1;
09760       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09761    }
09762 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09763    tmp->caller.id.name.presentation = i->callingpres;
09764    tmp->caller.id.number.presentation = i->callingpres;
09765    tmp->caller.id.number.plan = i->cid_ton;
09766    tmp->caller.ani2 = i->cid_ani2;
09767    tmp->caller.id.tag = ast_strdup(i->cid_tag);
09768    /* clear the fake event in case we posted one before we had ast_channel */
09769    i->fake_event = 0;
09770    /* Assure there is no confmute on this channel */
09771    dahdi_confmute(i, 0);
09772    i->muting = 0;
09773    /* Configure the new channel jb */
09774    ast_jb_configure(tmp, &global_jbconf);
09775 
09776    /* Set initial device state */
09777    ast_copy_string(device_name, tmp->name, sizeof(device_name));
09778    dashptr = strrchr(device_name, '-');
09779    if (dashptr) {
09780       *dashptr = '\0';
09781    }
09782    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
09783 
09784    for (v = i->vars ; v ; v = v->next)
09785       pbx_builtin_setvar_helper(tmp, v->name, v->value);
09786 
09787    ast_module_ref(ast_module_info->self);
09788 
09789    dahdi_ami_channel_event(i, tmp);
09790    if (startpbx) {
09791 #ifdef HAVE_OPENR2
09792       if (i->mfcr2call) {
09793          pbx_builtin_setvar_helper(tmp, "MFCR2_CATEGORY", openr2_proto_get_category_string(i->mfcr2_recvd_category));
09794       }
09795 #endif
09796       if (ast_pbx_start(tmp)) {
09797          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
09798          ast_hangup(tmp);
09799          return NULL;
09800       }
09801    }
09802    return tmp;
09803 }
09804 
09805 
09806 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
09807 {
09808    char c;
09809 
09810    *str = 0; /* start with empty output buffer */
09811    for (;;)
09812    {
09813       /* Wait for the first digit (up to specified ms). */
09814       c = ast_waitfordigit(chan, ms);
09815       /* if timeout, hangup or error, return as such */
09816       if (c < 1)
09817          return c;
09818       *str++ = c;
09819       *str = 0;
09820       if (strchr(term, c))
09821          return 1;
09822    }
09823 }
09824 
09825 static int dahdi_wink(struct dahdi_pvt *p, int idx)
09826 {
09827    int j;
09828    dahdi_set_hook(p->subs[idx].dfd, DAHDI_WINK);
09829    for (;;)
09830    {
09831       /* set bits of interest */
09832       j = DAHDI_IOMUX_SIGEVENT;
09833       /* wait for some happening */
09834       if (ioctl(p->subs[idx].dfd,DAHDI_IOMUX,&j) == -1) return(-1);
09835       /* exit loop if we have it */
09836       if (j & DAHDI_IOMUX_SIGEVENT) break;
09837    }
09838    /* get the event info */
09839    if (ioctl(p->subs[idx].dfd,DAHDI_GETEVENT,&j) == -1) return(-1);
09840    return 0;
09841 }
09842 
09843 /*! \brief enable or disable the chan_dahdi Do-Not-Disturb mode for a DAHDI channel
09844  * \param dahdichan "Physical" DAHDI channel (e.g: DAHDI/5)
09845  * \param flag on 1 to enable, 0 to disable, -1 return dnd value
09846  *
09847  * chan_dahdi has a DND (Do Not Disturb) mode for each dahdichan (physical
09848  * DAHDI channel). Use this to enable or disable it.
09849  *
09850  * \bug the use of the word "channel" for those dahdichans is really confusing.
09851  */
09852 static int dahdi_dnd(struct dahdi_pvt *dahdichan, int flag)
09853 {
09854    if (analog_lib_handles(dahdichan->sig, dahdichan->radio, dahdichan->oprmode)) {
09855       return analog_dnd(dahdichan->sig_pvt, flag);
09856    }
09857 
09858    if (flag == -1) {
09859       return dahdichan->dnd;
09860    }
09861 
09862    /* Do not disturb */
09863    dahdichan->dnd = flag;
09864    ast_verb(3, "%s DND on channel %d\n",
09865          flag? "Enabled" : "Disabled",
09866          dahdichan->channel);
09867    manager_event(EVENT_FLAG_SYSTEM, "DNDState",
09868          "Channel: DAHDI/%d\r\n"
09869          "Status: %s\r\n", dahdichan->channel,
09870          flag? "enabled" : "disabled");
09871 
09872    return 0;
09873 }
09874 
09875 static int canmatch_featurecode(const char *exten)
09876 {
09877    int extlen = strlen(exten);
09878    const char *pickup_ext;
09879    if (!extlen) {
09880       return 1;
09881    }
09882    pickup_ext = ast_pickup_ext();
09883    if (extlen < strlen(pickup_ext) && !strncmp(pickup_ext, exten, extlen)) {
09884       return 1;
09885    }
09886    /* hardcoded features are *60, *67, *69, *70, *72, *73, *78, *79, *82, *0 */
09887    if (exten[0] == '*' && extlen < 3) {
09888       if (extlen == 1) {
09889          return 1;
09890       }
09891       /* "*0" should be processed before it gets here */
09892       switch (exten[1]) {
09893       case '6':
09894       case '7':
09895       case '8':
09896          return 1;
09897       }
09898    }
09899    return 0;
09900 }
09901 
09902 static void *analog_ss_thread(void *data)
09903 {
09904    struct ast_channel *chan = data;
09905    struct dahdi_pvt *p = chan->tech_pvt;
09906    char exten[AST_MAX_EXTENSION] = "";
09907    char exten2[AST_MAX_EXTENSION] = "";
09908    unsigned char buf[256];
09909    char dtmfcid[300];
09910    char dtmfbuf[300];
09911    struct callerid_state *cs = NULL;
09912    char *name = NULL, *number = NULL;
09913    int distMatches;
09914    int curRingData[3];
09915    int receivedRingT;
09916    int counter1;
09917    int counter;
09918    int samples = 0;
09919    struct ast_smdi_md_message *smdi_msg = NULL;
09920    int flags = 0;
09921    int i;
09922    int timeout;
09923    int getforward = 0;
09924    char *s1, *s2;
09925    int len = 0;
09926    int res;
09927    int idx;
09928 
09929    ast_mutex_lock(&ss_thread_lock);
09930    ss_thread_count++;
09931    ast_mutex_unlock(&ss_thread_lock);
09932    /* in the bizarre case where the channel has become a zombie before we
09933       even get started here, abort safely
09934    */
09935    if (!p) {
09936       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
09937       ast_hangup(chan);
09938       goto quit;
09939    }
09940    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
09941    idx = dahdi_get_index(chan, p, 1);
09942    if (idx < 0) {
09943       ast_log(LOG_WARNING, "Huh?\n");
09944       ast_hangup(chan);
09945       goto quit;
09946    }
09947    if (p->dsp)
09948       ast_dsp_digitreset(p->dsp);
09949    switch (p->sig) {
09950    case SIG_FEATD:
09951    case SIG_FEATDMF:
09952    case SIG_FEATDMF_TA:
09953    case SIG_E911:
09954    case SIG_FGC_CAMAMF:
09955    case SIG_FEATB:
09956    case SIG_EMWINK:
09957    case SIG_SF_FEATD:
09958    case SIG_SF_FEATDMF:
09959    case SIG_SF_FEATB:
09960    case SIG_SFWINK:
09961       if (dahdi_wink(p, idx))
09962          goto quit;
09963       /* Fall through */
09964    case SIG_EM:
09965    case SIG_EM_E1:
09966    case SIG_SF:
09967    case SIG_FGC_CAMA:
09968       res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09969       if (p->dsp)
09970          ast_dsp_digitreset(p->dsp);
09971       /* set digit mode appropriately */
09972       if (p->dsp) {
09973          if (NEED_MFDETECT(p))
09974             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
09975          else
09976             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
09977       }
09978       memset(dtmfbuf, 0, sizeof(dtmfbuf));
09979       /* Wait for the first digit only if immediate=no */
09980       if (!p->immediate)
09981          /* Wait for the first digit (up to 5 seconds). */
09982          res = ast_waitfordigit(chan, 5000);
09983       else
09984          res = 0;
09985       if (res > 0) {
09986          /* save first char */
09987          dtmfbuf[0] = res;
09988          switch (p->sig) {
09989          case SIG_FEATD:
09990          case SIG_SF_FEATD:
09991             res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
09992             if (res > 0)
09993                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
09994             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09995             break;
09996          case SIG_FEATDMF_TA:
09997             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09998             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09999             if (dahdi_wink(p, idx)) goto quit;
10000             dtmfbuf[0] = 0;
10001             /* Wait for the first digit (up to 5 seconds). */
10002             res = ast_waitfordigit(chan, 5000);
10003             if (res <= 0) break;
10004             dtmfbuf[0] = res;
10005             /* fall through intentionally */
10006          case SIG_FEATDMF:
10007          case SIG_E911:
10008          case SIG_FGC_CAMAMF:
10009          case SIG_SF_FEATDMF:
10010             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10011             /* if international caca, do it again to get real ANO */
10012             if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
10013             {
10014                if (dahdi_wink(p, idx)) goto quit;
10015                dtmfbuf[0] = 0;
10016                /* Wait for the first digit (up to 5 seconds). */
10017                res = ast_waitfordigit(chan, 5000);
10018                if (res <= 0) break;
10019                dtmfbuf[0] = res;
10020                res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10021             }
10022             if (res > 0) {
10023                /* if E911, take off hook */
10024                if (p->sig == SIG_E911)
10025                   dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10026                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
10027             }
10028             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10029             break;
10030          case SIG_FEATB:
10031          case SIG_SF_FEATB:
10032             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10033             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10034             break;
10035          case SIG_EMWINK:
10036             /* if we received a '*', we are actually receiving Feature Group D
10037                dial syntax, so use that mode; otherwise, fall through to normal
10038                mode
10039             */
10040             if (res == '*') {
10041                res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
10042                if (res > 0)
10043                   res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
10044                if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10045                break;
10046             }
10047          default:
10048             /* If we got the first digit, get the rest */
10049             len = 1;
10050             dtmfbuf[len] = '\0';
10051             while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
10052                if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
10053                   timeout = matchdigittimeout;
10054                } else {
10055                   timeout = gendigittimeout;
10056                }
10057                res = ast_waitfordigit(chan, timeout);
10058                if (res < 0) {
10059                   ast_debug(1, "waitfordigit returned < 0...\n");
10060                   ast_hangup(chan);
10061                   goto quit;
10062                } else if (res) {
10063                   dtmfbuf[len++] = res;
10064                   dtmfbuf[len] = '\0';
10065                } else {
10066                   break;
10067                }
10068             }
10069             break;
10070          }
10071       }
10072       if (res == -1) {
10073          ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
10074          ast_hangup(chan);
10075          goto quit;
10076       } else if (res < 0) {
10077          ast_debug(1, "Got hung up before digits finished\n");
10078          ast_hangup(chan);
10079          goto quit;
10080       }
10081 
10082       if (p->sig == SIG_FGC_CAMA) {
10083          char anibuf[100];
10084 
10085          if (ast_safe_sleep(chan,1000) == -1) {
10086             ast_hangup(chan);
10087             goto quit;
10088          }
10089          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10090          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
10091          res = my_getsigstr(chan, anibuf, "#", 10000);
10092          if ((res > 0) && (strlen(anibuf) > 2)) {
10093             if (anibuf[strlen(anibuf) - 1] == '#')
10094                anibuf[strlen(anibuf) - 1] = 0;
10095             ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
10096          }
10097          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10098       }
10099 
10100       ast_copy_string(exten, dtmfbuf, sizeof(exten));
10101       if (ast_strlen_zero(exten))
10102          ast_copy_string(exten, "s", sizeof(exten));
10103       if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
10104          /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
10105          if (exten[0] == '*') {
10106             char *stringp=NULL;
10107             ast_copy_string(exten2, exten, sizeof(exten2));
10108             /* Parse out extension and callerid */
10109             stringp=exten2 +1;
10110             s1 = strsep(&stringp, "*");
10111             s2 = strsep(&stringp, "*");
10112             if (s2) {
10113                if (!ast_strlen_zero(p->cid_num))
10114                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10115                else
10116                   ast_set_callerid(chan, s1, NULL, s1);
10117                ast_copy_string(exten, s2, sizeof(exten));
10118             } else
10119                ast_copy_string(exten, s1, sizeof(exten));
10120          } else if (p->sig == SIG_FEATD)
10121             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10122       }
10123       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
10124          if (exten[0] == '*') {
10125             char *stringp=NULL;
10126             ast_copy_string(exten2, exten, sizeof(exten2));
10127             /* Parse out extension and callerid */
10128             stringp=exten2 +1;
10129             s1 = strsep(&stringp, "#");
10130             s2 = strsep(&stringp, "#");
10131             if (s2) {
10132                if (!ast_strlen_zero(p->cid_num))
10133                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10134                else
10135                   if (*(s1 + 2))
10136                      ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
10137                ast_copy_string(exten, s2 + 1, sizeof(exten));
10138             } else
10139                ast_copy_string(exten, s1 + 2, sizeof(exten));
10140          } else
10141             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10142       }
10143       if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
10144          if (exten[0] == '*') {
10145             char *stringp=NULL;
10146             ast_copy_string(exten2, exten, sizeof(exten2));
10147             /* Parse out extension and callerid */
10148             stringp=exten2 +1;
10149             s1 = strsep(&stringp, "#");
10150             s2 = strsep(&stringp, "#");
10151             if (s2 && (*(s2 + 1) == '0')) {
10152                if (*(s2 + 2))
10153                   ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
10154             }
10155             if (s1)  ast_copy_string(exten, s1, sizeof(exten));
10156             else ast_copy_string(exten, "911", sizeof(exten));
10157          } else
10158             ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10159       }
10160       if (p->sig == SIG_FEATB) {
10161          if (exten[0] == '*') {
10162             char *stringp=NULL;
10163             ast_copy_string(exten2, exten, sizeof(exten2));
10164             /* Parse out extension and callerid */
10165             stringp=exten2 +1;
10166             s1 = strsep(&stringp, "#");
10167             ast_copy_string(exten, exten2 + 1, sizeof(exten));
10168          } else
10169             ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10170       }
10171       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
10172          dahdi_wink(p, idx);
10173          /* some switches require a minimum guard time between
10174             the last FGD wink and something that answers
10175             immediately. This ensures it */
10176          if (ast_safe_sleep(chan, 100)) {
10177             ast_hangup(chan);
10178             goto quit;
10179          }
10180       }
10181       dahdi_enable_ec(p);
10182       if (NEED_MFDETECT(p)) {
10183          if (p->dsp) {
10184             if (!p->hardwaredtmf)
10185                ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10186             else {
10187                ast_dsp_free(p->dsp);
10188                p->dsp = NULL;
10189             }
10190          }
10191       }
10192 
10193       if (ast_exists_extension(chan, chan->context, exten, 1,
10194          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
10195          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
10196          if (p->dsp) ast_dsp_digitreset(p->dsp);
10197          res = ast_pbx_run(chan);
10198          if (res) {
10199             ast_log(LOG_WARNING, "PBX exited non-zero\n");
10200             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10201          }
10202          goto quit;
10203       } else {
10204          ast_verb(2, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
10205          sleep(2);
10206          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_INFO);
10207          if (res < 0)
10208             ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
10209          else
10210             sleep(1);
10211          res = ast_streamfile(chan, "ss-noservice", chan->language);
10212          if (res >= 0)
10213             ast_waitstream(chan, "");
10214          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10215          ast_hangup(chan);
10216          goto quit;
10217       }
10218       break;
10219    case SIG_FXOLS:
10220    case SIG_FXOGS:
10221    case SIG_FXOKS:
10222       /* Read the first digit */
10223       timeout = firstdigittimeout;
10224       /* If starting a threeway call, never timeout on the first digit so someone
10225          can use flash-hook as a "hold" feature */
10226       if (p->subs[SUB_THREEWAY].owner)
10227          timeout = 999999;
10228       while (len < AST_MAX_EXTENSION-1) {
10229          /* Read digit unless it's supposed to be immediate, in which case the
10230             only answer is 's' */
10231          if (p->immediate)
10232             res = 's';
10233          else
10234             res = ast_waitfordigit(chan, timeout);
10235          timeout = 0;
10236          if (res < 0) {
10237             ast_debug(1, "waitfordigit returned < 0...\n");
10238             res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10239             ast_hangup(chan);
10240             goto quit;
10241          } else if (res) {
10242             ast_debug(1,"waitfordigit returned '%c' (%d), timeout = %d\n", res, res, timeout);
10243             exten[len++]=res;
10244             exten[len] = '\0';
10245          }
10246          if (!ast_ignore_pattern(chan->context, exten))
10247             tone_zone_play_tone(p->subs[idx].dfd, -1);
10248          else
10249             tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
10250          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && !ast_parking_ext_valid(exten, chan, chan->context)) {
10251             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
10252                if (getforward) {
10253                   /* Record this as the forwarding extension */
10254                   ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
10255                   ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
10256                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10257                   if (res)
10258                      break;
10259                   usleep(500000);
10260                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10261                   sleep(1);
10262                   memset(exten, 0, sizeof(exten));
10263                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
10264                   len = 0;
10265                   getforward = 0;
10266                } else {
10267                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10268                   ast_copy_string(chan->exten, exten, sizeof(chan->exten));
10269                   if (!ast_strlen_zero(p->cid_num)) {
10270                      if (!p->hidecallerid)
10271                         ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10272                      else
10273                         ast_set_callerid(chan, NULL, NULL, p->cid_num);
10274                   }
10275                   if (!ast_strlen_zero(p->cid_name)) {
10276                      if (!p->hidecallerid)
10277                         ast_set_callerid(chan, NULL, p->cid_name, NULL);
10278                   }
10279                   ast_setstate(chan, AST_STATE_RING);
10280                   dahdi_enable_ec(p);
10281                   res = ast_pbx_run(chan);
10282                   if (res) {
10283                      ast_log(LOG_WARNING, "PBX exited non-zero\n");
10284                      res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10285                   }
10286                   goto quit;
10287                }
10288             } else {
10289                /* It's a match, but they just typed a digit, and there is an ambiguous match,
10290                   so just set the timeout to matchdigittimeout and wait some more */
10291                timeout = matchdigittimeout;
10292             }
10293          } else if (res == 0) {
10294             ast_debug(1, "not enough digits (and no ambiguous match)...\n");
10295             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10296             dahdi_wait_event(p->subs[idx].dfd);
10297             ast_hangup(chan);
10298             goto quit;
10299          } else if (p->callwaiting && !strcmp(exten, "*70")) {
10300             ast_verb(3, "Disabling call waiting on %s\n", chan->name);
10301             /* Disable call waiting if enabled */
10302             p->callwaiting = 0;
10303             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10304             if (res) {
10305                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10306                   chan->name, strerror(errno));
10307             }
10308             len = 0;
10309             ioctl(p->subs[idx].dfd,DAHDI_CONFDIAG,&len);
10310             memset(exten, 0, sizeof(exten));
10311             timeout = firstdigittimeout;
10312 
10313          } else if (!strcmp(exten,ast_pickup_ext())) {
10314             /* Scan all channels and see if there are any
10315              * ringing channels that have call groups
10316              * that equal this channels pickup group
10317              */
10318             if (idx == SUB_REAL) {
10319                /* Switch us from Third call to Call Wait */
10320                if (p->subs[SUB_THREEWAY].owner) {
10321                   /* If you make a threeway call and the *8# a call, it should actually
10322                      look like a callwait */
10323                   alloc_sub(p, SUB_CALLWAIT);
10324                   swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
10325                   unalloc_sub(p, SUB_THREEWAY);
10326                }
10327                dahdi_enable_ec(p);
10328                if (ast_pickup_call(chan)) {
10329                   ast_debug(1, "No call pickup possible...\n");
10330                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10331                   dahdi_wait_event(p->subs[idx].dfd);
10332                }
10333                ast_hangup(chan);
10334                goto quit;
10335             } else {
10336                ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
10337                ast_hangup(chan);
10338                goto quit;
10339             }
10340 
10341          } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
10342             ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
10343             /* Disable Caller*ID if enabled */
10344             p->hidecallerid = 1;
10345             ast_party_number_free(&chan->caller.id.number);
10346             ast_party_number_init(&chan->caller.id.number);
10347             ast_party_name_free(&chan->caller.id.name);
10348             ast_party_name_init(&chan->caller.id.name);
10349             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10350             if (res) {
10351                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10352                   chan->name, strerror(errno));
10353             }
10354             len = 0;
10355             memset(exten, 0, sizeof(exten));
10356             timeout = firstdigittimeout;
10357          } else if (p->callreturn && !strcmp(exten, "*69")) {
10358             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10359             break;
10360          } else if (!strcmp(exten, "*78")) {
10361             dahdi_dnd(p, 1);
10362             /* Do not disturb */
10363             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10364             getforward = 0;
10365             memset(exten, 0, sizeof(exten));
10366             len = 0;
10367          } else if (!strcmp(exten, "*79")) {
10368             dahdi_dnd(p, 0);
10369             /* Do not disturb */
10370             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10371             getforward = 0;
10372             memset(exten, 0, sizeof(exten));
10373             len = 0;
10374          } else if (p->cancallforward && !strcmp(exten, "*72")) {
10375             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10376             getforward = 1;
10377             memset(exten, 0, sizeof(exten));
10378             len = 0;
10379          } else if (p->cancallforward && !strcmp(exten, "*73")) {
10380             ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
10381             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10382             memset(p->call_forward, 0, sizeof(p->call_forward));
10383             getforward = 0;
10384             memset(exten, 0, sizeof(exten));
10385             len = 0;
10386          } else if ((p->transfer || p->canpark) && ast_parking_ext_valid(exten, chan, chan->context) &&
10387                   p->subs[SUB_THREEWAY].owner &&
10388                   ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
10389             /* This is a three way call, the main call being a real channel,
10390                and we're parking the first call. */
10391             ast_masq_park_call_exten(ast_bridged_channel(p->subs[SUB_THREEWAY].owner),
10392                chan, exten, chan->context, 0, NULL);
10393             ast_verb(3, "Parking call to '%s'\n", chan->name);
10394             break;
10395          } else if (p->hidecallerid && !strcmp(exten, "*82")) {
10396             ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
10397             /* Enable Caller*ID if enabled */
10398             p->hidecallerid = 0;
10399             ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
10400             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10401             if (res) {
10402                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10403                   chan->name, strerror(errno));
10404             }
10405             len = 0;
10406             memset(exten, 0, sizeof(exten));
10407             timeout = firstdigittimeout;
10408          } else if (!strcmp(exten, "*0")) {
10409             struct ast_channel *nbridge =
10410                p->subs[SUB_THREEWAY].owner;
10411             struct dahdi_pvt *pbridge = NULL;
10412             /* set up the private struct of the bridged one, if any */
10413             if (nbridge && ast_bridged_channel(nbridge))
10414                pbridge = ast_bridged_channel(nbridge)->tech_pvt;
10415             if (nbridge && pbridge &&
10416                (nbridge->tech == &dahdi_tech) &&
10417                (ast_bridged_channel(nbridge)->tech == &dahdi_tech) &&
10418                ISTRUNK(pbridge)) {
10419                int func = DAHDI_FLASH;
10420                /* Clear out the dial buffer */
10421                p->dop.dialstr[0] = '\0';
10422                /* flash hookswitch */
10423                if ((ioctl(pbridge->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
10424                   ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
10425                      nbridge->name, strerror(errno));
10426                }
10427                swap_subs(p, SUB_REAL, SUB_THREEWAY);
10428                unalloc_sub(p, SUB_THREEWAY);
10429                p->owner = p->subs[SUB_REAL].owner;
10430                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
10431                   ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
10432                ast_hangup(chan);
10433                goto quit;
10434             } else {
10435                tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10436                dahdi_wait_event(p->subs[idx].dfd);
10437                tone_zone_play_tone(p->subs[idx].dfd, -1);
10438                swap_subs(p, SUB_REAL, SUB_THREEWAY);
10439                unalloc_sub(p, SUB_THREEWAY);
10440                p->owner = p->subs[SUB_REAL].owner;
10441                ast_hangup(chan);
10442                goto quit;
10443             }
10444          } else if (!ast_canmatch_extension(chan, chan->context, exten, 1,
10445             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
10446             && !canmatch_featurecode(exten)) {
10447             ast_debug(1, "Can't match %s from '%s' in context %s\n", exten,
10448                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<Unknown Caller>"),
10449                chan->context);
10450             break;
10451          }
10452          if (!timeout)
10453             timeout = gendigittimeout;
10454          if (len && !ast_ignore_pattern(chan->context, exten))
10455             tone_zone_play_tone(p->subs[idx].dfd, -1);
10456       }
10457       break;
10458    case SIG_FXSLS:
10459    case SIG_FXSGS:
10460    case SIG_FXSKS:
10461       /* check for SMDI messages */
10462       if (p->use_smdi && p->smdi_iface) {
10463          smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
10464 
10465          if (smdi_msg != NULL) {
10466             ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
10467 
10468             if (smdi_msg->type == 'B')
10469                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
10470             else if (smdi_msg->type == 'N')
10471                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
10472 
10473             ast_debug(1, "Received SMDI message on %s\n", chan->name);
10474          } else {
10475             ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
10476          }
10477       }
10478 
10479       if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
10480          number = smdi_msg->calling_st;
10481 
10482       /* If we want caller id, we're in a prering state due to a polarity reversal
10483        * and we're set to use a polarity reversal to trigger the start of caller id,
10484        * grab the caller id and wait for ringing to start... */
10485       } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING &&
10486                    (p->cid_start == CID_START_POLARITY || p->cid_start == CID_START_POLARITY_IN || p->cid_start == CID_START_DTMF_NOALERT))) {
10487          /* If set to use DTMF CID signalling, listen for DTMF */
10488          if (p->cid_signalling == CID_SIG_DTMF) {
10489             int k = 0;
10490             cs = NULL;
10491             ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
10492             dahdi_setlinear(p->subs[idx].dfd, 0);
10493             /*
10494              * We are the only party interested in the Rx stream since
10495              * we have not answered yet.  We don't need or even want DTMF
10496              * emulation.  The DTMF digits can come so fast that emulation
10497              * can drop some of them.
10498              */
10499             ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
10500             res = 4000;/* This is a typical OFF time between rings. */
10501             for (;;) {
10502                struct ast_frame *f;
10503                res = ast_waitfor(chan, res);
10504                if (res <= 0) {
10505                   /*
10506                    * We do not need to restore the dahdi_setlinear()
10507                    * or AST_FLAG_END_DTMF_ONLY flag settings since we
10508                    * are hanging up the channel.
10509                    */
10510                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10511                      "Exiting simple switch\n");
10512                   ast_hangup(chan);
10513                   goto quit;
10514                }
10515                f = ast_read(chan);
10516                if (!f)
10517                   break;
10518                if (f->frametype == AST_FRAME_DTMF) {
10519                   if (k < ARRAY_LEN(dtmfbuf) - 1) {
10520                      dtmfbuf[k++] = f->subclass.integer;
10521                   }
10522                   ast_debug(1, "CID got digit '%c'\n", f->subclass.integer);
10523                   res = 4000;/* This is a typical OFF time between rings. */
10524                }
10525                ast_frfree(f);
10526                if (chan->_state == AST_STATE_RING ||
10527                   chan->_state == AST_STATE_RINGING)
10528                   break; /* Got ring */
10529             }
10530             ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
10531             dtmfbuf[k] = '\0';
10532             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10533             /* Got cid and ring. */
10534             ast_debug(1, "CID got string '%s'\n", dtmfbuf);
10535             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10536             ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
10537             /* If first byte is NULL, we have no cid */
10538             if (!ast_strlen_zero(dtmfcid))
10539                number = dtmfcid;
10540             else
10541                number = NULL;
10542          /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10543          } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
10544             cs = callerid_new(p->cid_signalling);
10545             if (cs) {
10546                samples = 0;
10547 #if 1
10548                bump_gains(p);
10549 #endif
10550                /* Take out of linear mode for Caller*ID processing */
10551                dahdi_setlinear(p->subs[idx].dfd, 0);
10552 
10553                /* First we wait and listen for the Caller*ID */
10554                for (;;) {
10555                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10556                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10557                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10558                      callerid_free(cs);
10559                      ast_hangup(chan);
10560                      goto quit;
10561                   }
10562                   if (i & DAHDI_IOMUX_SIGEVENT) {
10563                      res = dahdi_get_event(p->subs[idx].dfd);
10564                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10565                      if (res == DAHDI_EVENT_NOALARM) {
10566                         p->inalarm = 0;
10567                      }
10568 
10569                      if (p->cid_signalling == CID_SIG_V23_JP) {
10570                         if (res == DAHDI_EVENT_RINGBEGIN) {
10571                            res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10572                            usleep(1);
10573                         }
10574                      } else {
10575                         res = 0;
10576                         break;
10577                      }
10578                   } else if (i & DAHDI_IOMUX_READ) {
10579                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10580                      if (res < 0) {
10581                         if (errno != ELAST) {
10582                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10583                            callerid_free(cs);
10584                            ast_hangup(chan);
10585                            goto quit;
10586                         }
10587                         break;
10588                      }
10589                      samples += res;
10590 
10591                      if (p->cid_signalling == CID_SIG_V23_JP) {
10592                         res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
10593                      } else {
10594                         res = callerid_feed(cs, buf, res, AST_LAW(p));
10595                      }
10596                      if (res < 0) {
10597                         /*
10598                          * The previous diagnostic message output likely
10599                          * explains why it failed.
10600                          */
10601                         ast_log(LOG_WARNING,
10602                            "Failed to decode CallerID on channel '%s'\n",
10603                            chan->name);
10604                         break;
10605                      } else if (res)
10606                         break;
10607                      else if (samples > (8000 * 10))
10608                         break;
10609                   }
10610                }
10611                if (res == 1) {
10612                   callerid_get(cs, &name, &number, &flags);
10613                   ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10614                }
10615 
10616                if (p->cid_signalling == CID_SIG_V23_JP) {
10617                   res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
10618                   usleep(1);
10619                }
10620 
10621                /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
10622                res = 4000;/* This is a typical OFF time between rings. */
10623                for (;;) {
10624                   struct ast_frame *f;
10625                   res = ast_waitfor(chan, res);
10626                   if (res <= 0) {
10627                      ast_log(LOG_WARNING, "CID timed out waiting for ring. "
10628                         "Exiting simple switch\n");
10629                      ast_hangup(chan);
10630                      goto quit;
10631                   }
10632                   if (!(f = ast_read(chan))) {
10633                      ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
10634                      ast_hangup(chan);
10635                      goto quit;
10636                   }
10637                   ast_frfree(f);
10638                   if (chan->_state == AST_STATE_RING ||
10639                      chan->_state == AST_STATE_RINGING)
10640                      break; /* Got ring */
10641                }
10642 
10643                /* We must have a ring by now, so, if configured, lets try to listen for
10644                 * distinctive ringing */
10645                if (p->usedistinctiveringdetection) {
10646                   len = 0;
10647                   distMatches = 0;
10648                   /* Clear the current ring data array so we don't have old data in it. */
10649                   for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10650                      curRingData[receivedRingT] = 0;
10651                   receivedRingT = 0;
10652                   counter = 0;
10653                   counter1 = 0;
10654                   /* Check to see if context is what it should be, if not set to be. */
10655                   if (strcmp(p->context,p->defcontext) != 0) {
10656                      ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10657                      ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10658                   }
10659 
10660                   for (;;) {
10661                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10662                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10663                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10664                         callerid_free(cs);
10665                         ast_hangup(chan);
10666                         goto quit;
10667                      }
10668                      if (i & DAHDI_IOMUX_SIGEVENT) {
10669                         res = dahdi_get_event(p->subs[idx].dfd);
10670                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10671                         if (res == DAHDI_EVENT_NOALARM) {
10672                            p->inalarm = 0;
10673                         }
10674                         res = 0;
10675                         /* Let us detect distinctive ring */
10676 
10677                         curRingData[receivedRingT] = p->ringt;
10678 
10679                         if (p->ringt < p->ringt_base/2)
10680                            break;
10681                         /* Increment the ringT counter so we can match it against
10682                            values in chan_dahdi.conf for distinctive ring */
10683                         if (++receivedRingT == ARRAY_LEN(curRingData))
10684                            break;
10685                      } else if (i & DAHDI_IOMUX_READ) {
10686                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10687                         if (res < 0) {
10688                            if (errno != ELAST) {
10689                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10690                               callerid_free(cs);
10691                               ast_hangup(chan);
10692                               goto quit;
10693                            }
10694                            break;
10695                         }
10696                         if (p->ringt > 0) {
10697                            if (!(--p->ringt)) {
10698                               res = -1;
10699                               break;
10700                            }
10701                         }
10702                      }
10703                   }
10704                      /* this only shows up if you have n of the dring patterns filled in */
10705                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10706                   for (counter = 0; counter < 3; counter++) {
10707                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10708                      channel */
10709                      distMatches = 0;
10710                      for (counter1 = 0; counter1 < 3; counter1++) {
10711                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10712                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10713                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10714                            curRingData[counter1]);
10715                            distMatches++;
10716                         } else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10717                               curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10718                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10719                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10720                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10721                            distMatches++;
10722                         }
10723                      }
10724 
10725                      if (distMatches == 3) {
10726                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10727                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10728                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10729                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10730                         break;
10731                      }
10732                   }
10733                }
10734                /* Restore linear mode (if appropriate) for Caller*ID processing */
10735                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10736 #if 1
10737                restore_gains(p);
10738 #endif
10739             } else
10740                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10741          } else {
10742             ast_log(LOG_WARNING, "Channel %s in prering "
10743                "state, but I have nothing to do. "
10744                "Terminating simple switch, should be "
10745                "restarted by the actual ring.\n",
10746                chan->name);
10747             ast_hangup(chan);
10748             goto quit;
10749          }
10750       } else if (p->use_callerid && p->cid_start == CID_START_RING) {
10751          if (p->cid_signalling == CID_SIG_DTMF) {
10752             int k = 0;
10753             cs = NULL;
10754             dahdi_setlinear(p->subs[idx].dfd, 0);
10755             res = 2000;
10756             for (;;) {
10757                struct ast_frame *f;
10758                res = ast_waitfor(chan, res);
10759                if (res <= 0) {
10760                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10761                      "Exiting simple switch\n");
10762                   ast_hangup(chan);
10763                   goto quit;
10764                }
10765                f = ast_read(chan);
10766                if (!f) {
10767                   /* Hangup received waiting for DTMFCID. Exiting simple switch. */
10768                   ast_hangup(chan);
10769                   goto quit;
10770                }
10771                if (f->frametype == AST_FRAME_DTMF) {
10772                   dtmfbuf[k++] = f->subclass.integer;
10773                   ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass.integer);
10774                   res = 2000;
10775                }
10776                ast_frfree(f);
10777 
10778                if (p->ringt_base == p->ringt)
10779                   break;
10780             }
10781             dtmfbuf[k] = '\0';
10782             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10783             /* Got cid and ring. */
10784             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10785             ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
10786                dtmfcid, flags);
10787             /* If first byte is NULL, we have no cid */
10788             if (!ast_strlen_zero(dtmfcid))
10789                number = dtmfcid;
10790             else
10791                number = NULL;
10792             /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10793          } else {
10794             /* FSK Bell202 callerID */
10795             cs = callerid_new(p->cid_signalling);
10796             if (cs) {
10797 #if 1
10798                bump_gains(p);
10799 #endif
10800                samples = 0;
10801                len = 0;
10802                distMatches = 0;
10803                /* Clear the current ring data array so we don't have old data in it. */
10804                for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10805                   curRingData[receivedRingT] = 0;
10806                receivedRingT = 0;
10807                counter = 0;
10808                counter1 = 0;
10809                /* Check to see if context is what it should be, if not set to be. */
10810                if (strcmp(p->context,p->defcontext) != 0) {
10811                   ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10812                   ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10813                }
10814 
10815                /* Take out of linear mode for Caller*ID processing */
10816                dahdi_setlinear(p->subs[idx].dfd, 0);
10817                for (;;) {
10818                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10819                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10820                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10821                      callerid_free(cs);
10822                      ast_hangup(chan);
10823                      goto quit;
10824                   }
10825                   if (i & DAHDI_IOMUX_SIGEVENT) {
10826                      res = dahdi_get_event(p->subs[idx].dfd);
10827                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10828                      if (res == DAHDI_EVENT_NOALARM) {
10829                         p->inalarm = 0;
10830                      }
10831                      /* If we get a PR event, they hung up while processing calerid */
10832                      if ( res == DAHDI_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
10833                         ast_log(LOG_DEBUG, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
10834                         p->polarity = POLARITY_IDLE;
10835                         callerid_free(cs);
10836                         ast_hangup(chan);
10837                         goto quit;
10838                      }
10839                      res = 0;
10840                      /* Let us detect callerid when the telco uses distinctive ring */
10841 
10842                      curRingData[receivedRingT] = p->ringt;
10843 
10844                      if (p->ringt < p->ringt_base/2)
10845                         break;
10846                      /* Increment the ringT counter so we can match it against
10847                         values in chan_dahdi.conf for distinctive ring */
10848                      if (++receivedRingT == ARRAY_LEN(curRingData))
10849                         break;
10850                   } else if (i & DAHDI_IOMUX_READ) {
10851                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10852                      if (res < 0) {
10853                         if (errno != ELAST) {
10854                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10855                            callerid_free(cs);
10856                            ast_hangup(chan);
10857                            goto quit;
10858                         }
10859                         break;
10860                      }
10861                      if (p->ringt > 0) {
10862                         if (!(--p->ringt)) {
10863                            res = -1;
10864                            break;
10865                         }
10866                      }
10867                      samples += res;
10868                      res = callerid_feed(cs, buf, res, AST_LAW(p));
10869                      if (res < 0) {
10870                         /*
10871                          * The previous diagnostic message output likely
10872                          * explains why it failed.
10873                          */
10874                         ast_log(LOG_WARNING,
10875                            "Failed to decode CallerID on channel '%s'\n",
10876                            chan->name);
10877                         break;
10878                      } else if (res)
10879                         break;
10880                      else if (samples > (8000 * 10))
10881                         break;
10882                   }
10883                }
10884                if (res == 1) {
10885                   callerid_get(cs, &name, &number, &flags);
10886                   ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10887                }
10888                if (distinctiveringaftercid == 1) {
10889                   /* Clear the current ring data array so we don't have old data in it. */
10890                   for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
10891                      curRingData[receivedRingT] = 0;
10892                   }
10893                   receivedRingT = 0;
10894                   ast_verb(3, "Detecting post-CID distinctive ring\n");
10895                   for (;;) {
10896                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10897                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10898                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10899                         callerid_free(cs);
10900                         ast_hangup(chan);
10901                         goto quit;
10902                      }
10903                      if (i & DAHDI_IOMUX_SIGEVENT) {
10904                         res = dahdi_get_event(p->subs[idx].dfd);
10905                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10906                         if (res == DAHDI_EVENT_NOALARM) {
10907                            p->inalarm = 0;
10908                         }
10909                         res = 0;
10910                         /* Let us detect callerid when the telco uses distinctive ring */
10911 
10912                         curRingData[receivedRingT] = p->ringt;
10913 
10914                         if (p->ringt < p->ringt_base/2)
10915                            break;
10916                         /* Increment the ringT counter so we can match it against
10917                            values in chan_dahdi.conf for distinctive ring */
10918                         if (++receivedRingT == ARRAY_LEN(curRingData))
10919                            break;
10920                      } else if (i & DAHDI_IOMUX_READ) {
10921                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10922                         if (res < 0) {
10923                            if (errno != ELAST) {
10924                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10925                               callerid_free(cs);
10926                               ast_hangup(chan);
10927                               goto quit;
10928                            }
10929                            break;
10930                         }
10931                         if (p->ringt > 0) {
10932                            if (!(--p->ringt)) {
10933                               res = -1;
10934                               break;
10935                            }
10936                         }
10937                      }
10938                   }
10939                }
10940                if (p->usedistinctiveringdetection) {
10941                   /* this only shows up if you have n of the dring patterns filled in */
10942                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10943 
10944                   for (counter = 0; counter < 3; counter++) {
10945                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10946                      channel */
10947                      /* this only shows up if you have n of the dring patterns filled in */
10948                      ast_verb(3, "Checking %d,%d,%d\n",
10949                            p->drings.ringnum[counter].ring[0],
10950                            p->drings.ringnum[counter].ring[1],
10951                            p->drings.ringnum[counter].ring[2]);
10952                      distMatches = 0;
10953                      for (counter1 = 0; counter1 < 3; counter1++) {
10954                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10955                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10956                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10957                            curRingData[counter1]);
10958                            distMatches++;
10959                         }
10960                         else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10961                            curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10962                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10963                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10964                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10965                            distMatches++;
10966                         }
10967                      }
10968                      if (distMatches == 3) {
10969                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10970                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10971                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10972                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10973                         break;
10974                      }
10975                   }
10976                }
10977                /* Restore linear mode (if appropriate) for Caller*ID processing */
10978                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10979 #if 1
10980                restore_gains(p);
10981 #endif
10982                if (res < 0) {
10983                   ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
10984                }
10985             } else
10986                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10987          }
10988       } else
10989          cs = NULL;
10990 
10991       if (number)
10992          ast_shrink_phone_number(number);
10993       ast_set_callerid(chan, number, name, number);
10994 
10995       if (smdi_msg)
10996          ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
10997 
10998       if (cs)
10999          callerid_free(cs);
11000 
11001       my_handle_notify_message(chan, p, flags, -1);
11002 
11003       ast_setstate(chan, AST_STATE_RING);
11004       chan->rings = 1;
11005       p->ringt = p->ringt_base;
11006       res = ast_pbx_run(chan);
11007       if (res) {
11008          ast_hangup(chan);
11009          ast_log(LOG_WARNING, "PBX exited non-zero\n");
11010       }
11011       goto quit;
11012    default:
11013       ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
11014       res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
11015       if (res < 0)
11016             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
11017    }
11018    res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
11019    if (res < 0)
11020          ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
11021    ast_hangup(chan);
11022 quit:
11023    ast_mutex_lock(&ss_thread_lock);
11024    ss_thread_count--;
11025    ast_cond_signal(&ss_thread_complete);
11026    ast_mutex_unlock(&ss_thread_lock);
11027    return NULL;
11028 }
11029 
11030 struct mwi_thread_data {
11031    struct dahdi_pvt *pvt;
11032    unsigned char buf[READ_SIZE];
11033    size_t len;
11034 };
11035 
11036 static int calc_energy(const unsigned char *buf, int len, format_t law)
11037 {
11038    int x;
11039    int sum = 0;
11040 
11041    if (!len)
11042       return 0;
11043 
11044    for (x = 0; x < len; x++)
11045       sum += abs(law == AST_FORMAT_ULAW ? AST_MULAW(buf[x]) : AST_ALAW(buf[x]));
11046 
11047    return sum / len;
11048 }
11049 
11050 static void *mwi_thread(void *data)
11051 {
11052    struct mwi_thread_data *mtd = data;
11053    struct callerid_state *cs;
11054    pthread_t threadid;
11055    int samples = 0;
11056    char *name, *number;
11057    int flags;
11058    int i, res;
11059    unsigned int spill_done = 0;
11060    int spill_result = -1;
11061 
11062    if (!(cs = callerid_new(mtd->pvt->cid_signalling))) {
11063       goto quit_no_clean;
11064    }
11065 
11066    callerid_feed(cs, mtd->buf, mtd->len, AST_LAW(mtd->pvt));
11067 
11068    bump_gains(mtd->pvt);
11069 
11070    for (;;) {
11071       i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
11072       if ((res = ioctl(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_IOMUX, &i))) {
11073          ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
11074          goto quit;
11075       }
11076 
11077       if (i & DAHDI_IOMUX_SIGEVENT) {
11078          struct ast_channel *chan;
11079 
11080          /* If we get an event, screen out events that we do not act on.
11081           * Otherwise, cancel and go to the simple switch to let it deal with it.
11082           */
11083          res = dahdi_get_event(mtd->pvt->subs[SUB_REAL].dfd);
11084 
11085          switch (res) {
11086          case DAHDI_EVENT_NEONMWI_ACTIVE:
11087          case DAHDI_EVENT_NEONMWI_INACTIVE:
11088          case DAHDI_EVENT_NONE:
11089          case DAHDI_EVENT_BITSCHANGED:
11090             break;
11091          case DAHDI_EVENT_NOALARM:
11092             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11093                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
11094 
11095                analog_p->inalarm = 0;
11096             }
11097             mtd->pvt->inalarm = 0;
11098             handle_clear_alarms(mtd->pvt);
11099             break;
11100          case DAHDI_EVENT_ALARM:
11101             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11102                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
11103 
11104                analog_p->inalarm = 1;
11105             }
11106             mtd->pvt->inalarm = 1;
11107             res = get_alarms(mtd->pvt);
11108             handle_alarms(mtd->pvt, res);
11109             break; /* What to do on channel alarm ???? -- fall thru intentionally?? */
11110          default:
11111             ast_log(LOG_NOTICE, "Got event %d (%s)...  Passing along to analog_ss_thread\n", res, event2str(res));
11112             callerid_free(cs);
11113 
11114             restore_gains(mtd->pvt);
11115             mtd->pvt->ringt = mtd->pvt->ringt_base;
11116 
11117             if ((chan = dahdi_new(mtd->pvt, AST_STATE_RING, 0, SUB_REAL, 0, NULL))) {
11118                int result;
11119 
11120                if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11121                   result = analog_ss_thread_start(mtd->pvt->sig_pvt, chan);
11122                } else {
11123                   result = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11124                }
11125                if (result) {
11126                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", mtd->pvt->channel);
11127                   res = tone_zone_play_tone(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11128                   if (res < 0)
11129                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", mtd->pvt->channel);
11130                   ast_hangup(chan);
11131                }
11132             } else {
11133                ast_log(LOG_WARNING, "Could not create channel to handle call\n");
11134             }
11135             goto quit_no_clean;
11136          }
11137       } else if (i & DAHDI_IOMUX_READ) {
11138          if ((res = read(mtd->pvt->subs[SUB_REAL].dfd, mtd->buf, sizeof(mtd->buf))) < 0) {
11139             if (errno != ELAST) {
11140                ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
11141                goto quit;
11142             }
11143             break;
11144          }
11145          samples += res;
11146          if (!spill_done) {
11147             if ((spill_result = callerid_feed(cs, mtd->buf, res, AST_LAW(mtd->pvt))) < 0) {
11148                /*
11149                 * The previous diagnostic message output likely
11150                 * explains why it failed.
11151                 */
11152                ast_log(LOG_WARNING, "Failed to decode CallerID\n");
11153                break;
11154             } else if (spill_result) {
11155                spill_done = 1;
11156             }
11157          } else {
11158             /* keep reading data until the energy level drops below the threshold
11159                so we don't get another 'trigger' on the remaining carrier signal
11160             */
11161             if (calc_energy(mtd->buf, res, AST_LAW(mtd->pvt)) <= mwilevel)
11162                break;
11163          }
11164          if (samples > (8000 * 4)) /*Termination case - time to give up*/
11165             break;
11166       }
11167    }
11168 
11169    if (spill_result == 1) {
11170       callerid_get(cs, &name, &number, &flags);
11171       if (flags & CID_MSGWAITING) {
11172          ast_log(LOG_NOTICE, "mwi: Have Messages on channel %d\n", mtd->pvt->channel);
11173          notify_message(mtd->pvt->mailbox, 1);
11174       } else if (flags & CID_NOMSGWAITING) {
11175          ast_log(LOG_NOTICE, "mwi: No Messages on channel %d\n", mtd->pvt->channel);
11176          notify_message(mtd->pvt->mailbox, 0);
11177       } else {
11178          ast_log(LOG_NOTICE, "mwi: Status unknown on channel %d\n", mtd->pvt->channel);
11179       }
11180    }
11181 
11182 
11183 quit:
11184    callerid_free(cs);
11185 
11186    restore_gains(mtd->pvt);
11187 
11188 quit_no_clean:
11189    mtd->pvt->mwimonitoractive = 0;
11190    ast_free(mtd);
11191 
11192    return NULL;
11193 }
11194 
11195 /*
11196 * The following three functions (mwi_send_init, mwi_send_process_buffer,
11197 * mwi_send_process_event) work with the do_monitor thread to generate mwi spills
11198 * that are sent out via FXS port on voicemail state change.  The execution of
11199 * the mwi send is state driven and can either generate a ring pulse prior to
11200 * sending the fsk spill or simply send an fsk spill.
11201 */
11202 static int mwi_send_init(struct dahdi_pvt * pvt)
11203 {
11204    int x;
11205 
11206 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11207    /* Determine how this spill is to be sent */
11208    if (pvt->mwisend_rpas) {
11209       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
11210       pvt->mwisendactive = 1;
11211    } else if (pvt->mwisend_fsk) {
11212       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11213       pvt->mwisendactive = 1;
11214    } else {
11215       pvt->mwisendactive = 0;
11216       return 0;
11217    }
11218 #else
11219    if (mwisend_rpas) {
11220       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
11221    } else {
11222       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11223    }
11224    pvt->mwisendactive = 1;
11225 #endif
11226 
11227    if (pvt->cidspill) {
11228       ast_log(LOG_WARNING, "cidspill already exists when trying to send FSK MWI\n");
11229       ast_free(pvt->cidspill);
11230       pvt->cidspill = NULL;
11231       pvt->cidpos = 0;
11232       pvt->cidlen = 0;
11233    }
11234    pvt->cidspill = ast_calloc(1, MAX_CALLERID_SIZE);
11235    if (!pvt->cidspill) {
11236       pvt->mwisendactive = 0;
11237       return -1;
11238    }
11239    x = DAHDI_FLUSH_BOTH;
11240    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
11241    x = 3000;
11242    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_ONHOOKTRANSFER, &x);
11243 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11244    if (pvt->mwisend_fsk) {
11245 #endif
11246       pvt->cidlen = ast_callerid_vmwi_generate(pvt->cidspill, has_voicemail(pvt), CID_MWI_TYPE_MDMF_FULL,
11247                       AST_LAW(pvt), pvt->cid_name, pvt->cid_num, 0);
11248       pvt->cidpos = 0;
11249 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11250    }
11251 #endif
11252    return 0;
11253 }
11254 
11255 static int mwi_send_process_buffer(struct dahdi_pvt * pvt, int num_read)
11256 {
11257    struct timeval    now;
11258    int         res;
11259 
11260    /* sanity check to catch if this had been interrupted previously
11261    *  i.e. state says there is more to do but there is no spill allocated
11262    */
11263    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current && !pvt->cidspill) {
11264       pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11265    } else if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
11266       /* Normal processing -- Perform mwi send action */
11267       switch ( pvt->mwisend_data.mwisend_current) {
11268       case MWI_SEND_SA:
11269          /* Send the Ring Pulse Signal Alert */
11270          res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &AS_RP_cadence);
11271          if (res) {
11272             ast_log(LOG_WARNING, "Unable to set RP-AS ring cadence: %s\n", strerror(errno));
11273             goto quit;
11274          }
11275          res = dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RING);
11276          pvt->mwisend_data.mwisend_current = MWI_SEND_SA_WAIT;
11277          break;
11278       case MWI_SEND_SA_WAIT:  /* do nothing until I get RINGEROFF event */
11279          break;
11280       case MWI_SEND_PAUSE:  /* Wait between alert and spill - min of 500 mS*/
11281 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11282          if (pvt->mwisend_fsk) {
11283 #endif
11284             gettimeofday(&now, NULL);
11285             if ((int)(now.tv_sec - pvt->mwisend_data.pause.tv_sec) * 1000000 + (int)now.tv_usec - (int)pvt->mwisend_data.pause.tv_usec > 500000) {
11286                pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11287             }
11288 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11289          } else { /* support for mwisendtype=nofsk */
11290             pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
11291          }
11292 #endif
11293          break;
11294       case MWI_SEND_SPILL:
11295          /* We read some number of bytes.  Write an equal amount of data */
11296          if(0 < num_read) {
11297             if (num_read > pvt->cidlen - pvt->cidpos)
11298                num_read = pvt->cidlen - pvt->cidpos;
11299             res = write(pvt->subs[SUB_REAL].dfd, pvt->cidspill + pvt->cidpos, num_read);
11300             if (res > 0) {
11301                pvt->cidpos += res;
11302                if (pvt->cidpos >= pvt->cidlen) {
11303                   pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
11304                }
11305             } else {
11306                ast_log(LOG_WARNING, "MWI FSK Send Write failed: %s\n", strerror(errno));
11307                goto quit;
11308             }
11309          }
11310          break;
11311       case MWI_SEND_CLEANUP:
11312          /* For now, do nothing */
11313          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11314          break;
11315       default:
11316          /* Should not get here, punt*/
11317          goto quit;
11318       }
11319    }
11320 
11321    if (MWI_SEND_DONE == pvt->mwisend_data.mwisend_current) {
11322       if (pvt->cidspill) {
11323          ast_free(pvt->cidspill);
11324          pvt->cidspill = NULL;
11325          pvt->cidpos = 0;
11326          pvt->cidlen = 0;
11327       }
11328       pvt->mwisendactive = 0;
11329    }
11330    return 0;
11331 quit:
11332    if (pvt->cidspill) {
11333       ast_free(pvt->cidspill);
11334       pvt->cidspill = NULL;
11335       pvt->cidpos = 0;
11336       pvt->cidlen = 0;
11337    }
11338    pvt->mwisendactive = 0;
11339    return -1;
11340 }
11341 
11342 static int mwi_send_process_event(struct dahdi_pvt * pvt, int event)
11343 {
11344    int handled = 0;
11345 
11346    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
11347       switch (event) {
11348       case DAHDI_EVENT_RINGEROFF:
11349          if(pvt->mwisend_data.mwisend_current == MWI_SEND_SA_WAIT) {
11350             handled = 1;
11351 
11352             if (dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RINGOFF) ) {
11353                ast_log(LOG_WARNING, "Unable to finish RP-AS: %s mwi send aborted\n", strerror(errno));
11354                ast_free(pvt->cidspill);
11355                pvt->cidspill = NULL;
11356                pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11357                pvt->mwisendactive = 0;
11358             } else {
11359                pvt->mwisend_data.mwisend_current = MWI_SEND_PAUSE;
11360                gettimeofday(&pvt->mwisend_data.pause, NULL);
11361             }
11362          }
11363          break;
11364       /* Going off hook, I need to punt this spill */
11365       case DAHDI_EVENT_RINGOFFHOOK:
11366          if (pvt->cidspill) {
11367             ast_free(pvt->cidspill);
11368             pvt->cidspill = NULL;
11369             pvt->cidpos = 0;
11370             pvt->cidlen = 0;
11371          }
11372          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11373          pvt->mwisendactive = 0;
11374          break;
11375       case DAHDI_EVENT_RINGERON:
11376       case DAHDI_EVENT_HOOKCOMPLETE:
11377          break;
11378       default:
11379          break;
11380       }
11381    }
11382    return handled;
11383 }
11384 
11385 /* destroy a DAHDI channel, identified by its number */
11386 static int dahdi_destroy_channel_bynum(int channel)
11387 {
11388    struct dahdi_pvt *cur;
11389 
11390    ast_mutex_lock(&iflock);
11391    for (cur = iflist; cur; cur = cur->next) {
11392       if (cur->channel == channel) {
11393          int x = DAHDI_FLASH;
11394 
11395          /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
11396          ioctl(cur->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
11397 
11398          destroy_channel(cur, 1);
11399          ast_mutex_unlock(&iflock);
11400          ast_module_unref(ast_module_info->self);
11401          return RESULT_SUCCESS;
11402       }
11403    }
11404    ast_mutex_unlock(&iflock);
11405    return RESULT_FAILURE;
11406 }
11407 
11408 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
11409 {
11410    int res;
11411    pthread_t threadid;
11412    struct ast_channel *chan;
11413 
11414    /* Handle an event on a given channel for the monitor thread. */
11415 
11416    switch (event) {
11417    case DAHDI_EVENT_NONE:
11418    case DAHDI_EVENT_BITSCHANGED:
11419       break;
11420    case DAHDI_EVENT_WINKFLASH:
11421    case DAHDI_EVENT_RINGOFFHOOK:
11422       if (i->inalarm) break;
11423       if (i->radio) break;
11424       /* Got a ring/answer.  What kind of channel are we? */
11425       switch (i->sig) {
11426       case SIG_FXOLS:
11427       case SIG_FXOGS:
11428       case SIG_FXOKS:
11429          res = dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11430          if (res && (errno == EBUSY))
11431             break;
11432 
11433          /* Cancel VMWI spill */
11434          ast_free(i->cidspill);
11435          i->cidspill = NULL;
11436          restore_conference(i);
11437 
11438          if (i->immediate) {
11439             dahdi_enable_ec(i);
11440             /* The channel is immediately up.  Start right away */
11441             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
11442             chan = dahdi_new(i, AST_STATE_RING, 1, SUB_REAL, 0, NULL);
11443             if (!chan) {
11444                ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
11445                res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11446                if (res < 0)
11447                   ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11448             }
11449          } else {
11450             /* Check for callerid, digits, etc */
11451             chan = dahdi_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, NULL);
11452             if (chan) {
11453                if (has_voicemail(i))
11454                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
11455                else
11456                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
11457                if (res < 0)
11458                   ast_log(LOG_WARNING, "Unable to play dialtone on channel %d, do you have defaultzone and loadzone defined?\n", i->channel);
11459                if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11460                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11461                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11462                   if (res < 0)
11463                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11464                   ast_hangup(chan);
11465                }
11466             } else
11467                ast_log(LOG_WARNING, "Unable to create channel\n");
11468          }
11469          break;
11470       case SIG_FXSLS:
11471       case SIG_FXSGS:
11472       case SIG_FXSKS:
11473             i->ringt = i->ringt_base;
11474             /* Fall through */
11475       case SIG_EMWINK:
11476       case SIG_FEATD:
11477       case SIG_FEATDMF:
11478       case SIG_FEATDMF_TA:
11479       case SIG_E911:
11480       case SIG_FGC_CAMA:
11481       case SIG_FGC_CAMAMF:
11482       case SIG_FEATB:
11483       case SIG_EM:
11484       case SIG_EM_E1:
11485       case SIG_SFWINK:
11486       case SIG_SF_FEATD:
11487       case SIG_SF_FEATDMF:
11488       case SIG_SF_FEATB:
11489       case SIG_SF:
11490          /* Check for callerid, digits, etc */
11491          if (i->cid_start == CID_START_POLARITY_IN) {
11492             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11493          } else {
11494             chan = dahdi_new(i, AST_STATE_RING, 0, SUB_REAL, 0, NULL);
11495          }
11496 
11497          if (!chan) {
11498             ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11499          } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11500             ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11501             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11502             if (res < 0) {
11503                ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11504             }
11505             ast_hangup(chan);
11506          }
11507          break;
11508       default:
11509          ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11510          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11511          if (res < 0)
11512             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11513          return NULL;
11514       }
11515       break;
11516    case DAHDI_EVENT_NOALARM:
11517       switch (i->sig) {
11518 #if defined(HAVE_PRI)
11519       case SIG_PRI_LIB_HANDLE_CASES:
11520          ast_mutex_lock(&i->lock);
11521          sig_pri_chan_alarm_notify(i->sig_pvt, 1);
11522          ast_mutex_unlock(&i->lock);
11523          break;
11524 #endif   /* defined(HAVE_PRI) */
11525 #if defined(HAVE_SS7)
11526       case SIG_SS7:
11527          sig_ss7_set_alarm(i->sig_pvt, 0);
11528          break;
11529 #endif   /* defined(HAVE_SS7) */
11530       default:
11531          i->inalarm = 0;
11532          break;
11533       }
11534       handle_clear_alarms(i);
11535       break;
11536    case DAHDI_EVENT_ALARM:
11537       switch (i->sig) {
11538 #if defined(HAVE_PRI)
11539       case SIG_PRI_LIB_HANDLE_CASES:
11540          ast_mutex_lock(&i->lock);
11541          sig_pri_chan_alarm_notify(i->sig_pvt, 0);
11542          ast_mutex_unlock(&i->lock);
11543          break;
11544 #endif   /* defined(HAVE_PRI) */
11545 #if defined(HAVE_SS7)
11546       case SIG_SS7:
11547          sig_ss7_set_alarm(i->sig_pvt, 1);
11548          break;
11549 #endif   /* defined(HAVE_SS7) */
11550       default:
11551          i->inalarm = 1;
11552          break;
11553       }
11554       res = get_alarms(i);
11555       handle_alarms(i, res);
11556       /* fall thru intentionally */
11557    case DAHDI_EVENT_ONHOOK:
11558       if (i->radio)
11559          break;
11560       /* Back on hook.  Hang up. */
11561       switch (i->sig) {
11562       case SIG_FXOLS:
11563       case SIG_FXOGS:
11564       case SIG_FEATD:
11565       case SIG_FEATDMF:
11566       case SIG_FEATDMF_TA:
11567       case SIG_E911:
11568       case SIG_FGC_CAMA:
11569       case SIG_FGC_CAMAMF:
11570       case SIG_FEATB:
11571       case SIG_EM:
11572       case SIG_EM_E1:
11573       case SIG_EMWINK:
11574       case SIG_SF_FEATD:
11575       case SIG_SF_FEATDMF:
11576       case SIG_SF_FEATB:
11577       case SIG_SF:
11578       case SIG_SFWINK:
11579       case SIG_FXSLS:
11580       case SIG_FXSGS:
11581       case SIG_FXSKS:
11582       case SIG_FXOKS:
11583          dahdi_disable_ec(i);
11584          /* Diddle the battery for the zhone */
11585 #ifdef ZHONE_HACK
11586          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11587          usleep(1);
11588 #endif
11589          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11590          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
11591          break;
11592       case SIG_SS7:
11593       case SIG_PRI_LIB_HANDLE_CASES:
11594          dahdi_disable_ec(i);
11595          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11596          break;
11597       default:
11598          ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11599          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11600          return NULL;
11601       }
11602       break;
11603    case DAHDI_EVENT_POLARITY:
11604       switch (i->sig) {
11605       case SIG_FXSLS:
11606       case SIG_FXSKS:
11607       case SIG_FXSGS:
11608          /* We have already got a PR before the channel was
11609             created, but it wasn't handled. We need polarity
11610             to be REV for remote hangup detection to work.
11611             At least in Spain */
11612          if (i->hanguponpolarityswitch)
11613             i->polarity = POLARITY_REV;
11614          if (i->cid_start == CID_START_POLARITY || i->cid_start == CID_START_POLARITY_IN) {
11615             i->polarity = POLARITY_REV;
11616             ast_verb(2, "Starting post polarity "
11617                "CID detection on channel %d\n",
11618                i->channel);
11619             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11620             if (!chan) {
11621                ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11622             } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11623                ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11624             }
11625          }
11626          break;
11627       default:
11628          ast_log(LOG_WARNING, "handle_init_event detected "
11629             "polarity reversal on non-FXO (SIG_FXS) "
11630             "interface %d\n", i->channel);
11631       }
11632       break;
11633    case DAHDI_EVENT_REMOVED: /* destroy channel, will actually do so in do_monitor */
11634       ast_log(LOG_NOTICE,
11635             "Got DAHDI_EVENT_REMOVED. Destroying channel %d\n",
11636             i->channel);
11637       return i;
11638    case DAHDI_EVENT_NEONMWI_ACTIVE:
11639       if (i->mwimonitor_neon) {
11640          notify_message(i->mailbox, 1);
11641          ast_log(LOG_NOTICE, "NEON MWI set for channel %d, mailbox %s \n", i->channel, i->mailbox);
11642       }
11643       break;
11644    case DAHDI_EVENT_NEONMWI_INACTIVE:
11645       if (i->mwimonitor_neon) {
11646          notify_message(i->mailbox, 0);
11647          ast_log(LOG_NOTICE, "NEON MWI cleared for channel %d, mailbox %s\n", i->channel, i->mailbox);
11648       }
11649       break;
11650    }
11651    return NULL;
11652 }
11653 
11654 static void *do_monitor(void *data)
11655 {
11656    int count, res, res2, spoint, pollres=0;
11657    struct dahdi_pvt *i;
11658    struct dahdi_pvt *last = NULL;
11659    struct dahdi_pvt *doomed;
11660    time_t thispass = 0, lastpass = 0;
11661    int found;
11662    char buf[1024];
11663    struct pollfd *pfds=NULL;
11664    int lastalloc = -1;
11665    /* This thread monitors all the frame relay interfaces which are not yet in use
11666       (and thus do not have a separate thread) indefinitely */
11667    /* From here on out, we die whenever asked */
11668 #if 0
11669    if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
11670       ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
11671       return NULL;
11672    }
11673    ast_debug(1, "Monitor starting...\n");
11674 #endif
11675    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11676 
11677    for (;;) {
11678       /* Lock the interface list */
11679       ast_mutex_lock(&iflock);
11680       if (!pfds || (lastalloc != ifcount)) {
11681          if (pfds) {
11682             ast_free(pfds);
11683             pfds = NULL;
11684          }
11685          if (ifcount) {
11686             if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
11687                ast_mutex_unlock(&iflock);
11688                return NULL;
11689             }
11690          }
11691          lastalloc = ifcount;
11692       }
11693       /* Build the stuff we're going to poll on, that is the socket of every
11694          dahdi_pvt that does not have an associated owner channel */
11695       count = 0;
11696       for (i = iflist; i; i = i->next) {
11697          ast_mutex_lock(&i->lock);
11698          if (pfds && (i->subs[SUB_REAL].dfd > -1) && i->sig && (!i->radio) && !(i->sig & SIG_MFCR2)) {
11699             if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11700                struct analog_pvt *p = i->sig_pvt;
11701 
11702                if (!p) {
11703                   ast_log(LOG_ERROR, "No sig_pvt?\n");
11704                } else if (!p->owner && !p->subs[SUB_REAL].owner) {
11705                   /* This needs to be watched, as it lacks an owner */
11706                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11707                   pfds[count].events = POLLPRI;
11708                   pfds[count].revents = 0;
11709                   /* Message waiting or r2 channels also get watched for reading */
11710                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk || 
11711                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11712                      pfds[count].events |= POLLIN;
11713                   }
11714                   count++;
11715                }
11716             } else {
11717                if (!i->owner && !i->subs[SUB_REAL].owner && !i->mwimonitoractive ) {
11718                   /* This needs to be watched, as it lacks an owner */
11719                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11720                   pfds[count].events = POLLPRI;
11721                   pfds[count].revents = 0;
11722                   /* If we are monitoring for VMWI or sending CID, we need to
11723                      read from the channel as well */
11724                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk ||
11725                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11726                      pfds[count].events |= POLLIN;
11727                   }
11728                   count++;
11729                }
11730             }
11731          }
11732          ast_mutex_unlock(&i->lock);
11733       }
11734       /* Okay, now that we know what to do, release the interface lock */
11735       ast_mutex_unlock(&iflock);
11736 
11737       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
11738       pthread_testcancel();
11739       /* Wait at least a second for something to happen */
11740       res = poll(pfds, count, 1000);
11741       pthread_testcancel();
11742       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11743 
11744       /* Okay, poll has finished.  Let's see what happened.  */
11745       if (res < 0) {
11746          if ((errno != EAGAIN) && (errno != EINTR))
11747             ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
11748          continue;
11749       }
11750       /* Alright, lock the interface list again, and let's look and see what has
11751          happened */
11752       ast_mutex_lock(&iflock);
11753       found = 0;
11754       spoint = 0;
11755       lastpass = thispass;
11756       thispass = time(NULL);
11757       doomed = NULL;
11758       for (i = iflist;; i = i->next) {
11759          if (doomed) {
11760             int res;
11761             res = dahdi_destroy_channel_bynum(doomed->channel);
11762             if (res != RESULT_SUCCESS) {
11763                ast_log(LOG_WARNING, "Couldn't find channel to destroy, hopefully another destroy operation just happened.\n");
11764             }
11765             doomed = NULL;
11766          }
11767          if (!i) {
11768             break;
11769          }
11770 
11771          if (thispass != lastpass) {
11772             if (!found && ((i == last) || ((i == iflist) && !last))) {
11773                last = i;
11774                if (last) {
11775                   struct analog_pvt *analog_p = last->sig_pvt;
11776                   /* Only allow MWI to be initiated on a quiescent fxs port */
11777                   if (analog_p
11778                      && !last->mwisendactive
11779                      && (last->sig & __DAHDI_SIG_FXO)
11780                      && !analog_p->fxsoffhookstate
11781                      && !last->owner
11782                      && !ast_strlen_zero(last->mailbox)
11783                      && (thispass - analog_p->onhooktime > 3)) {
11784                      res = has_voicemail(last);
11785                      if (analog_p->msgstate != res) {
11786                         /* Set driver resources for signalling VMWI */
11787                         res2 = ioctl(last->subs[SUB_REAL].dfd, DAHDI_VMWI, &res);
11788                         if (res2) {
11789                            /* TODO: This message will ALWAYS be generated on some cards; any way to restrict it to those cards where it is interesting? */
11790                            ast_debug(3, "Unable to control message waiting led on channel %d: %s\n", last->channel, strerror(errno));
11791                         }
11792                         /* If enabled for FSK spill then initiate it */
11793                         if (mwi_send_init(last)) {
11794                            ast_log(LOG_WARNING, "Unable to initiate mwi send sequence on channel %d\n", last->channel);
11795                         }
11796                         analog_p->msgstate = res;
11797                         found ++;
11798                      }
11799                   }
11800                   last = last->next;
11801                }
11802             }
11803          }
11804          if ((i->subs[SUB_REAL].dfd > -1) && i->sig) {
11805             if (i->radio && !i->owner)
11806             {
11807                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11808                if (res)
11809                {
11810                   ast_debug(1, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
11811                   /* Don't hold iflock while handling init events */
11812                   ast_mutex_unlock(&iflock);
11813                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11814                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11815                   else
11816                      doomed = handle_init_event(i, res);
11817                   ast_mutex_lock(&iflock);
11818                }
11819                continue;
11820             }
11821             pollres = ast_fdisset(pfds, i->subs[SUB_REAL].dfd, count, &spoint);
11822             if (pollres & POLLIN) {
11823                if (i->owner || i->subs[SUB_REAL].owner) {
11824 #ifdef HAVE_PRI
11825                   if (!i->pri)
11826 #endif
11827                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].dfd);
11828                   continue;
11829                }
11830                if (!i->mwimonitor_fsk && !i->mwisendactive  && i->cid_start != CID_START_DTMF_NOALERT) {
11831                   ast_log(LOG_WARNING, "Whoa....  I'm not looking for MWI or sending MWI but am reading (%d)...\n", i->subs[SUB_REAL].dfd);
11832                   continue;
11833                }
11834                res = read(i->subs[SUB_REAL].dfd, buf, sizeof(buf));
11835                if (res > 0) {
11836                   if (i->mwimonitor_fsk) {
11837                      if (calc_energy((unsigned char *) buf, res, AST_LAW(i)) > mwilevel) {
11838                         pthread_attr_t attr;
11839                         pthread_t threadid;
11840                         struct mwi_thread_data *mtd;
11841 
11842                         pthread_attr_init(&attr);
11843                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
11844 
11845                         ast_log(LOG_DEBUG, "Maybe some MWI on port %d!\n", i->channel);
11846                         if ((mtd = ast_calloc(1, sizeof(*mtd)))) {
11847                            mtd->pvt = i;
11848                            memcpy(mtd->buf, buf, res);
11849                            mtd->len = res;
11850                            i->mwimonitoractive = 1;
11851                            if (ast_pthread_create_background(&threadid, &attr, mwi_thread, mtd)) {
11852                               ast_log(LOG_WARNING, "Unable to start mwi thread on channel %d\n", i->channel);
11853                               i->mwimonitoractive = 0;
11854                               ast_free(mtd);
11855                            }
11856                         }
11857                      }
11858                   /* If configured to check for a DTMF CID spill that comes without alert (e.g no polarity reversal) */
11859                   } else if (i->cid_start == CID_START_DTMF_NOALERT) {
11860                      int energy;
11861                      struct timeval now;
11862                      /* State machine dtmfcid_holdoff_state allows for the line to settle
11863                       * before checking agin for dtmf energy.  Presently waits for 500 mS before checking again 
11864                      */
11865                      if (1 == i->dtmfcid_holdoff_state) {
11866                         gettimeofday(&i->dtmfcid_delay, NULL);
11867                         i->dtmfcid_holdoff_state = 2;
11868                      } else if (2 == i->dtmfcid_holdoff_state) {
11869                         gettimeofday(&now, NULL);
11870                         if ((int)(now.tv_sec - i->dtmfcid_delay.tv_sec) * 1000000 + (int)now.tv_usec - (int)i->dtmfcid_delay.tv_usec > 500000) {
11871                            i->dtmfcid_holdoff_state = 0;
11872                         }
11873                      } else {
11874                         energy = calc_energy((unsigned char *) buf, res, AST_LAW(i));
11875                         if (!i->mwisendactive && energy > dtmfcid_level) {
11876                            pthread_t threadid;
11877                            struct ast_channel *chan;
11878                            ast_mutex_unlock(&iflock);
11879                            if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11880                               /* just in case this event changes or somehow destroys a channel, set doomed here too */
11881                               doomed = analog_handle_init_event(i->sig_pvt, ANALOG_EVENT_DTMFCID);  
11882                               i->dtmfcid_holdoff_state = 1;
11883                            } else {
11884                               chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11885                               if (!chan) {
11886                                  ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11887                               } else {
11888                                  res = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11889                                  if (res) {
11890                                     ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11891                                  } else {
11892                                     i->dtmfcid_holdoff_state = 1;
11893                                  }
11894                               }
11895                            }
11896                            ast_mutex_lock(&iflock);
11897                         }
11898                      }
11899                   }
11900                   if (i->mwisendactive) {
11901                      mwi_send_process_buffer(i, res);
11902                   }
11903                } else {
11904                   ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
11905                }
11906             }
11907             if (pollres & POLLPRI) {
11908                if (i->owner || i->subs[SUB_REAL].owner) {
11909 #ifdef HAVE_PRI
11910                   if (!i->pri)
11911 #endif
11912                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d)...\n", i->subs[SUB_REAL].dfd);
11913                   continue;
11914                }
11915                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11916                ast_debug(1, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
11917                /* Don't hold iflock while handling init events */
11918                ast_mutex_unlock(&iflock);
11919                if (0 == i->mwisendactive || 0 == mwi_send_process_event(i, res)) {
11920                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11921                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11922                   else
11923                      doomed = handle_init_event(i, res);
11924                }
11925                ast_mutex_lock(&iflock);
11926             }
11927          }
11928       }
11929       ast_mutex_unlock(&iflock);
11930    }
11931    /* Never reached */
11932    return NULL;
11933 
11934 }
11935 
11936 static int restart_monitor(void)
11937 {
11938    /* If we're supposed to be stopped -- stay stopped */
11939    if (monitor_thread == AST_PTHREADT_STOP)
11940       return 0;
11941    ast_mutex_lock(&monlock);
11942    if (monitor_thread == pthread_self()) {
11943       ast_mutex_unlock(&monlock);
11944       ast_log(LOG_WARNING, "Cannot kill myself\n");
11945       return -1;
11946    }
11947    if (monitor_thread != AST_PTHREADT_NULL) {
11948       /* Wake up the thread */
11949       pthread_kill(monitor_thread, SIGURG);
11950    } else {
11951       /* Start a new monitor */
11952       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
11953          ast_mutex_unlock(&monlock);
11954          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
11955          return -1;
11956       }
11957    }
11958    ast_mutex_unlock(&monlock);
11959    return 0;
11960 }
11961 
11962 #if defined(HAVE_PRI)
11963 static int pri_resolve_span(int *span, int channel, int offset, struct dahdi_spaninfo *si)
11964 {
11965    int x;
11966    int trunkgroup;
11967    /* Get appropriate trunk group if there is one */
11968    trunkgroup = pris[*span].mastertrunkgroup;
11969    if (trunkgroup) {
11970       /* Select a specific trunk group */
11971       for (x = 0; x < NUM_SPANS; x++) {
11972          if (pris[x].pri.trunkgroup == trunkgroup) {
11973             *span = x;
11974             return 0;
11975          }
11976       }
11977       ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
11978       *span = -1;
11979    } else {
11980       if (pris[*span].pri.trunkgroup) {
11981          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is trunk group %d (please use spanmap)\n", *span, pris[*span].pri.trunkgroup);
11982          *span = -1;
11983       } else if (pris[*span].mastertrunkgroup) {
11984          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
11985          *span = -1;
11986       } else {
11987          if (si->totalchans == 31) {
11988             /* E1 */
11989             pris[*span].dchannels[0] = 16 + offset;
11990          } else if (si->totalchans == 24) {
11991             /* T1 or J1 */
11992             pris[*span].dchannels[0] = 24 + offset;
11993          } else if (si->totalchans == 3) {
11994             /* BRI */
11995             pris[*span].dchannels[0] = 3 + offset;
11996          } else {
11997             ast_log(LOG_WARNING, "Unable to use span %d, since the D-channel cannot be located (unexpected span size of %d channels)\n", *span, si->totalchans);
11998             *span = -1;
11999             return 0;
12000          }
12001          pris[*span].pri.span = *span + 1;
12002       }
12003    }
12004    return 0;
12005 }
12006 #endif   /* defined(HAVE_PRI) */
12007 
12008 #if defined(HAVE_PRI)
12009 static int pri_create_trunkgroup(int trunkgroup, int *channels)
12010 {
12011    struct dahdi_spaninfo si;
12012    struct dahdi_params p;
12013    int fd;
12014    int span;
12015    int ospan=0;
12016    int x,y;
12017    for (x = 0; x < NUM_SPANS; x++) {
12018       if (pris[x].pri.trunkgroup == trunkgroup) {
12019          ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
12020          return -1;
12021       }
12022    }
12023    for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
12024       if (!channels[y])
12025          break;
12026       memset(&si, 0, sizeof(si));
12027       memset(&p, 0, sizeof(p));
12028       fd = open("/dev/dahdi/channel", O_RDWR);
12029       if (fd < 0) {
12030          ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
12031          return -1;
12032       }
12033       x = channels[y];
12034       if (ioctl(fd, DAHDI_SPECIFY, &x)) {
12035          ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
12036          close(fd);
12037          return -1;
12038       }
12039       if (ioctl(fd, DAHDI_GET_PARAMS, &p)) {
12040          ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
12041          return -1;
12042       }
12043       if (ioctl(fd, DAHDI_SPANSTAT, &si)) {
12044          ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d): %s\n", channels[y], p.spanno, strerror(errno));
12045          close(fd);
12046          return -1;
12047       }
12048       span = p.spanno - 1;
12049       if (pris[span].pri.trunkgroup) {
12050          ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].pri.trunkgroup);
12051          close(fd);
12052          return -1;
12053       }
12054       if (pris[span].pri.pvts[0]) {
12055          ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
12056          close(fd);
12057          return -1;
12058       }
12059       if (!y) {
12060          pris[span].pri.trunkgroup = trunkgroup;
12061          ospan = span;
12062       }
12063       pris[ospan].dchannels[y] = channels[y];
12064       pris[span].pri.span = span + 1;
12065       close(fd);
12066    }
12067    return 0;
12068 }
12069 #endif   /* defined(HAVE_PRI) */
12070 
12071 #if defined(HAVE_PRI)
12072 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
12073 {
12074    if (pris[span].mastertrunkgroup) {
12075       ast_log(LOG_WARNING, "Span %d is already part of trunk group %d, cannot add to trunk group %d\n", span + 1, pris[span].mastertrunkgroup, trunkgroup);
12076       return -1;
12077    }
12078    pris[span].mastertrunkgroup = trunkgroup;
12079    pris[span].prilogicalspan = logicalspan;
12080    return 0;
12081 }
12082 #endif   /* defined(HAVE_PRI) */
12083 
12084 #if defined(HAVE_SS7)
12085 static unsigned int parse_pointcode(const char *pcstring)
12086 {
12087    unsigned int code1, code2, code3;
12088    int numvals;
12089 
12090    numvals = sscanf(pcstring, "%30d-%30d-%30d", &code1, &code2, &code3);
12091    if (numvals == 1)
12092       return code1;
12093    if (numvals == 3)
12094       return (code1 << 16) | (code2 << 8) | code3;
12095 
12096    return 0;
12097 }
12098 #endif   /* defined(HAVE_SS7) */
12099 
12100 #if defined(HAVE_SS7)
12101 static struct dahdi_ss7 * ss7_resolve_linkset(int linkset)
12102 {
12103    if ((linkset < 0) || (linkset >= NUM_SPANS))
12104       return NULL;
12105    else
12106       return &linksets[linkset - 1];
12107 }
12108 #endif   /* defined(HAVE_SS7) */
12109 
12110 #ifdef HAVE_OPENR2
12111 static void dahdi_r2_destroy_links(void)
12112 {
12113    int i = 0;
12114    if (!r2links) {
12115       return;
12116    }
12117    for (; i < r2links_count; i++) {
12118       if (r2links[i]->r2master != AST_PTHREADT_NULL) {
12119          pthread_cancel(r2links[i]->r2master);
12120          pthread_join(r2links[i]->r2master, NULL);
12121          openr2_context_delete(r2links[i]->protocol_context);
12122       }
12123       ast_free(r2links[i]);
12124    }
12125    ast_free(r2links);
12126    r2links = NULL;
12127    r2links_count = 0;
12128 }
12129 
12130 #define R2_LINK_CAPACITY 10
12131 static struct dahdi_mfcr2 *dahdi_r2_get_link(void)
12132 {
12133    struct dahdi_mfcr2 *new_r2link = NULL;
12134    struct dahdi_mfcr2 **new_r2links = NULL;
12135    /* this function is called just when starting up and no monitor threads have been launched,
12136       no need to lock monitored_count member */
12137    if (!r2links_count || (r2links[r2links_count - 1]->monitored_count == R2_LINK_CAPACITY)) {
12138       new_r2link = ast_calloc(1, sizeof(**r2links));
12139       if (!new_r2link) {
12140          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
12141          return NULL;
12142       }
12143       new_r2links = ast_realloc(r2links, ((r2links_count + 1) * sizeof(*r2links)));
12144       if (!new_r2links) {
12145          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
12146          ast_free(new_r2link);
12147          return NULL;
12148       }
12149       r2links = new_r2links;
12150       new_r2link->r2master = AST_PTHREADT_NULL;
12151       r2links[r2links_count] = new_r2link;
12152       r2links_count++;
12153       ast_log(LOG_DEBUG, "Created new R2 link!\n");
12154    }
12155    return r2links[r2links_count - 1];
12156 }
12157 
12158 static int dahdi_r2_set_context(struct dahdi_mfcr2 *r2_link, const struct dahdi_chan_conf *conf)
12159 {
12160    char tmplogdir[] = "/tmp";
12161    char logdir[OR2_MAX_PATH];
12162    int threshold = 0;
12163    int snres = 0;
12164    r2_link->protocol_context = openr2_context_new(NULL, &dahdi_r2_event_iface,
12165          &dahdi_r2_transcode_iface, conf->mfcr2.variant, conf->mfcr2.max_ani,
12166          conf->mfcr2.max_dnis);
12167    if (!r2_link->protocol_context) {
12168       return -1;
12169    }
12170    openr2_context_set_log_level(r2_link->protocol_context, conf->mfcr2.loglevel);
12171    openr2_context_set_ani_first(r2_link->protocol_context, conf->mfcr2.get_ani_first);
12172 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
12173    openr2_context_set_skip_category_request(r2_link->protocol_context, conf->mfcr2.skip_category_request);
12174 #endif
12175    openr2_context_set_mf_threshold(r2_link->protocol_context, threshold);
12176    openr2_context_set_mf_back_timeout(r2_link->protocol_context, conf->mfcr2.mfback_timeout);
12177    openr2_context_set_metering_pulse_timeout(r2_link->protocol_context, conf->mfcr2.metering_pulse_timeout);
12178    openr2_context_set_double_answer(r2_link->protocol_context, conf->mfcr2.double_answer);
12179    openr2_context_set_immediate_accept(r2_link->protocol_context, conf->mfcr2.immediate_accept);
12180    if (ast_strlen_zero(conf->mfcr2.logdir)) {
12181       if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
12182          ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
12183       }
12184    } else {
12185       snres = snprintf(logdir, sizeof(logdir), "%s/%s/%s", ast_config_AST_LOG_DIR, "mfcr2", conf->mfcr2.logdir);
12186       if (snres >= sizeof(logdir)) {
12187          ast_log(LOG_ERROR, "MFC/R2 logging directory truncated, using %s\n", tmplogdir);
12188          if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
12189             ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
12190          }
12191       } else {
12192          if (openr2_context_set_log_directory(r2_link->protocol_context, logdir)) {
12193             ast_log(LOG_ERROR, "Failed setting MFC/R2 log directory %s\n", logdir);
12194          }
12195       }
12196    }
12197    if (!ast_strlen_zero(conf->mfcr2.r2proto_file)) {
12198       if (openr2_context_configure_from_advanced_file(r2_link->protocol_context, conf->mfcr2.r2proto_file)) {
12199          ast_log(LOG_ERROR, "Failed to configure r2context from advanced configuration file %s\n", conf->mfcr2.r2proto_file);
12200       }
12201    }
12202    r2_link->monitored_count = 0;
12203    return 0;
12204 }
12205 #endif
12206 
12207 /* converts a DAHDI sigtype to signalling as can be configured from
12208  * chan_dahdi.conf.
12209  * While both have basically the same values, this will later be the
12210  * place to add filters and sanity checks
12211  */
12212 static int sigtype_to_signalling(int sigtype)
12213 {
12214    return sigtype;
12215 }
12216 
12217 /*!
12218  * \internal
12219  * \brief Get file name and channel number from (subdir,number)
12220  *
12221  * \param subdir name of the subdirectory under /dev/dahdi/
12222  * \param channel name of device file under /dev/dahdi/<subdir>/
12223  * \param path buffer to put file name in
12224  * \param pathlen maximal length of path
12225  *
12226  * \retval minor number of dahdi channel.
12227  * \retval -errno on error.
12228  */
12229 static int device2chan(const char *subdir, int channel, char *path, int pathlen)
12230 {
12231    struct stat stbuf;
12232    int      num;
12233 
12234    snprintf(path, pathlen, "/dev/dahdi/%s/%d", subdir, channel);
12235    if (stat(path, &stbuf) < 0) {
12236       ast_log(LOG_ERROR, "stat(%s) failed: %s\n", path, strerror(errno));
12237       return -errno;
12238    }
12239    if (!S_ISCHR(stbuf.st_mode)) {
12240       ast_log(LOG_ERROR, "%s: Not a character device file\n", path);
12241       return -EINVAL;
12242    }
12243    num = minor(stbuf.st_rdev);
12244    ast_log(LOG_DEBUG, "%s -> %d\n", path, num);
12245    return num;
12246 
12247 }
12248 
12249 /*!
12250  * \internal
12251  * \brief Initialize/create a channel interface.
12252  *
12253  * \param channel Channel interface number to initialize/create.
12254  * \param conf Configuration parameters to initialize interface with.
12255  * \param reloading What we are doing now:
12256  * 0 - initial module load,
12257  * 1 - module reload,
12258  * 2 - module restart
12259  *
12260  * \retval Interface-pointer initialized/created
12261  * \retval NULL if error
12262  */
12263 static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf, int reloading)
12264 {
12265    /* Make a dahdi_pvt structure for this interface */
12266    struct dahdi_pvt *tmp;/*!< Current channel structure initializing */
12267    char fn[80];
12268    struct dahdi_bufferinfo bi;
12269 
12270    int res;
12271 #if defined(HAVE_PRI)
12272    int span = 0;
12273 #endif   /* defined(HAVE_PRI) */
12274    int here = 0;/*!< TRUE if the channel interface already exists. */
12275    int x;
12276    struct analog_pvt *analog_p = NULL;
12277    struct dahdi_params p;
12278 #if defined(HAVE_PRI)
12279    struct dahdi_spaninfo si;
12280    struct sig_pri_chan *pri_chan = NULL;
12281 #endif   /* defined(HAVE_PRI) */
12282 #if defined(HAVE_SS7)
12283    struct sig_ss7_chan *ss7_chan = NULL;
12284 #endif   /* defined(HAVE_SS7) */
12285 
12286    /* Search channel interface list to see if it already exists. */
12287    for (tmp = iflist; tmp; tmp = tmp->next) {
12288       if (!tmp->destroy) {
12289          if (tmp->channel == channel) {
12290             /* The channel interface already exists. */
12291             here = 1;
12292             break;
12293          }
12294          if (tmp->channel > channel) {
12295             /* No way it can be in the sorted list. */
12296             tmp = NULL;
12297             break;
12298          }
12299       }
12300    }
12301 
12302    if (!here && reloading != 1) {
12303       tmp = ast_calloc(1, sizeof(*tmp));
12304       if (!tmp) {
12305          return NULL;
12306       }
12307       tmp->cc_params = ast_cc_config_params_init();
12308       if (!tmp->cc_params) {
12309          ast_free(tmp);
12310          return NULL;
12311       }
12312       ast_mutex_init(&tmp->lock);
12313       ifcount++;
12314       for (x = 0; x < 3; x++)
12315          tmp->subs[x].dfd = -1;
12316       tmp->channel = channel;
12317       tmp->priindication_oob = conf->chan.priindication_oob;
12318    }
12319 
12320    if (tmp) {
12321       int chan_sig = conf->chan.sig;
12322 
12323       /* If there are variables in tmp before it is updated to match the new config, clear them */
12324       if (reloading && tmp->vars) {
12325          ast_variables_destroy(tmp->vars);
12326          tmp->vars = NULL;
12327       }
12328 
12329 
12330       if (!here) {
12331          /* Can only get here if this is a new channel interface being created. */
12332          if ((channel != CHAN_PSEUDO)) {
12333             int count = 0;
12334 
12335             snprintf(fn, sizeof(fn), "%d", channel);
12336             /* Open non-blocking */
12337             tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
12338             while (tmp->subs[SUB_REAL].dfd < 0 && reloading == 2 && count < 1000) { /* the kernel may not call dahdi_release fast enough for the open flagbit to be cleared in time */
12339                usleep(1);
12340                tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
12341                count++;
12342             }
12343             /* Allocate a DAHDI structure */
12344             if (tmp->subs[SUB_REAL].dfd < 0) {
12345                ast_log(LOG_ERROR, "Unable to open channel %d: %s\nhere = %d, tmp->channel = %d, channel = %d\n", channel, strerror(errno), here, tmp->channel, channel);
12346                destroy_dahdi_pvt(tmp);
12347                return NULL;
12348             }
12349             memset(&p, 0, sizeof(p));
12350             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12351             if (res < 0) {
12352                ast_log(LOG_ERROR, "Unable to get parameters: %s\n", strerror(errno));
12353                destroy_dahdi_pvt(tmp);
12354                return NULL;
12355             }
12356             if (conf->is_sig_auto)
12357                chan_sig = sigtype_to_signalling(p.sigtype);
12358             if (p.sigtype != (chan_sig & 0x3ffff)) {
12359                ast_log(LOG_ERROR, "Signalling requested on channel %d is %s but line is in %s signalling\n", channel, sig2str(chan_sig), sig2str(p.sigtype));
12360                destroy_dahdi_pvt(tmp);
12361                return NULL;
12362             }
12363             tmp->law_default = p.curlaw;
12364             tmp->law = p.curlaw;
12365             tmp->span = p.spanno;
12366 #if defined(HAVE_PRI)
12367             span = p.spanno - 1;
12368 #endif   /* defined(HAVE_PRI) */
12369          } else {
12370             chan_sig = 0;
12371          }
12372          tmp->sig = chan_sig;
12373          tmp->outsigmod = conf->chan.outsigmod;
12374 
12375          if (analog_lib_handles(chan_sig, tmp->radio, tmp->oprmode)) {
12376             analog_p = analog_new(dahdisig_to_analogsig(chan_sig), &dahdi_analog_callbacks, tmp);
12377             if (!analog_p) {
12378                destroy_dahdi_pvt(tmp);
12379                return NULL;
12380             }
12381             tmp->sig_pvt = analog_p;
12382          }
12383 #if defined(HAVE_SS7)
12384          if (chan_sig == SIG_SS7) {
12385             struct dahdi_ss7 *ss7;
12386             int clear = 0;
12387 
12388             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &clear)) {
12389                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
12390                destroy_dahdi_pvt(tmp);
12391                return NULL;
12392             }
12393 
12394             ss7 = ss7_resolve_linkset(cur_linkset);
12395             if (!ss7) {
12396                ast_log(LOG_ERROR, "Unable to find linkset %d\n", cur_linkset);
12397                destroy_dahdi_pvt(tmp);
12398                return NULL;
12399             }
12400             ss7->ss7.span = cur_linkset;
12401             if (cur_cicbeginswith < 0) {
12402                ast_log(LOG_ERROR, "Need to set cicbeginswith for the channels!\n");
12403                destroy_dahdi_pvt(tmp);
12404                return NULL;
12405             }
12406             ss7_chan = sig_ss7_chan_new(tmp, &dahdi_ss7_callbacks, &ss7->ss7);
12407             if (!ss7_chan) {
12408                destroy_dahdi_pvt(tmp);
12409                return NULL;
12410             }
12411             tmp->sig_pvt = ss7_chan;
12412             tmp->ss7 = &ss7->ss7;
12413 
12414             ss7_chan->channel = tmp->channel;
12415             ss7_chan->cic = cur_cicbeginswith++;
12416 
12417             /* DB: Add CIC's DPC information */
12418             ss7_chan->dpc = cur_defaultdpc;
12419 
12420             ss7->ss7.pvts[ss7->ss7.numchans++] = ss7_chan;
12421 
12422             ast_copy_string(ss7->ss7.internationalprefix, conf->ss7.ss7.internationalprefix, sizeof(ss7->ss7.internationalprefix));
12423             ast_copy_string(ss7->ss7.nationalprefix, conf->ss7.ss7.nationalprefix, sizeof(ss7->ss7.nationalprefix));
12424             ast_copy_string(ss7->ss7.subscriberprefix, conf->ss7.ss7.subscriberprefix, sizeof(ss7->ss7.subscriberprefix));
12425             ast_copy_string(ss7->ss7.unknownprefix, conf->ss7.ss7.unknownprefix, sizeof(ss7->ss7.unknownprefix));
12426 
12427             ss7->ss7.called_nai = conf->ss7.ss7.called_nai;
12428             ss7->ss7.calling_nai = conf->ss7.ss7.calling_nai;
12429          }
12430 #endif   /* defined(HAVE_SS7) */
12431 #ifdef HAVE_OPENR2
12432          if (chan_sig == SIG_MFCR2) {
12433             struct dahdi_mfcr2 *r2_link;
12434             r2_link = dahdi_r2_get_link();
12435             if (!r2_link) {
12436                ast_log(LOG_WARNING, "Cannot get another R2 DAHDI context!\n");
12437                destroy_dahdi_pvt(tmp);
12438                return NULL;
12439             }
12440             if (!r2_link->protocol_context && dahdi_r2_set_context(r2_link, conf)) {
12441                ast_log(LOG_ERROR, "Cannot create OpenR2 protocol context.\n");
12442                destroy_dahdi_pvt(tmp);
12443                return NULL;
12444             }
12445             if (r2_link->numchans == ARRAY_LEN(r2_link->pvts)) {
12446                ast_log(LOG_ERROR, "Cannot add more channels to this link!\n");
12447                destroy_dahdi_pvt(tmp);
12448                return NULL;
12449             }
12450             r2_link->pvts[r2_link->numchans++] = tmp;
12451             tmp->r2chan = openr2_chan_new_from_fd(r2_link->protocol_context,
12452                                         tmp->subs[SUB_REAL].dfd,
12453                                         NULL, NULL);
12454             if (!tmp->r2chan) {
12455                openr2_liberr_t err = openr2_context_get_last_error(r2_link->protocol_context);
12456                ast_log(LOG_ERROR, "Cannot create OpenR2 channel: %s\n", openr2_context_error_string(err));
12457                destroy_dahdi_pvt(tmp);
12458                return NULL;
12459             }
12460             tmp->mfcr2 = r2_link;
12461             if (conf->mfcr2.call_files) {
12462                openr2_chan_enable_call_files(tmp->r2chan);
12463             }
12464             openr2_chan_set_client_data(tmp->r2chan, tmp);
12465             /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
12466             openr2_chan_set_logging_func(tmp->r2chan, (openr2_logging_func_t)dahdi_r2_on_chan_log);
12467             openr2_chan_set_log_level(tmp->r2chan, conf->mfcr2.loglevel);
12468             tmp->mfcr2_category = conf->mfcr2.category;
12469             tmp->mfcr2_charge_calls = conf->mfcr2.charge_calls;
12470             tmp->mfcr2_allow_collect_calls = conf->mfcr2.allow_collect_calls;
12471             tmp->mfcr2_forced_release = conf->mfcr2.forced_release;
12472             tmp->mfcr2_accept_on_offer = conf->mfcr2.accept_on_offer;
12473             tmp->mfcr2call = 0;
12474             tmp->mfcr2_dnis_index = 0;
12475             tmp->mfcr2_ani_index = 0;
12476             r2_link->monitored_count++;
12477          }
12478 #endif
12479 #ifdef HAVE_PRI
12480          if (dahdi_sig_pri_lib_handles(chan_sig)) {
12481             int offset;
12482             int matchesdchan;
12483             int x,y;
12484             int myswitchtype = 0;
12485 
12486             offset = 0;
12487             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &offset)) {
12488                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
12489                destroy_dahdi_pvt(tmp);
12490                return NULL;
12491             }
12492             if (span >= NUM_SPANS) {
12493                ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
12494                destroy_dahdi_pvt(tmp);
12495                return NULL;
12496             } else {
12497                si.spanno = 0;
12498                if (ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SPANSTAT,&si) == -1) {
12499                   ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
12500                   destroy_dahdi_pvt(tmp);
12501                   return NULL;
12502                }
12503                /* Store the logical span first based upon the real span */
12504                tmp->logicalspan = pris[span].prilogicalspan;
12505                pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
12506                if (span < 0) {
12507                   ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
12508                   destroy_dahdi_pvt(tmp);
12509                   return NULL;
12510                }
12511                myswitchtype = conf->pri.pri.switchtype;
12512                /* Make sure this isn't a d-channel */
12513                matchesdchan=0;
12514                for (x = 0; x < NUM_SPANS; x++) {
12515                   for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
12516                      if (pris[x].dchannels[y] == tmp->channel) {
12517                         matchesdchan = 1;
12518                         break;
12519                      }
12520                   }
12521                }
12522                if (!matchesdchan) {
12523                   if (pris[span].pri.nodetype && (pris[span].pri.nodetype != conf->pri.pri.nodetype)) {
12524                      ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].pri.nodetype));
12525                      destroy_dahdi_pvt(tmp);
12526                      return NULL;
12527                   }
12528                   if (pris[span].pri.switchtype && (pris[span].pri.switchtype != myswitchtype)) {
12529                      ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].pri.switchtype));
12530                      destroy_dahdi_pvt(tmp);
12531                      return NULL;
12532                   }
12533                   if ((pris[span].pri.dialplan) && (pris[span].pri.dialplan != conf->pri.pri.dialplan)) {
12534                      ast_log(LOG_ERROR, "Span %d is already a %s dialing plan\n", span + 1, pris[span].pri.dialplan == -1 ? "Dynamically set dialplan in ISDN" : pri_plan2str(pris[span].pri.dialplan));
12535                      destroy_dahdi_pvt(tmp);
12536                      return NULL;
12537                   }
12538                   if (!ast_strlen_zero(pris[span].pri.idledial) && strcmp(pris[span].pri.idledial, conf->pri.pri.idledial)) {
12539                      ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf->pri.pri.idledial);
12540                      destroy_dahdi_pvt(tmp);
12541                      return NULL;
12542                   }
12543                   if (!ast_strlen_zero(pris[span].pri.idleext) && strcmp(pris[span].pri.idleext, conf->pri.pri.idleext)) {
12544                      ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf->pri.pri.idleext);
12545                      destroy_dahdi_pvt(tmp);
12546                      return NULL;
12547                   }
12548                   if (pris[span].pri.minunused && (pris[span].pri.minunused != conf->pri.pri.minunused)) {
12549                      ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf->pri.pri.minunused);
12550                      destroy_dahdi_pvt(tmp);
12551                      return NULL;
12552                   }
12553                   if (pris[span].pri.minidle && (pris[span].pri.minidle != conf->pri.pri.minidle)) {
12554                      ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf->pri.pri.minidle);
12555                      destroy_dahdi_pvt(tmp);
12556                      return NULL;
12557                   }
12558                   if (pris[span].pri.numchans >= ARRAY_LEN(pris[span].pri.pvts)) {
12559                      ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
12560                         pris[span].pri.trunkgroup);
12561                      destroy_dahdi_pvt(tmp);
12562                      return NULL;
12563                   }
12564 
12565                   ast_debug(4, "Adding callbacks %p to chan %d\n", &dahdi_pri_callbacks, tmp->channel);
12566                   pri_chan = sig_pri_chan_new(tmp, &dahdi_pri_callbacks, &pris[span].pri, tmp->logicalspan, p.chanpos, pris[span].mastertrunkgroup);
12567                   if (!pri_chan) {
12568                      destroy_dahdi_pvt(tmp);
12569                      return NULL;
12570                   }
12571                   tmp->sig_pvt = pri_chan;
12572                   tmp->pri = &pris[span].pri;
12573 
12574                   tmp->priexclusive = conf->chan.priexclusive;
12575 
12576                   if (!tmp->pri->cc_params) {
12577                      tmp->pri->cc_params = ast_cc_config_params_init();
12578                      if (!tmp->pri->cc_params) {
12579                         destroy_dahdi_pvt(tmp);
12580                         return NULL;
12581                      }
12582                   }
12583                   ast_cc_copy_config_params(tmp->pri->cc_params,
12584                      conf->chan.cc_params);
12585 
12586                   pris[span].pri.sig = chan_sig;
12587                   pris[span].pri.nodetype = conf->pri.pri.nodetype;
12588                   pris[span].pri.switchtype = myswitchtype;
12589                   pris[span].pri.nsf = conf->pri.pri.nsf;
12590                   pris[span].pri.dialplan = conf->pri.pri.dialplan;
12591                   pris[span].pri.localdialplan = conf->pri.pri.localdialplan;
12592                   pris[span].pri.pvts[pris[span].pri.numchans++] = tmp->sig_pvt;
12593                   pris[span].pri.minunused = conf->pri.pri.minunused;
12594                   pris[span].pri.minidle = conf->pri.pri.minidle;
12595                   pris[span].pri.overlapdial = conf->pri.pri.overlapdial;
12596                   pris[span].pri.qsigchannelmapping = conf->pri.pri.qsigchannelmapping;
12597                   pris[span].pri.discardremoteholdretrieval = conf->pri.pri.discardremoteholdretrieval;
12598 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12599                   pris[span].pri.enable_service_message_support = conf->pri.pri.enable_service_message_support;
12600 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
12601 #ifdef HAVE_PRI_INBANDDISCONNECT
12602                   pris[span].pri.inbanddisconnect = conf->pri.pri.inbanddisconnect;
12603 #endif
12604 #if defined(HAVE_PRI_CALL_HOLD)
12605                   pris[span].pri.hold_disconnect_transfer =
12606                      conf->pri.pri.hold_disconnect_transfer;
12607 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
12608 #if defined(HAVE_PRI_CCSS)
12609                   pris[span].pri.cc_ptmp_recall_mode =
12610                      conf->pri.pri.cc_ptmp_recall_mode;
12611                   pris[span].pri.cc_qsig_signaling_link_req =
12612                      conf->pri.pri.cc_qsig_signaling_link_req;
12613                   pris[span].pri.cc_qsig_signaling_link_rsp =
12614                      conf->pri.pri.cc_qsig_signaling_link_rsp;
12615 #endif   /* defined(HAVE_PRI_CCSS) */
12616 #if defined(HAVE_PRI_CALL_WAITING)
12617                   pris[span].pri.max_call_waiting_calls =
12618                      conf->pri.pri.max_call_waiting_calls;
12619                   pris[span].pri.allow_call_waiting_calls =
12620                      conf->pri.pri.allow_call_waiting_calls;
12621 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12622                   pris[span].pri.transfer = conf->chan.transfer;
12623                   pris[span].pri.facilityenable = conf->pri.pri.facilityenable;
12624 #if defined(HAVE_PRI_L2_PERSISTENCE)
12625                   pris[span].pri.l2_persistence = conf->pri.pri.l2_persistence;
12626 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
12627 #if defined(HAVE_PRI_AOC_EVENTS)
12628                   pris[span].pri.aoc_passthrough_flag = conf->pri.pri.aoc_passthrough_flag;
12629                   pris[span].pri.aoce_delayhangup = conf->pri.pri.aoce_delayhangup;
12630 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
12631                   if (chan_sig == SIG_BRI_PTMP) {
12632                      pris[span].pri.layer1_ignored = conf->pri.pri.layer1_ignored;
12633                   } else {
12634                      /* Option does not apply to this line type. */
12635                      pris[span].pri.layer1_ignored = 0;
12636                   }
12637                   pris[span].pri.append_msn_to_user_tag = conf->pri.pri.append_msn_to_user_tag;
12638                   ast_copy_string(pris[span].pri.initial_user_tag, conf->chan.cid_tag, sizeof(pris[span].pri.initial_user_tag));
12639                   ast_copy_string(pris[span].pri.msn_list, conf->pri.pri.msn_list, sizeof(pris[span].pri.msn_list));
12640 #if defined(HAVE_PRI_MWI)
12641                   ast_copy_string(pris[span].pri.mwi_mailboxes,
12642                      conf->pri.pri.mwi_mailboxes,
12643                      sizeof(pris[span].pri.mwi_mailboxes));
12644 #endif   /* defined(HAVE_PRI_MWI) */
12645                   ast_copy_string(pris[span].pri.idledial, conf->pri.pri.idledial, sizeof(pris[span].pri.idledial));
12646                   ast_copy_string(pris[span].pri.idleext, conf->pri.pri.idleext, sizeof(pris[span].pri.idleext));
12647                   ast_copy_string(pris[span].pri.internationalprefix, conf->pri.pri.internationalprefix, sizeof(pris[span].pri.internationalprefix));
12648                   ast_copy_string(pris[span].pri.nationalprefix, conf->pri.pri.nationalprefix, sizeof(pris[span].pri.nationalprefix));
12649                   ast_copy_string(pris[span].pri.localprefix, conf->pri.pri.localprefix, sizeof(pris[span].pri.localprefix));
12650                   ast_copy_string(pris[span].pri.privateprefix, conf->pri.pri.privateprefix, sizeof(pris[span].pri.privateprefix));
12651                   ast_copy_string(pris[span].pri.unknownprefix, conf->pri.pri.unknownprefix, sizeof(pris[span].pri.unknownprefix));
12652                   pris[span].pri.resetinterval = conf->pri.pri.resetinterval;
12653 
12654                   for (x = 0; x < PRI_MAX_TIMERS; x++) {
12655                      pris[span].pri.pritimers[x] = conf->pri.pri.pritimers[x];
12656                   }
12657 
12658 #if defined(HAVE_PRI_CALL_WAITING)
12659                   /* Channel initial config parameters. */
12660                   pris[span].pri.ch_cfg.stripmsd = conf->chan.stripmsd;
12661                   pris[span].pri.ch_cfg.hidecallerid = conf->chan.hidecallerid;
12662                   pris[span].pri.ch_cfg.hidecalleridname = conf->chan.hidecalleridname;
12663                   pris[span].pri.ch_cfg.immediate = conf->chan.immediate;
12664                   pris[span].pri.ch_cfg.priexclusive = conf->chan.priexclusive;
12665                   pris[span].pri.ch_cfg.priindication_oob = conf->chan.priindication_oob;
12666                   pris[span].pri.ch_cfg.use_callerid = conf->chan.use_callerid;
12667                   pris[span].pri.ch_cfg.use_callingpres = conf->chan.use_callingpres;
12668                   ast_copy_string(pris[span].pri.ch_cfg.context, conf->chan.context, sizeof(pris[span].pri.ch_cfg.context));
12669                   ast_copy_string(pris[span].pri.ch_cfg.mohinterpret, conf->chan.mohinterpret, sizeof(pris[span].pri.ch_cfg.mohinterpret));
12670 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12671                } else {
12672                   ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", p.chanpos);
12673                   destroy_dahdi_pvt(tmp);
12674                   return NULL;
12675                }
12676             }
12677          }
12678 #endif
12679       } else {
12680          /* already exists in interface list */
12681          ast_log(LOG_WARNING, "Attempt to configure channel %d with signaling %s ignored because it is already configured to be %s.\n", tmp->channel, dahdi_sig2str(chan_sig), dahdi_sig2str(tmp->sig));
12682          chan_sig = tmp->sig;
12683          if (tmp->subs[SUB_REAL].dfd > -1) {
12684             memset(&p, 0, sizeof(p));
12685             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12686          }
12687       }
12688       /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
12689       switch (chan_sig) {
12690       case SIG_FXSKS:
12691       case SIG_FXSLS:
12692       case SIG_EM:
12693       case SIG_EM_E1:
12694       case SIG_EMWINK:
12695       case SIG_FEATD:
12696       case SIG_FEATDMF:
12697       case SIG_FEATDMF_TA:
12698       case SIG_FEATB:
12699       case SIG_E911:
12700       case SIG_SF:
12701       case SIG_SFWINK:
12702       case SIG_FGC_CAMA:
12703       case SIG_FGC_CAMAMF:
12704       case SIG_SF_FEATD:
12705       case SIG_SF_FEATDMF:
12706       case SIG_SF_FEATB:
12707          p.starttime = 250;
12708          break;
12709       }
12710 
12711       if (tmp->radio) {
12712          /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
12713          p.channo = channel;
12714          p.rxwinktime = 1;
12715          p.rxflashtime = 1;
12716          p.starttime = 1;
12717          p.debouncetime = 5;
12718       } else {
12719          p.channo = channel;
12720          /* Override timing settings based on config file */
12721          if (conf->timing.prewinktime >= 0)
12722             p.prewinktime = conf->timing.prewinktime;
12723          if (conf->timing.preflashtime >= 0)
12724             p.preflashtime = conf->timing.preflashtime;
12725          if (conf->timing.winktime >= 0)
12726             p.winktime = conf->timing.winktime;
12727          if (conf->timing.flashtime >= 0)
12728             p.flashtime = conf->timing.flashtime;
12729          if (conf->timing.starttime >= 0)
12730             p.starttime = conf->timing.starttime;
12731          if (conf->timing.rxwinktime >= 0)
12732             p.rxwinktime = conf->timing.rxwinktime;
12733          if (conf->timing.rxflashtime >= 0)
12734             p.rxflashtime = conf->timing.rxflashtime;
12735          if (conf->timing.debouncetime >= 0)
12736             p.debouncetime = conf->timing.debouncetime;
12737       }
12738 
12739       /* don't set parms on a pseudo-channel */
12740       if (tmp->subs[SUB_REAL].dfd >= 0)
12741       {
12742          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_PARAMS, &p);
12743          if (res < 0) {
12744             ast_log(LOG_ERROR, "Unable to set parameters: %s\n", strerror(errno));
12745             destroy_dahdi_pvt(tmp);
12746             return NULL;
12747          }
12748       }
12749 #if 1
12750       if (!here && (tmp->subs[SUB_REAL].dfd > -1)) {
12751          memset(&bi, 0, sizeof(bi));
12752          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
12753          if (!res) {
12754             bi.txbufpolicy = conf->chan.buf_policy;
12755             bi.rxbufpolicy = conf->chan.buf_policy;
12756             bi.numbufs = conf->chan.buf_no;
12757             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
12758             if (res < 0) {
12759                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", channel, strerror(errno));
12760             }
12761          } else {
12762             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", channel, strerror(errno));
12763          }
12764          tmp->buf_policy = conf->chan.buf_policy;
12765          tmp->buf_no = conf->chan.buf_no;
12766          tmp->usefaxbuffers = conf->chan.usefaxbuffers;
12767          tmp->faxbuf_policy = conf->chan.faxbuf_policy;
12768          tmp->faxbuf_no = conf->chan.faxbuf_no;
12769          /* This is not as gnarly as it may first appear.  If the ioctl above failed, we'd be setting
12770           * tmp->bufsize to zero which would cause subsequent faxbuffer-related ioctl calls to fail.
12771           * The reason the ioctl call above failed should to be determined before worrying about the
12772           * faxbuffer-related ioctl calls */
12773          tmp->bufsize = bi.bufsize;
12774       }
12775 #endif
12776       tmp->immediate = conf->chan.immediate;
12777       tmp->transfertobusy = conf->chan.transfertobusy;
12778       if (chan_sig & __DAHDI_SIG_FXS) {
12779          tmp->mwimonitor_fsk = conf->chan.mwimonitor_fsk;
12780          tmp->mwimonitor_neon = conf->chan.mwimonitor_neon;
12781          tmp->mwimonitor_rpas = conf->chan.mwimonitor_rpas;
12782       }
12783       tmp->ringt_base = ringt_base;
12784       tmp->firstradio = 0;
12785       if ((chan_sig == SIG_FXOKS) || (chan_sig == SIG_FXOLS) || (chan_sig == SIG_FXOGS))
12786          tmp->permcallwaiting = conf->chan.callwaiting;
12787       else
12788          tmp->permcallwaiting = 0;
12789       /* Flag to destroy the channel must be cleared on new mkif.  Part of changes for reload to work */
12790       tmp->destroy = 0;
12791       tmp->drings = conf->chan.drings;
12792 
12793       /* 10 is a nice default. */
12794       if (tmp->drings.ringnum[0].range == 0)
12795          tmp->drings.ringnum[0].range = 10;
12796       if (tmp->drings.ringnum[1].range == 0)
12797          tmp->drings.ringnum[1].range = 10;
12798       if (tmp->drings.ringnum[2].range == 0)
12799          tmp->drings.ringnum[2].range = 10;
12800 
12801       tmp->usedistinctiveringdetection = usedistinctiveringdetection;
12802       tmp->callwaitingcallerid = conf->chan.callwaitingcallerid;
12803       tmp->threewaycalling = conf->chan.threewaycalling;
12804       tmp->adsi = conf->chan.adsi;
12805       tmp->use_smdi = conf->chan.use_smdi;
12806       tmp->permhidecallerid = conf->chan.hidecallerid;
12807       tmp->hidecalleridname = conf->chan.hidecalleridname;
12808       tmp->callreturn = conf->chan.callreturn;
12809       tmp->echocancel = conf->chan.echocancel;
12810       tmp->echotraining = conf->chan.echotraining;
12811       tmp->pulse = conf->chan.pulse;
12812       if (tmp->echocancel.head.tap_length) {
12813          tmp->echocanbridged = conf->chan.echocanbridged;
12814       } else {
12815          if (conf->chan.echocanbridged)
12816             ast_log(LOG_NOTICE, "echocancelwhenbridged requires echocancel to be enabled; ignoring\n");
12817          tmp->echocanbridged = 0;
12818       }
12819       tmp->busydetect = conf->chan.busydetect;
12820       tmp->busycount = conf->chan.busycount;
12821       tmp->busy_tonelength = conf->chan.busy_tonelength;
12822       tmp->busy_quietlength = conf->chan.busy_quietlength;
12823       tmp->callprogress = conf->chan.callprogress;
12824       tmp->waitfordialtone = conf->chan.waitfordialtone;
12825       tmp->cancallforward = conf->chan.cancallforward;
12826       tmp->dtmfrelax = conf->chan.dtmfrelax;
12827       tmp->callwaiting = tmp->permcallwaiting;
12828       tmp->hidecallerid = tmp->permhidecallerid;
12829       tmp->channel = channel;
12830       tmp->stripmsd = conf->chan.stripmsd;
12831       tmp->use_callerid = conf->chan.use_callerid;
12832       tmp->cid_signalling = conf->chan.cid_signalling;
12833       tmp->cid_start = conf->chan.cid_start;
12834       tmp->dahditrcallerid = conf->chan.dahditrcallerid;
12835       tmp->restrictcid = conf->chan.restrictcid;
12836       tmp->use_callingpres = conf->chan.use_callingpres;
12837       if (tmp->usedistinctiveringdetection) {
12838          if (!tmp->use_callerid) {
12839             ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
12840             tmp->use_callerid = 1;
12841          }
12842       }
12843 
12844       if (tmp->cid_signalling == CID_SIG_SMDI) {
12845          if (!tmp->use_smdi) {
12846             ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
12847             tmp->use_smdi = 1;
12848          }
12849       }
12850       if (tmp->use_smdi) {
12851          tmp->smdi_iface = ast_smdi_interface_find(conf->smdi_port);
12852          if (!(tmp->smdi_iface)) {
12853             ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
12854             tmp->use_smdi = 0;
12855          }
12856       }
12857 
12858       ast_copy_string(tmp->accountcode, conf->chan.accountcode, sizeof(tmp->accountcode));
12859       tmp->amaflags = conf->chan.amaflags;
12860       if (!here) {
12861          tmp->confno = -1;
12862          tmp->propconfno = -1;
12863       }
12864       tmp->canpark = conf->chan.canpark;
12865       tmp->transfer = conf->chan.transfer;
12866       ast_copy_string(tmp->defcontext,conf->chan.context,sizeof(tmp->defcontext));
12867       ast_copy_string(tmp->language, conf->chan.language, sizeof(tmp->language));
12868       ast_copy_string(tmp->mohinterpret, conf->chan.mohinterpret, sizeof(tmp->mohinterpret));
12869       ast_copy_string(tmp->mohsuggest, conf->chan.mohsuggest, sizeof(tmp->mohsuggest));
12870       ast_copy_string(tmp->context, conf->chan.context, sizeof(tmp->context));
12871       ast_copy_string(tmp->parkinglot, conf->chan.parkinglot, sizeof(tmp->parkinglot));
12872       tmp->cid_ton = 0;
12873       if (analog_lib_handles(tmp->sig, tmp->radio, tmp->oprmode)) {
12874          ast_copy_string(tmp->cid_num, conf->chan.cid_num, sizeof(tmp->cid_num));
12875          ast_copy_string(tmp->cid_name, conf->chan.cid_name, sizeof(tmp->cid_name));
12876       } else {
12877          tmp->cid_num[0] = '\0';
12878          tmp->cid_name[0] = '\0';
12879       }
12880 #if defined(HAVE_PRI)
12881       if (dahdi_sig_pri_lib_handles(tmp->sig)) {
12882          tmp->cid_tag[0] = '\0';
12883       } else
12884 #endif   /* defined(HAVE_PRI) */
12885       {
12886          ast_copy_string(tmp->cid_tag, conf->chan.cid_tag, sizeof(tmp->cid_tag));
12887       }
12888       tmp->cid_subaddr[0] = '\0';
12889       ast_copy_string(tmp->mailbox, conf->chan.mailbox, sizeof(tmp->mailbox));
12890       if (channel != CHAN_PSEUDO && !ast_strlen_zero(tmp->mailbox)) {
12891          char *mailbox, *context;
12892          mailbox = context = ast_strdupa(tmp->mailbox);
12893          strsep(&context, "@");
12894          if (ast_strlen_zero(context))
12895             context = "default";
12896          tmp->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "Dahdi MWI subscription", NULL,
12897             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12898             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12899             AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
12900             AST_EVENT_IE_END);
12901       }
12902 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
12903       tmp->mwisend_setting = conf->chan.mwisend_setting;
12904       tmp->mwisend_fsk  = conf->chan.mwisend_fsk;
12905       tmp->mwisend_rpas = conf->chan.mwisend_rpas;
12906 #endif
12907 
12908       tmp->group = conf->chan.group;
12909       tmp->callgroup = conf->chan.callgroup;
12910       tmp->pickupgroup= conf->chan.pickupgroup;
12911       if (conf->chan.vars) {
12912          struct ast_variable *v, *tmpvar;
12913                    for (v = conf->chan.vars ; v ; v = v->next) {
12914                          if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
12915                                   tmpvar->next = tmp->vars;
12916                                    tmp->vars = tmpvar;
12917                            }
12918                   }
12919       }
12920       tmp->cid_rxgain = conf->chan.cid_rxgain;
12921       tmp->rxgain = conf->chan.rxgain;
12922       tmp->txgain = conf->chan.txgain;
12923       tmp->txdrc = conf->chan.txdrc;
12924       tmp->rxdrc = conf->chan.rxdrc;
12925       tmp->tonezone = conf->chan.tonezone;
12926       if (tmp->subs[SUB_REAL].dfd > -1) {
12927          set_actual_gain(tmp->subs[SUB_REAL].dfd, tmp->rxgain, tmp->txgain, tmp->rxdrc, tmp->txdrc, tmp->law);
12928          if (tmp->dsp)
12929             ast_dsp_set_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
12930          update_conf(tmp);
12931          if (!here) {
12932             switch (chan_sig) {
12933             case SIG_PRI_LIB_HANDLE_CASES:
12934             case SIG_SS7:
12935             case SIG_MFCR2:
12936                break;
12937             default:
12938                /* Hang it up to be sure it's good */
12939                dahdi_set_hook(tmp->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
12940                break;
12941             }
12942          }
12943          ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SETTONEZONE,&tmp->tonezone);
12944          if ((res = get_alarms(tmp)) != DAHDI_ALARM_NONE) {
12945             /* the dchannel is down so put the channel in alarm */
12946             switch (tmp->sig) {
12947 #ifdef HAVE_PRI
12948             case SIG_PRI_LIB_HANDLE_CASES:
12949                sig_pri_set_alarm(tmp->sig_pvt, 1);
12950                break;
12951 #endif
12952 #if defined(HAVE_SS7)
12953             case SIG_SS7:
12954                sig_ss7_set_alarm(tmp->sig_pvt, 1);
12955                break;
12956 #endif   /* defined(HAVE_SS7) */
12957             default:
12958                /* The only sig submodule left should be sig_analog. */
12959                analog_p = tmp->sig_pvt;
12960                if (analog_p) {
12961                   analog_p->inalarm = 1;
12962                }
12963                tmp->inalarm = 1;
12964                break;
12965             }
12966             handle_alarms(tmp, res);
12967          }
12968       }
12969 
12970       tmp->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
12971       tmp->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
12972       tmp->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
12973       tmp->sendcalleridafter = conf->chan.sendcalleridafter;
12974       ast_cc_copy_config_params(tmp->cc_params, conf->chan.cc_params);
12975 
12976       if (!here) {
12977          tmp->locallyblocked = 0;
12978          tmp->remotelyblocked = 0;
12979          switch (tmp->sig) {
12980 #if defined(HAVE_PRI)
12981          case SIG_PRI_LIB_HANDLE_CASES:
12982             tmp->inservice = 1;/* Inservice until actually implemented. */
12983 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12984             ((struct sig_pri_chan *) tmp->sig_pvt)->service_status = 0;
12985             if (chan_sig == SIG_PRI) {
12986                char db_chan_name[20];
12987                char db_answer[5];
12988 
12989                /*
12990                 * Initialize the active out-of-service status
12991                 * and delete any record if the feature is not enabled.
12992                 */
12993                snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, tmp->channel);
12994                if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
12995                   unsigned *why;
12996 
12997                   why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
12998                   if (tmp->pri->enable_service_message_support) {
12999                      char state;
13000 
13001                      sscanf(db_answer, "%1c:%30u", &state, why);
13002 
13003                      /* Ensure that only the implemented bits could be set.*/
13004                      *why &= (SRVST_NEAREND | SRVST_FAREND);
13005                   }
13006                   if (!*why) {
13007                      ast_db_del(db_chan_name, SRVST_DBKEY);
13008                   }
13009                }
13010             }
13011 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
13012             break;
13013 #endif   /* defined(HAVE_PRI) */
13014 #if defined(HAVE_SS7)
13015          case SIG_SS7:
13016             tmp->inservice = 0;
13017             break;
13018 #endif   /* defined(HAVE_SS7) */
13019          default:
13020              /* We default to in service on protocols that don't have a reset */
13021             tmp->inservice = 1;
13022             break;
13023          }
13024       }
13025 
13026       switch (tmp->sig) {
13027 #if defined(HAVE_PRI)
13028       case SIG_PRI_LIB_HANDLE_CASES:
13029          if (pri_chan) {
13030             pri_chan->channel = tmp->channel;
13031             pri_chan->hidecallerid = tmp->hidecallerid;
13032             pri_chan->hidecalleridname = tmp->hidecalleridname;
13033             pri_chan->immediate = tmp->immediate;
13034             pri_chan->inalarm = tmp->inalarm;
13035             pri_chan->priexclusive = tmp->priexclusive;
13036             pri_chan->priindication_oob = tmp->priindication_oob;
13037             pri_chan->use_callerid = tmp->use_callerid;
13038             pri_chan->use_callingpres = tmp->use_callingpres;
13039             ast_copy_string(pri_chan->context, tmp->context,
13040                sizeof(pri_chan->context));
13041             ast_copy_string(pri_chan->mohinterpret, tmp->mohinterpret,
13042                sizeof(pri_chan->mohinterpret));
13043             pri_chan->stripmsd = tmp->stripmsd;
13044          }
13045          break;
13046 #endif   /* defined(HAVE_PRI) */
13047 #if defined(HAVE_SS7)
13048       case SIG_SS7:
13049          if (ss7_chan) {
13050             ss7_chan->inalarm = tmp->inalarm;
13051 
13052             ss7_chan->stripmsd = tmp->stripmsd;
13053             ss7_chan->hidecallerid = tmp->hidecallerid;
13054             ss7_chan->use_callerid = tmp->use_callerid;
13055             ss7_chan->use_callingpres = tmp->use_callingpres;
13056             ss7_chan->immediate = tmp->immediate;
13057             ss7_chan->locallyblocked = tmp->locallyblocked;
13058             ss7_chan->remotelyblocked = tmp->remotelyblocked;
13059             ast_copy_string(ss7_chan->context, tmp->context,
13060                sizeof(ss7_chan->context));
13061             ast_copy_string(ss7_chan->mohinterpret, tmp->mohinterpret,
13062                sizeof(ss7_chan->mohinterpret));
13063          }
13064          break;
13065 #endif   /* defined(HAVE_SS7) */
13066       default:
13067          /* The only sig submodule left should be sig_analog. */
13068          analog_p = tmp->sig_pvt;
13069          if (analog_p) {
13070             analog_p->channel = tmp->channel;
13071             analog_p->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
13072             analog_p->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
13073             analog_p->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
13074             analog_p->permcallwaiting = conf->chan.callwaiting; /* permcallwaiting possibly modified in analog_config_complete */
13075             analog_p->callreturn = conf->chan.callreturn;
13076             analog_p->cancallforward = conf->chan.cancallforward;
13077             analog_p->canpark = conf->chan.canpark;
13078             analog_p->dahditrcallerid = conf->chan.dahditrcallerid;
13079             analog_p->immediate = conf->chan.immediate;
13080             analog_p->permhidecallerid = conf->chan.permhidecallerid;
13081             analog_p->pulse = conf->chan.pulse;
13082             analog_p->threewaycalling = conf->chan.threewaycalling;
13083             analog_p->transfer = conf->chan.transfer;
13084             analog_p->transfertobusy = conf->chan.transfertobusy;
13085             analog_p->use_callerid = tmp->use_callerid;
13086             analog_p->use_smdi = tmp->use_smdi;
13087             analog_p->smdi_iface = tmp->smdi_iface;
13088             analog_p->outsigmod = ANALOG_SIG_NONE;
13089             analog_p->echotraining = conf->chan.echotraining;
13090             analog_p->cid_signalling = conf->chan.cid_signalling;
13091             analog_p->stripmsd = conf->chan.stripmsd;
13092             switch (conf->chan.cid_start) {
13093             case CID_START_POLARITY:
13094                analog_p->cid_start = ANALOG_CID_START_POLARITY;
13095                break;
13096             case CID_START_POLARITY_IN:
13097                analog_p->cid_start = ANALOG_CID_START_POLARITY_IN;
13098                break;
13099             case CID_START_DTMF_NOALERT:
13100                analog_p->cid_start = ANALOG_CID_START_DTMF_NOALERT;
13101                break;
13102             default:
13103                analog_p->cid_start = ANALOG_CID_START_RING;
13104                break;
13105             }
13106             analog_p->callwaitingcallerid = conf->chan.callwaitingcallerid;
13107             analog_p->ringt = conf->chan.ringt;
13108             analog_p->ringt_base = ringt_base;
13109             analog_p->chan_tech = &dahdi_tech;
13110             analog_p->onhooktime = time(NULL);
13111             if (chan_sig & __DAHDI_SIG_FXO) {
13112                memset(&p, 0, sizeof(p));
13113                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
13114                if (!res) {
13115                   analog_p->fxsoffhookstate = p.rxisoffhook;
13116                }
13117 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
13118                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_VMWI_CONFIG, &tmp->mwisend_setting);
13119 #endif
13120             }
13121             analog_p->msgstate = -1;
13122 
13123             ast_copy_string(analog_p->mohsuggest, conf->chan.mohsuggest, sizeof(analog_p->mohsuggest));
13124             ast_copy_string(analog_p->cid_num, conf->chan.cid_num, sizeof(analog_p->cid_num));
13125             ast_copy_string(analog_p->cid_name, conf->chan.cid_name, sizeof(analog_p->cid_name));
13126 
13127             analog_config_complete(analog_p);
13128          }
13129          break;
13130       }
13131 #if defined(HAVE_PRI)
13132       if (tmp->channel == CHAN_PSEUDO) {
13133          /*
13134           * Save off pseudo channel buffer policy values for dynamic creation of
13135           * no B channel interfaces.
13136           */
13137          dahdi_pseudo_parms.buf_no = tmp->buf_no;
13138          dahdi_pseudo_parms.buf_policy = tmp->buf_policy;
13139          dahdi_pseudo_parms.faxbuf_no = tmp->faxbuf_no;
13140          dahdi_pseudo_parms.faxbuf_policy = tmp->faxbuf_policy;
13141       }
13142 #endif   /* defined(HAVE_PRI) */
13143    }
13144    if (tmp && !here) {
13145       /* Add the new channel interface to the sorted channel interface list. */
13146       dahdi_iflist_insert(tmp);
13147    }
13148    return tmp;
13149 }
13150 
13151 static int is_group_or_channel_match(struct dahdi_pvt *p, int span, ast_group_t groupmatch, int *groupmatched, int channelmatch, int *channelmatched)
13152 {
13153 #if defined(HAVE_PRI)
13154    if (0 < span) {
13155       /* The channel must be on the specified PRI span. */
13156       if (!p->pri || p->pri->span != span) {
13157          return 0;
13158       }
13159       if (!groupmatch && channelmatch == -1) {
13160          /* Match any group since it only needs to be on the PRI span. */
13161          *groupmatched = 1;
13162          return 1;
13163       }
13164    }
13165 #endif   /* defined(HAVE_PRI) */
13166    /* check group matching */
13167    if (groupmatch) {
13168       if ((p->group & groupmatch) != groupmatch)
13169          /* Doesn't match the specified group, try the next one */
13170          return 0;
13171       *groupmatched = 1;
13172    }
13173    /* Check to see if we have a channel match */
13174    if (channelmatch != -1) {
13175       if (p->channel != channelmatch)
13176          /* Doesn't match the specified channel, try the next one */
13177          return 0;
13178       *channelmatched = 1;
13179    }
13180 
13181    return 1;
13182 }
13183 
13184 static int available(struct dahdi_pvt **pvt, int is_specific_channel)
13185 {
13186    struct dahdi_pvt *p = *pvt;
13187 
13188    if (p->inalarm)
13189       return 0;
13190 
13191    if (analog_lib_handles(p->sig, p->radio, p->oprmode))
13192       return analog_available(p->sig_pvt);
13193 
13194    switch (p->sig) {
13195 #if defined(HAVE_PRI)
13196    case SIG_PRI_LIB_HANDLE_CASES:
13197       {
13198          struct sig_pri_chan *pvt_chan;
13199          int res;
13200 
13201          pvt_chan = p->sig_pvt;
13202          res = sig_pri_available(&pvt_chan, is_specific_channel);
13203          *pvt = pvt_chan->chan_pvt;
13204          return res;
13205       }
13206 #endif   /* defined(HAVE_PRI) */
13207 #if defined(HAVE_SS7)
13208    case SIG_SS7:
13209       return sig_ss7_available(p->sig_pvt);
13210 #endif   /* defined(HAVE_SS7) */
13211    default:
13212       break;
13213    }
13214 
13215    if (p->locallyblocked || p->remotelyblocked) {
13216       return 0;
13217    }
13218 
13219    /* If no owner definitely available */
13220    if (!p->owner) {
13221 #ifdef HAVE_OPENR2
13222       /* Trust MFC/R2 */
13223       if (p->mfcr2) {
13224          if (p->mfcr2call) {
13225             return 0;
13226          } else {
13227             return 1;
13228          }
13229       }
13230 #endif
13231       return 1;
13232    }
13233 
13234    return 0;
13235 }
13236 
13237 #if defined(HAVE_PRI)
13238 #if defined(HAVE_PRI_CALL_WAITING)
13239 /*!
13240  * \internal
13241  * \brief Init the private channel configuration using the span controller.
13242  * \since 1.8
13243  *
13244  * \param priv Channel to init the configuration.
13245  * \param pri sig_pri PRI control structure.
13246  *
13247  * \note Assumes the pri->lock is already obtained.
13248  *
13249  * \return Nothing
13250  */
13251 static void my_pri_init_config(void *priv, struct sig_pri_span *pri)
13252 {
13253    struct dahdi_pvt *pvt = priv;
13254 
13255    pvt->stripmsd = pri->ch_cfg.stripmsd;
13256    pvt->hidecallerid = pri->ch_cfg.hidecallerid;
13257    pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
13258    pvt->immediate = pri->ch_cfg.immediate;
13259    pvt->priexclusive = pri->ch_cfg.priexclusive;
13260    pvt->priindication_oob = pri->ch_cfg.priindication_oob;
13261    pvt->use_callerid = pri->ch_cfg.use_callerid;
13262    pvt->use_callingpres = pri->ch_cfg.use_callingpres;
13263    ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
13264    ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
13265 }
13266 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13267 #endif   /* defined(HAVE_PRI) */
13268 
13269 #if defined(HAVE_PRI)
13270 /*!
13271  * \internal
13272  * \brief Create a no B channel interface.
13273  * \since 1.8
13274  *
13275  * \param pri sig_pri span controller to add interface.
13276  *
13277  * \note Assumes the pri->lock is already obtained.
13278  *
13279  * \retval array-index into private pointer array on success.
13280  * \retval -1 on error.
13281  */
13282 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri)
13283 {
13284    int pvt_idx;
13285    int res;
13286    unsigned idx;
13287    struct dahdi_pvt *pvt;
13288    struct sig_pri_chan *chan;
13289    struct dahdi_bufferinfo bi;
13290 
13291    static int nobch_channel = CHAN_PSEUDO;
13292 
13293    /* Find spot in the private pointer array for new interface. */
13294    for (pvt_idx = 0; pvt_idx < pri->numchans; ++pvt_idx) {
13295       if (!pri->pvts[pvt_idx]) {
13296          break;
13297       }
13298    }
13299    if (pri->numchans == pvt_idx) {
13300       if (ARRAY_LEN(pri->pvts) <= pvt_idx) {
13301          ast_log(LOG_ERROR, "Unable to add a no-B-channel interface!\n");
13302          return -1;
13303       }
13304 
13305       /* Add new spot to the private pointer array. */
13306       pri->pvts[pvt_idx] = NULL;
13307       ++pri->numchans;
13308    }
13309 
13310    pvt = ast_calloc(1, sizeof(*pvt));
13311    if (!pvt) {
13312       return -1;
13313    }
13314    pvt->cc_params = ast_cc_config_params_init();
13315    if (!pvt->cc_params) {
13316       ast_free(pvt);
13317       return -1;
13318    }
13319    ast_mutex_init(&pvt->lock);
13320    for (idx = 0; idx < ARRAY_LEN(pvt->subs); ++idx) {
13321       pvt->subs[idx].dfd = -1;
13322    }
13323    pvt->buf_no = dahdi_pseudo_parms.buf_no;
13324    pvt->buf_policy = dahdi_pseudo_parms.buf_policy;
13325    pvt->faxbuf_no = dahdi_pseudo_parms.faxbuf_no;
13326    pvt->faxbuf_policy = dahdi_pseudo_parms.faxbuf_policy;
13327 
13328    chan = sig_pri_chan_new(pvt, &dahdi_pri_callbacks, pri, 0, 0, 0);
13329    if (!chan) {
13330       destroy_dahdi_pvt(pvt);
13331       return -1;
13332    }
13333    chan->no_b_channel = 1;
13334 
13335    /*
13336     * Pseudo channel companding law.
13337     * Needed for outgoing call waiting calls.
13338     * XXX May need to make this determined by switchtype or user option.
13339     */
13340    pvt->law_default = DAHDI_LAW_ALAW;
13341 
13342    pvt->sig = pri->sig;
13343    pvt->outsigmod = -1;
13344    pvt->pri = pri;
13345    pvt->sig_pvt = chan;
13346    pri->pvts[pvt_idx] = chan;
13347 
13348    pvt->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
13349    if (pvt->subs[SUB_REAL].dfd < 0) {
13350       ast_log(LOG_ERROR, "Unable to open no B channel interface pseudo channel: %s\n",
13351          strerror(errno));
13352       destroy_dahdi_pvt(pvt);
13353       return -1;
13354    }
13355    memset(&bi, 0, sizeof(bi));
13356    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
13357    if (!res) {
13358       pvt->bufsize = bi.bufsize;
13359       bi.txbufpolicy = pvt->buf_policy;
13360       bi.rxbufpolicy = pvt->buf_policy;
13361       bi.numbufs = pvt->buf_no;
13362       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
13363       if (res < 0) {
13364          ast_log(LOG_WARNING,
13365             "Unable to set buffer policy on no B channel interface: %s\n",
13366             strerror(errno));
13367       }
13368    } else
13369       ast_log(LOG_WARNING,
13370          "Unable to check buffer policy on no B channel interface: %s\n",
13371          strerror(errno));
13372 
13373    --nobch_channel;
13374    if (CHAN_PSEUDO < nobch_channel) {
13375       nobch_channel = CHAN_PSEUDO - 1;
13376    }
13377    pvt->channel = nobch_channel;
13378    pvt->span = pri->span;
13379    chan->channel = pvt->channel;
13380 
13381    dahdi_nobch_insert(pri, pvt);
13382 
13383    return pvt_idx;
13384 }
13385 #endif   /* defined(HAVE_PRI) */
13386 
13387 /* This function can *ONLY* be used for copying pseudo (CHAN_PSEUDO) private
13388    structures; it makes no attempt to safely copy regular channel private
13389    structures that might contain reference-counted object pointers and other
13390    scary bits
13391 */
13392 static struct dahdi_pvt *duplicate_pseudo(struct dahdi_pvt *src)
13393 {
13394    struct dahdi_pvt *p;
13395    struct dahdi_bufferinfo bi;
13396    int res;
13397 
13398    p = ast_malloc(sizeof(*p));
13399    if (!p) {
13400       return NULL;
13401    }
13402    *p = *src;
13403 
13404    /* Must deep copy the cc_params. */
13405    p->cc_params = ast_cc_config_params_init();
13406    if (!p->cc_params) {
13407       ast_free(p);
13408       return NULL;
13409    }
13410    ast_cc_copy_config_params(p->cc_params, src->cc_params);
13411 
13412    p->which_iflist = DAHDI_IFLIST_NONE;
13413    p->next = NULL;
13414    p->prev = NULL;
13415    ast_mutex_init(&p->lock);
13416    p->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
13417    if (p->subs[SUB_REAL].dfd < 0) {
13418       ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
13419       destroy_dahdi_pvt(p);
13420       return NULL;
13421    }
13422    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
13423    if (!res) {
13424       bi.txbufpolicy = src->buf_policy;
13425       bi.rxbufpolicy = src->buf_policy;
13426       bi.numbufs = src->buf_no;
13427       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
13428       if (res < 0) {
13429          ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel: %s\n", strerror(errno));
13430       }
13431    } else
13432       ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel: %s\n", strerror(errno));
13433    p->destroy = 1;
13434    dahdi_iflist_insert(p);
13435    return p;
13436 }
13437 
13438 struct dahdi_starting_point {
13439    /*! Group matching mask.  Zero if not specified. */
13440    ast_group_t groupmatch;
13441    /*! DAHDI channel to match with.  -1 if not specified. */
13442    int channelmatch;
13443    /*! Round robin saved search location index. (Valid if roundrobin TRUE) */
13444    int rr_starting_point;
13445    /*! ISDN span where channels can be picked (Zero if not specified) */
13446    int span;
13447    /*! Analog channel distinctive ring cadance index. */
13448    int cadance;
13449    /*! Dialing option. c/r/d if present and valid. */
13450    char opt;
13451    /*! TRUE if to search the channel list backwards. */
13452    char backwards;
13453    /*! TRUE if search is done with round robin sequence. */
13454    char roundrobin;
13455 };
13456 static struct dahdi_pvt *determine_starting_point(const char *data, struct dahdi_starting_point *param)
13457 {
13458    char *dest;
13459    char *s;
13460    int x;
13461    int res = 0;
13462    struct dahdi_pvt *p;
13463    char *subdir = NULL;
13464    AST_DECLARE_APP_ARGS(args,
13465       AST_APP_ARG(group);  /* channel/group token */
13466       //AST_APP_ARG(ext);  /* extension token */
13467       //AST_APP_ARG(opts); /* options token */
13468       AST_APP_ARG(other);  /* Any remining unused arguments */
13469    );
13470 
13471    /*
13472     * data is ---v
13473     * Dial(DAHDI/pseudo[/extension[/options]])
13474     * Dial(DAHDI/<channel#>[c|r<cadance#>|d][/extension[/options]])
13475     * Dial(DAHDI/<subdir>!<channel#>[c|r<cadance#>|d][/extension[/options]])
13476     * Dial(DAHDI/i<span>[/extension[/options]])
13477     * Dial(DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]])
13478     *
13479     * i - ISDN span channel restriction.
13480     *     Used by CC to ensure that the CC recall goes out the same span.
13481     *     Also to make ISDN channel names dialable when the sequence number
13482     *     is stripped off.  (Used by DTMF attended transfer feature.)
13483     *
13484     * g - channel group allocation search forward
13485     * G - channel group allocation search backward
13486     * r - channel group allocation round robin search forward
13487     * R - channel group allocation round robin search backward
13488     *
13489     * c - Wait for DTMF digit to confirm answer
13490     * r<cadance#> - Set distintive ring cadance number
13491     * d - Force bearer capability for ISDN/SS7 call to digital.
13492     */
13493 
13494    if (data) {
13495       dest = ast_strdupa(data);
13496    } else {
13497       ast_log(LOG_WARNING, "Channel requested with no data\n");
13498       return NULL;
13499    }
13500    AST_NONSTANDARD_APP_ARGS(args, dest, '/');
13501    if (!args.argc || ast_strlen_zero(args.group)) {
13502       ast_log(LOG_WARNING, "No channel/group specified\n");
13503       return NULL;
13504    }
13505 
13506    /* Initialize the output parameters */
13507    memset(param, 0, sizeof(*param));
13508    param->channelmatch = -1;
13509 
13510    if (strchr(args.group, '!') != NULL) {
13511       char *prev = args.group;
13512       while ((s = strchr(prev, '!')) != NULL) {
13513          *s++ = '/';
13514          prev = s;
13515       }
13516       *(prev - 1) = '\0';
13517       subdir = args.group;
13518       args.group = prev;
13519    } else if (args.group[0] == 'i') {
13520       /* Extract the ISDN span channel restriction specifier. */
13521       res = sscanf(args.group + 1, "%30d", &x);
13522       if (res < 1) {
13523          ast_log(LOG_WARNING, "Unable to determine ISDN span for data %s\n", data);
13524          return NULL;
13525       }
13526       param->span = x;
13527 
13528       /* Remove the ISDN span channel restriction specifier. */
13529       s = strchr(args.group, '-');
13530       if (!s) {
13531          /* Search all groups since we are ISDN span restricted. */
13532          return iflist;
13533       }
13534       args.group = s + 1;
13535       res = 0;
13536    }
13537    if (toupper(args.group[0]) == 'G' || toupper(args.group[0])=='R') {
13538       /* Retrieve the group number */
13539       s = args.group + 1;
13540       res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13541       if (res < 1) {
13542          ast_log(LOG_WARNING, "Unable to determine group for data %s\n", data);
13543          return NULL;
13544       }
13545       param->groupmatch = ((ast_group_t) 1 << x);
13546 
13547       if (toupper(args.group[0]) == 'G') {
13548          if (args.group[0] == 'G') {
13549             param->backwards = 1;
13550             p = ifend;
13551          } else
13552             p = iflist;
13553       } else {
13554          if (ARRAY_LEN(round_robin) <= x) {
13555             ast_log(LOG_WARNING, "Round robin index %d out of range for data %s\n",
13556                x, data);
13557             return NULL;
13558          }
13559          if (args.group[0] == 'R') {
13560             param->backwards = 1;
13561             p = round_robin[x] ? round_robin[x]->prev : ifend;
13562             if (!p)
13563                p = ifend;
13564          } else {
13565             p = round_robin[x] ? round_robin[x]->next : iflist;
13566             if (!p)
13567                p = iflist;
13568          }
13569          param->roundrobin = 1;
13570          param->rr_starting_point = x;
13571       }
13572    } else {
13573       s = args.group;
13574       if (!strcasecmp(s, "pseudo")) {
13575          /* Special case for pseudo */
13576          x = CHAN_PSEUDO;
13577          param->channelmatch = x;
13578       } else {
13579          res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13580          if (res < 1) {
13581             ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", data);
13582             return NULL;
13583          } else {
13584             param->channelmatch = x;
13585          }
13586       }
13587       if (subdir) {
13588          char path[PATH_MAX];
13589          struct stat stbuf;
13590 
13591          snprintf(path, sizeof(path), "/dev/dahdi/%s/%d",
13592                subdir, param->channelmatch);
13593          if (stat(path, &stbuf) < 0) {
13594             ast_log(LOG_WARNING, "stat(%s) failed: %s\n",
13595                   path, strerror(errno));
13596             return NULL;
13597          }
13598          if (!S_ISCHR(stbuf.st_mode)) {
13599             ast_log(LOG_ERROR, "%s: Not a character device file\n",
13600                   path);
13601             return NULL;
13602          }
13603          param->channelmatch = minor(stbuf.st_rdev);
13604       }
13605 
13606       p = iflist;
13607    }
13608 
13609    if (param->opt == 'r' && res < 3) {
13610       ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", data);
13611       param->opt = '\0';
13612    }
13613 
13614    return p;
13615 }
13616 
13617 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
13618 {
13619    int callwait = 0;
13620    struct dahdi_pvt *p;
13621    struct ast_channel *tmp = NULL;
13622    struct dahdi_pvt *exitpvt;
13623    int channelmatched = 0;
13624    int groupmatched = 0;
13625 #if defined(HAVE_PRI) || defined(HAVE_SS7)
13626    int transcapdigital = 0;
13627 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
13628    struct dahdi_starting_point start;
13629 
13630    ast_mutex_lock(&iflock);
13631    p = determine_starting_point(data, &start);
13632    if (!p) {
13633       /* We couldn't determine a starting point, which likely means badly-formatted channel name. Abort! */
13634       ast_mutex_unlock(&iflock);
13635       return NULL;
13636    }
13637 
13638    /* Search for an unowned channel */
13639    exitpvt = p;
13640    while (p && !tmp) {
13641       if (start.roundrobin)
13642          round_robin[start.rr_starting_point] = p;
13643 
13644       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)
13645          && available(&p, channelmatched)) {
13646          ast_debug(1, "Using channel %d\n", p->channel);
13647 
13648          callwait = (p->owner != NULL);
13649 #ifdef HAVE_OPENR2
13650          if (p->mfcr2) {
13651             ast_mutex_lock(&p->lock);
13652             if (p->mfcr2call) {
13653                ast_mutex_unlock(&p->lock);
13654                ast_log(LOG_DEBUG, "Yay!, someone just beat us in the race for channel %d.\n", p->channel);
13655                goto next;
13656             }
13657             p->mfcr2call = 1;
13658             ast_mutex_unlock(&p->lock);
13659          }
13660 #endif
13661          if (p->channel == CHAN_PSEUDO) {
13662             p = duplicate_pseudo(p);
13663             if (!p) {
13664                break;
13665             }
13666          }
13667 
13668          p->distinctivering = 0;
13669          /* Make special notes */
13670          switch (start.opt) {
13671          case '\0':
13672             /* No option present. */
13673             break;
13674          case 'c':
13675             /* Confirm answer */
13676             p->confirmanswer = 1;
13677             break;
13678          case 'r':
13679             /* Distinctive ring */
13680             p->distinctivering = start.cadance;
13681             break;
13682          case 'd':
13683 #if defined(HAVE_PRI) || defined(HAVE_SS7)
13684             /* If this is an ISDN call, make it digital */
13685             transcapdigital = AST_TRANS_CAP_DIGITAL;
13686 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
13687             break;
13688          default:
13689             ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", start.opt, (char *)data);
13690             break;
13691          }
13692 
13693          p->outgoing = 1;
13694          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
13695             tmp = analog_request(p->sig_pvt, &callwait, requestor);
13696 #ifdef HAVE_PRI
13697          } else if (dahdi_sig_pri_lib_handles(p->sig)) {
13698             /*
13699              * We already have the B channel reserved for this call.  We
13700              * just need to make sure that dahdi_hangup() has completed
13701              * cleaning up before continuing.
13702              */
13703             ast_mutex_lock(&p->lock);
13704             ast_mutex_unlock(&p->lock);
13705 
13706             sig_pri_extract_called_num_subaddr(p->sig_pvt, data, p->dnid,
13707                sizeof(p->dnid));
13708             tmp = sig_pri_request(p->sig_pvt, SIG_PRI_DEFLAW, requestor, transcapdigital);
13709 #endif
13710 #if defined(HAVE_SS7)
13711          } else if (p->sig == SIG_SS7) {
13712             tmp = sig_ss7_request(p->sig_pvt, SIG_SS7_DEFLAW, requestor, transcapdigital);
13713 #endif   /* defined(HAVE_SS7) */
13714          } else {
13715             tmp = dahdi_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, requestor ? requestor->linkedid : "");
13716          }
13717          if (!tmp) {
13718             p->outgoing = 0;
13719 #if defined(HAVE_PRI)
13720             switch (p->sig) {
13721             case SIG_PRI_LIB_HANDLE_CASES:
13722 #if defined(HAVE_PRI_CALL_WAITING)
13723                if (((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting) {
13724                   ((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting = 0;
13725                   ast_atomic_fetchadd_int(&p->pri->num_call_waiting_calls, -1);
13726                }
13727 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13728                /*
13729                 * This should be the last thing to clear when we are done with
13730                 * the channel.
13731                 */
13732                ((struct sig_pri_chan *) p->sig_pvt)->allocated = 0;
13733                break;
13734             default:
13735                break;
13736             }
13737 #endif   /* defined(HAVE_PRI) */
13738          } else {
13739             snprintf(p->dialstring, sizeof(p->dialstring), "DAHDI/%s", (char *) data);
13740          }
13741          break;
13742       }
13743 #ifdef HAVE_OPENR2
13744 next:
13745 #endif
13746       if (start.backwards) {
13747          p = p->prev;
13748          if (!p)
13749             p = ifend;
13750       } else {
13751          p = p->next;
13752          if (!p)
13753             p = iflist;
13754       }
13755       /* stop when you roll to the one that we started from */
13756       if (p == exitpvt)
13757          break;
13758    }
13759    ast_mutex_unlock(&iflock);
13760    restart_monitor();
13761    if (cause && !tmp) {
13762       if (callwait || channelmatched) {
13763          *cause = AST_CAUSE_BUSY;
13764       } else if (groupmatched) {
13765          *cause = AST_CAUSE_CONGESTION;
13766       } else {
13767          /*
13768           * We did not match any channel requested.
13769           * Dialplan error requesting non-existant channel?
13770           */
13771       }
13772    }
13773 
13774    return tmp;
13775 }
13776 
13777 /*!
13778  * \internal
13779  * \brief Determine the device state for a given DAHDI device if we can.
13780  * \since 1.8
13781  *
13782  * \param data DAHDI device name after "DAHDI/".
13783  *
13784  * \retval device_state enum ast_device_state value.
13785  * \retval AST_DEVICE_UNKNOWN if we could not determine the device's state.
13786  */
13787 static int dahdi_devicestate(void *data)
13788 {
13789 #if defined(HAVE_PRI)
13790    char *device;
13791    unsigned span;
13792    int res;
13793 
13794    device = data;
13795 
13796    if (*device != 'I') {
13797       /* The request is not for an ISDN span device. */
13798       return AST_DEVICE_UNKNOWN;
13799    }
13800    res = sscanf(device, "I%30u", &span);
13801    if (res != 1 || !span || NUM_SPANS < span) {
13802       /* Bad format for ISDN span device name. */
13803       return AST_DEVICE_UNKNOWN;
13804    }
13805    device = strchr(device, '/');
13806    if (!device) {
13807       /* Bad format for ISDN span device name. */
13808       return AST_DEVICE_UNKNOWN;
13809    }
13810 
13811    /*
13812     * Since there are currently no other span devstate's defined,
13813     * it must be congestion.
13814     */
13815 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13816    ++device;
13817    if (!strcmp(device, "congestion"))
13818 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13819    {
13820       return pris[span - 1].pri.congestion_devstate;
13821    }
13822 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13823    else if (!strcmp(device, "threshold")) {
13824       return pris[span - 1].pri.threshold_devstate;
13825    }
13826    return AST_DEVICE_UNKNOWN;
13827 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13828 #else
13829    return AST_DEVICE_UNKNOWN;
13830 #endif   /* defined(HAVE_PRI) */
13831 }
13832 
13833 /*!
13834  * \brief Callback made when dial failed to get a channel out of dahdi_request().
13835  * \since 1.8
13836  *
13837  * \param inbound Incoming asterisk channel.
13838  * \param dest Same dial string passed to dahdi_request().
13839  * \param callback Callback into CC core to announce a busy channel available for CC.
13840  *
13841  * \details
13842  * This callback acts like a forked dial with all prongs of the fork busy.
13843  * Essentially, for each channel that could have taken the call, indicate that
13844  * it is busy.
13845  *
13846  * \retval 0 on success.
13847  * \retval -1 on error.
13848  */
13849 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback)
13850 {
13851    struct dahdi_pvt *p;
13852    struct dahdi_pvt *exitpvt;
13853    struct dahdi_starting_point start;
13854    int groupmatched = 0;
13855    int channelmatched = 0;
13856 
13857    ast_mutex_lock(&iflock);
13858    p = determine_starting_point(dest, &start);
13859    if (!p) {
13860       ast_mutex_unlock(&iflock);
13861       return -1;
13862    }
13863    exitpvt = p;
13864    for (;;) {
13865       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)) {
13866          /* We found a potential match. call the callback */
13867          struct ast_str *device_name;
13868          char *dash;
13869          const char *monitor_type;
13870          char dialstring[AST_CHANNEL_NAME];
13871          char full_device_name[AST_CHANNEL_NAME];
13872 
13873          switch (ast_get_cc_monitor_policy(p->cc_params)) {
13874          case AST_CC_MONITOR_NEVER:
13875             break;
13876          case AST_CC_MONITOR_NATIVE:
13877          case AST_CC_MONITOR_ALWAYS:
13878          case AST_CC_MONITOR_GENERIC:
13879 #if defined(HAVE_PRI)
13880             if (dahdi_sig_pri_lib_handles(p->sig)) {
13881                /*
13882                 * ISDN is in a trunk busy condition so we need to monitor
13883                 * the span congestion device state.
13884                 */
13885                snprintf(full_device_name, sizeof(full_device_name),
13886                   "DAHDI/I%d/congestion", p->pri->span);
13887             } else
13888 #endif   /* defined(HAVE_PRI) */
13889             {
13890 #if defined(HAVE_PRI)
13891                device_name = create_channel_name(p, 1, "");
13892 #else
13893                device_name = create_channel_name(p);
13894 #endif   /* defined(HAVE_PRI) */
13895                snprintf(full_device_name, sizeof(full_device_name), "DAHDI/%s",
13896                   device_name ? ast_str_buffer(device_name) : "");
13897                ast_free(device_name);
13898                /*
13899                 * The portion after the '-' in the channel name is either a random
13900                 * number, a sequence number, or a subchannel number. None are
13901                 * necessary so strip them off.
13902                 */
13903                dash = strrchr(full_device_name, '-');
13904                if (dash) {
13905                   *dash = '\0';
13906                }
13907             }
13908             snprintf(dialstring, sizeof(dialstring), "DAHDI/%s", dest);
13909 
13910             /*
13911              * Analog can only do generic monitoring.
13912              * ISDN is in a trunk busy condition and any "device" is going
13913              * to be busy until a B channel becomes available.  The generic
13914              * monitor can do this task.
13915              */
13916             monitor_type = AST_CC_GENERIC_MONITOR_TYPE;
13917             callback(inbound,
13918 #if defined(HAVE_PRI)
13919                p->pri ? p->pri->cc_params : p->cc_params,
13920 #else
13921                p->cc_params,
13922 #endif   /* defined(HAVE_PRI) */
13923                monitor_type, full_device_name, dialstring, NULL);
13924             break;
13925          }
13926       }
13927       p = start.backwards ? p->prev : p->next;
13928       if (!p) {
13929          p = start.backwards ? ifend : iflist;
13930       }
13931       if (p == exitpvt) {
13932          break;
13933       }
13934    }
13935    ast_mutex_unlock(&iflock);
13936    return 0;
13937 }
13938 
13939 #if defined(HAVE_SS7)
13940 static void dahdi_ss7_message(struct ss7 *ss7, char *s)
13941 {
13942    int i;
13943 
13944    if (ss7) {
13945       for (i = 0; i < NUM_SPANS; i++) {
13946          if (linksets[i].ss7.ss7 == ss7) {
13947             ast_verbose("[%d] %s", i + 1, s);
13948             return;
13949          }
13950       }
13951    }
13952    ast_verbose("%s", s);
13953 }
13954 #endif   /* defined(HAVE_SS7) */
13955 
13956 #if defined(HAVE_SS7)
13957 static void dahdi_ss7_error(struct ss7 *ss7, char *s)
13958 {
13959    int i;
13960 
13961    if (ss7) {
13962       for (i = 0; i < NUM_SPANS; i++) {
13963          if (linksets[i].ss7.ss7 == ss7) {
13964             ast_log(LOG_ERROR, "[%d] %s", i + 1, s);
13965             return;
13966          }
13967       }
13968    }
13969    ast_log(LOG_ERROR, "%s", s);
13970 }
13971 #endif   /* defined(HAVE_SS7) */
13972 
13973 #if defined(HAVE_OPENR2)
13974 static void *mfcr2_monitor(void *data)
13975 {
13976    struct dahdi_mfcr2 *mfcr2 = data;
13977    /* we should be using pthread_key_create
13978       and allocate pollers dynamically.
13979       I think do_monitor() could be leaking, since it
13980       could be cancelled at any time and is not
13981       using thread keys, why?, */
13982    struct pollfd pollers[ARRAY_LEN(mfcr2->pvts)];
13983    int res = 0;
13984    int i = 0;
13985    int oldstate = 0;
13986    int quit_loop = 0;
13987    int maxsleep = 20;
13988    int was_idle = 0;
13989    int pollsize = 0;
13990    /* now that we're ready to get calls, unblock our side and
13991       get current line state */
13992    for (i = 0; i < mfcr2->numchans; i++) {
13993       openr2_chan_set_idle(mfcr2->pvts[i]->r2chan);
13994       openr2_chan_handle_cas(mfcr2->pvts[i]->r2chan);
13995    }
13996    while (1) {
13997       /* we trust here that the mfcr2 channel list will not ever change once
13998          the module is loaded */
13999       pollsize = 0;
14000       for (i = 0; i < mfcr2->numchans; i++) {
14001          pollers[i].revents = 0;
14002          pollers[i].events = 0;
14003          if (mfcr2->pvts[i]->owner) {
14004             continue;
14005          }
14006          if (!mfcr2->pvts[i]->r2chan) {
14007             ast_log(LOG_DEBUG, "Wow, no r2chan on channel %d\n", mfcr2->pvts[i]->channel);
14008             quit_loop = 1;
14009             break;
14010          }
14011          openr2_chan_enable_read(mfcr2->pvts[i]->r2chan);
14012          pollers[i].events = POLLIN | POLLPRI;
14013          pollers[i].fd = mfcr2->pvts[i]->subs[SUB_REAL].dfd;
14014          pollsize++;
14015       }
14016       if (quit_loop) {
14017          break;
14018       }
14019       if (pollsize == 0) {
14020          if (!was_idle) {
14021             ast_log(LOG_DEBUG, "Monitor thread going idle since everybody has an owner\n");
14022             was_idle = 1;
14023          }
14024          poll(NULL, 0, maxsleep);
14025          continue;
14026       }
14027       was_idle = 0;
14028       /* probably poll() is a valid cancel point, lets just be on the safe side
14029          by calling pthread_testcancel */
14030       pthread_testcancel();
14031       res = poll(pollers, mfcr2->numchans, maxsleep);
14032       pthread_testcancel();
14033       if ((res < 0) && (errno != EINTR)) {
14034          ast_log(LOG_ERROR, "going out, poll failed: %s\n", strerror(errno));
14035          break;
14036       }
14037       /* do we want to allow to cancel while processing events? */
14038       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
14039       for (i = 0; i < mfcr2->numchans; i++) {
14040          if (pollers[i].revents & POLLPRI || pollers[i].revents & POLLIN) {
14041             openr2_chan_process_event(mfcr2->pvts[i]->r2chan);
14042          }
14043       }
14044       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
14045    }
14046    ast_log(LOG_NOTICE, "Quitting MFC/R2 monitor thread\n");
14047    return 0;
14048 }
14049 #endif /* HAVE_OPENR2 */
14050 
14051 #if defined(HAVE_PRI)
14052 #ifndef PRI_RESTART
14053 #error "Upgrade your libpri"
14054 #endif
14055 static void dahdi_pri_message(struct pri *pri, char *s)
14056 {
14057    int x;
14058    int y;
14059    int dchan = -1;
14060    int span = -1;
14061    int dchancount = 0;
14062 
14063    if (pri) {
14064       for (x = 0; x < NUM_SPANS; x++) {
14065          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14066             if (pris[x].pri.dchans[y]) {
14067                dchancount++;
14068             }
14069 
14070             if (pris[x].pri.dchans[y] == pri) {
14071                dchan = y;
14072             }
14073          }
14074          if (dchan >= 0) {
14075             span = x;
14076             break;
14077          }
14078          dchancount = 0;
14079       }
14080       if (-1 < span) {
14081          if (1 < dchancount) {
14082             ast_verbose("[PRI Span: %d D-Channel: %d] %s", span + 1, dchan, s);
14083          } else {
14084             ast_verbose("PRI Span: %d %s", span + 1, s);
14085          }
14086       } else {
14087          ast_verbose("PRI Span: ? %s", s);
14088       }
14089    } else {
14090       ast_verbose("PRI Span: ? %s", s);
14091    }
14092 
14093    ast_mutex_lock(&pridebugfdlock);
14094 
14095    if (pridebugfd >= 0) {
14096       if (write(pridebugfd, s, strlen(s)) < 0) {
14097          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14098       }
14099    }
14100 
14101    ast_mutex_unlock(&pridebugfdlock);
14102 }
14103 #endif   /* defined(HAVE_PRI) */
14104 
14105 #if defined(HAVE_PRI)
14106 static void dahdi_pri_error(struct pri *pri, char *s)
14107 {
14108    int x;
14109    int y;
14110    int dchan = -1;
14111    int span = -1;
14112    int dchancount = 0;
14113 
14114    if (pri) {
14115       for (x = 0; x < NUM_SPANS; x++) {
14116          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14117             if (pris[x].pri.dchans[y]) {
14118                dchancount++;
14119             }
14120 
14121             if (pris[x].pri.dchans[y] == pri) {
14122                dchan = y;
14123             }
14124          }
14125          if (dchan >= 0) {
14126             span = x;
14127             break;
14128          }
14129          dchancount = 0;
14130       }
14131       if (-1 < span) {
14132          if (1 < dchancount) {
14133             ast_log(LOG_ERROR, "[PRI Span: %d D-Channel: %d] %s", span + 1, dchan, s);
14134          } else {
14135             ast_log(LOG_ERROR, "PRI Span: %d %s", span + 1, s);
14136          }
14137       } else {
14138          ast_log(LOG_ERROR, "PRI Span: ? %s", s);
14139       }
14140    } else {
14141       ast_log(LOG_ERROR, "PRI Span: ? %s", s);
14142    }
14143 
14144    ast_mutex_lock(&pridebugfdlock);
14145 
14146    if (pridebugfd >= 0) {
14147       if (write(pridebugfd, s, strlen(s)) < 0) {
14148          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14149       }
14150    }
14151 
14152    ast_mutex_unlock(&pridebugfdlock);
14153 }
14154 #endif   /* defined(HAVE_PRI) */
14155 
14156 #if defined(HAVE_PRI)
14157 static int prepare_pri(struct dahdi_pri *pri)
14158 {
14159    int i, res, x;
14160    struct dahdi_params p;
14161    struct dahdi_bufferinfo bi;
14162    struct dahdi_spaninfo si;
14163 
14164    pri->pri.calls = &dahdi_pri_callbacks;
14165 
14166    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
14167       if (!pri->dchannels[i])
14168          break;
14169       pri->pri.fds[i] = open("/dev/dahdi/channel", O_RDWR);
14170       x = pri->dchannels[i];
14171       if ((pri->pri.fds[i] < 0) || (ioctl(pri->pri.fds[i],DAHDI_SPECIFY,&x) == -1)) {
14172          ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
14173          return -1;
14174       }
14175       memset(&p, 0, sizeof(p));
14176       res = ioctl(pri->pri.fds[i], DAHDI_GET_PARAMS, &p);
14177       if (res) {
14178          dahdi_close_pri_fd(pri, i);
14179          ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
14180          return -1;
14181       }
14182       if ((p.sigtype != DAHDI_SIG_HDLCFCS) && (p.sigtype != DAHDI_SIG_HARDHDLC)) {
14183          dahdi_close_pri_fd(pri, i);
14184          ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode.\n", x);
14185          return -1;
14186       }
14187       memset(&si, 0, sizeof(si));
14188       res = ioctl(pri->pri.fds[i], DAHDI_SPANSTAT, &si);
14189       if (res) {
14190          dahdi_close_pri_fd(pri, i);
14191          ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
14192       }
14193       if (!si.alarms) {
14194          pri_event_noalarm(&pri->pri, i, 1);
14195       } else {
14196          pri_event_alarm(&pri->pri, i, 1);
14197       }
14198       memset(&bi, 0, sizeof(bi));
14199       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
14200       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
14201       bi.numbufs = 32;
14202       bi.bufsize = 1024;
14203       if (ioctl(pri->pri.fds[i], DAHDI_SET_BUFINFO, &bi)) {
14204          ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n", x, strerror(errno));
14205          dahdi_close_pri_fd(pri, i);
14206          return -1;
14207       }
14208       pri->pri.dchan_logical_span[i] = pris[p.spanno - 1].prilogicalspan;
14209    }
14210    return 0;
14211 }
14212 #endif   /* defined(HAVE_PRI) */
14213 
14214 #if defined(HAVE_PRI)
14215 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
14216 {
14217    int which, span;
14218    char *ret = NULL;
14219 
14220    if (pos != rpos)
14221       return ret;
14222 
14223    for (which = span = 0; span < NUM_SPANS; span++) {
14224       if (pris[span].pri.pri && ++which > state) {
14225          if (asprintf(&ret, "%d", span + 1) < 0) { /* user indexes start from 1 */
14226             ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
14227          }
14228          break;
14229       }
14230    }
14231    return ret;
14232 }
14233 #endif   /* defined(HAVE_PRI) */
14234 
14235 #if defined(HAVE_PRI)
14236 static char *complete_span_4(const char *line, const char *word, int pos, int state)
14237 {
14238    return complete_span_helper(line,word,pos,state,3);
14239 }
14240 #endif   /* defined(HAVE_PRI) */
14241 
14242 #if defined(HAVE_PRI)
14243 static char *handle_pri_set_debug_file(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14244 {
14245    int myfd;
14246    switch (cmd) {
14247    case CLI_INIT:
14248       e->command = "pri set debug file";
14249       e->usage = "Usage: pri set debug file [output-file]\n"
14250          "       Sends PRI debug output to the specified output file\n";
14251       return NULL;
14252    case CLI_GENERATE:
14253       return NULL;
14254    }
14255    if (a->argc < 5)
14256       return CLI_SHOWUSAGE;
14257 
14258    if (ast_strlen_zero(a->argv[4]))
14259       return CLI_SHOWUSAGE;
14260 
14261    myfd = open(a->argv[4], O_CREAT|O_WRONLY, AST_FILE_MODE);
14262    if (myfd < 0) {
14263       ast_cli(a->fd, "Unable to open '%s' for writing\n", a->argv[4]);
14264       return CLI_SUCCESS;
14265    }
14266 
14267    ast_mutex_lock(&pridebugfdlock);
14268 
14269    if (pridebugfd >= 0)
14270       close(pridebugfd);
14271 
14272    pridebugfd = myfd;
14273    ast_copy_string(pridebugfilename,a->argv[4],sizeof(pridebugfilename));
14274    ast_mutex_unlock(&pridebugfdlock);
14275    ast_cli(a->fd, "PRI debug output will be sent to '%s'\n", a->argv[4]);
14276    return CLI_SUCCESS;
14277 }
14278 #endif   /* defined(HAVE_PRI) */
14279 
14280 #if defined(HAVE_PRI)
14281 static char *handle_pri_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14282 {
14283    int span;
14284    int x;
14285    int level = 0;
14286    switch (cmd) {
14287    case CLI_INIT:
14288       e->command = "pri set debug {on|off|0|1|2} span";
14289       e->usage =
14290          "Usage: pri set debug {<level>|on|off} span <span>\n"
14291          "       Enables debugging on a given PRI span\n";
14292       return NULL;
14293    case CLI_GENERATE:
14294       return complete_span_4(a->line, a->word, a->pos, a->n);
14295    }
14296    if (a->argc < 6) {
14297       return CLI_SHOWUSAGE;
14298    }
14299 
14300    if (!strcasecmp(a->argv[3], "on")) {
14301       level = 1;
14302    } else if (!strcasecmp(a->argv[3], "off")) {
14303       level = 0;
14304    } else {
14305       level = atoi(a->argv[3]);
14306    }
14307    span = atoi(a->argv[5]);
14308    if ((span < 1) || (span > NUM_SPANS)) {
14309       ast_cli(a->fd, "Invalid span %s.  Should be a number %d to %d\n", a->argv[5], 1, NUM_SPANS);
14310       return CLI_SUCCESS;
14311    }
14312    if (!pris[span-1].pri.pri) {
14313       ast_cli(a->fd, "No PRI running on span %d\n", span);
14314       return CLI_SUCCESS;
14315    }
14316 
14317    /* Set debug level in libpri */
14318    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14319       if (pris[span - 1].pri.dchans[x]) {
14320          switch (level) {
14321          case 0:
14322             pri_set_debug(pris[span - 1].pri.dchans[x], 0);
14323             break;
14324          case 1:
14325             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_NORMAL);
14326             break;
14327          default:
14328             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_INTENSE);
14329             break;
14330          }
14331       }
14332    }
14333    if (level == 0) {
14334       /* Close the debugging file if it's set */
14335       ast_mutex_lock(&pridebugfdlock);
14336       if (0 <= pridebugfd) {
14337          close(pridebugfd);
14338          pridebugfd = -1;
14339          ast_cli(a->fd, "Disabled PRI debug output to file '%s'\n",
14340             pridebugfilename);
14341       }
14342       ast_mutex_unlock(&pridebugfdlock);
14343    }
14344    pris[span - 1].pri.debug = (level) ? 1 : 0;
14345    ast_cli(a->fd, "%s debugging on span %d\n", (level) ? "Enabled" : "Disabled", span);
14346    return CLI_SUCCESS;
14347 }
14348 #endif   /* defined(HAVE_PRI) */
14349 
14350 #if defined(HAVE_PRI)
14351 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14352 static char *handle_pri_service_generic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a, int changestatus)
14353 {
14354    unsigned *why;
14355    int channel;
14356    int trunkgroup;
14357    int x, y, fd = a->fd;
14358    int interfaceid = 0;
14359    char db_chan_name[20], db_answer[5];
14360    struct dahdi_pvt *tmp;
14361    struct dahdi_pri *pri;
14362 
14363    if (a->argc < 5 || a->argc > 6)
14364       return CLI_SHOWUSAGE;
14365    if (strchr(a->argv[4], ':')) {
14366       if (sscanf(a->argv[4], "%30d:%30d", &trunkgroup, &channel) != 2)
14367          return CLI_SHOWUSAGE;
14368       if ((trunkgroup < 1) || (channel < 1))
14369          return CLI_SHOWUSAGE;
14370       pri = NULL;
14371       for (x=0;x<NUM_SPANS;x++) {
14372          if (pris[x].pri.trunkgroup == trunkgroup) {
14373             pri = pris + x;
14374             break;
14375          }
14376       }
14377       if (!pri) {
14378          ast_cli(fd, "No such trunk group %d\n", trunkgroup);
14379          return CLI_FAILURE;
14380       }
14381    } else
14382       channel = atoi(a->argv[4]);
14383 
14384    if (a->argc == 6)
14385       interfaceid = atoi(a->argv[5]);
14386 
14387    /* either servicing a D-Channel */
14388    for (x = 0; x < NUM_SPANS; x++) {
14389       for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14390          if (pris[x].dchannels[y] == channel) {
14391             pri = pris + x;
14392             if (pri->pri.enable_service_message_support) {
14393                ast_mutex_lock(&pri->pri.lock);
14394                pri_maintenance_service(pri->pri.pri, interfaceid, -1, changestatus);
14395                ast_mutex_unlock(&pri->pri.lock);
14396             } else {
14397                ast_cli(fd,
14398                   "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
14399                   "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
14400             }
14401             return CLI_SUCCESS;
14402          }
14403       }
14404    }
14405 
14406    /* or servicing a B-Channel */
14407    ast_mutex_lock(&iflock);
14408    for (tmp = iflist; tmp; tmp = tmp->next) {
14409       if (tmp->pri && tmp->channel == channel) {
14410          ast_mutex_unlock(&iflock);
14411          ast_mutex_lock(&tmp->pri->lock);
14412          if (!tmp->pri->enable_service_message_support) {
14413             ast_mutex_unlock(&tmp->pri->lock);
14414             ast_cli(fd,
14415                "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
14416                "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
14417             return CLI_SUCCESS;
14418          }
14419          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, channel);
14420          why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
14421          switch(changestatus) {
14422          case 0: /* enable */
14423             /* Near end wants to be in service now. */
14424             ast_db_del(db_chan_name, SRVST_DBKEY);
14425             *why &= ~SRVST_NEAREND;
14426             if (*why) {
14427                snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
14428                ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
14429             } else {
14430                dahdi_pri_update_span_devstate(tmp->pri);
14431             }
14432             break;
14433          /* case 1:  -- loop */
14434          case 2: /* disable */
14435             /* Near end wants to be out-of-service now. */
14436             ast_db_del(db_chan_name, SRVST_DBKEY);
14437             *why |= SRVST_NEAREND;
14438             snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
14439             ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
14440             dahdi_pri_update_span_devstate(tmp->pri);
14441             break;
14442          /* case 3:  -- continuity */
14443          /* case 4:  -- shutdown */
14444          default:
14445             ast_log(LOG_WARNING, "Unsupported changestatus: '%d'\n", changestatus);
14446             break;
14447          }
14448          pri_maintenance_bservice(tmp->pri->pri, tmp->sig_pvt, changestatus);
14449          ast_mutex_unlock(&tmp->pri->lock);
14450          return CLI_SUCCESS;
14451       }
14452    }
14453    ast_mutex_unlock(&iflock);
14454 
14455    ast_cli(fd, "Unable to find given channel %d, possibly not a PRI\n", channel);
14456    return CLI_FAILURE;
14457 }
14458 
14459 static char *handle_pri_service_enable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14460 {
14461    switch (cmd) {
14462    case CLI_INIT:
14463       e->command = "pri service enable channel";
14464       e->usage =
14465          "Usage: pri service enable channel <channel> [<interface id>]\n"
14466          "       Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
14467          "  to restore a channel to service, with optional interface id\n"
14468          "  as agreed upon with remote switch operator\n";
14469       return NULL;
14470    case CLI_GENERATE:
14471       return NULL;
14472    }
14473    return handle_pri_service_generic(e, cmd, a, 0);
14474 }
14475 
14476 static char *handle_pri_service_disable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14477 {
14478    switch (cmd) {
14479    case CLI_INIT:
14480       e->command = "pri service disable channel";
14481       e->usage =
14482          "Usage: pri service disable channel <chan num> [<interface id>]\n"
14483          "  Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
14484          "  to remove a channel from service, with optional interface id\n"
14485          "  as agreed upon with remote switch operator\n";
14486       return NULL;
14487    case CLI_GENERATE:
14488       return NULL;
14489    }
14490    return handle_pri_service_generic(e, cmd, a, 2);
14491 }
14492 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14493 #endif   /* defined(HAVE_PRI) */
14494 
14495 #if defined(HAVE_PRI)
14496 static char *handle_pri_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14497 {
14498    int span;
14499 
14500    switch (cmd) {
14501    case CLI_INIT:
14502       e->command = "pri show channels";
14503       e->usage =
14504          "Usage: pri show channels\n"
14505          "       Displays PRI channel information such as the current mapping\n"
14506          "       of DAHDI B channels to Asterisk channel names and which calls\n"
14507          "       are on hold or call-waiting.  Calls on hold or call-waiting\n"
14508          "       are not associated with any B channel.\n";
14509       return NULL;
14510    case CLI_GENERATE:
14511       return NULL;
14512    }
14513 
14514    if (a->argc != 3)
14515       return CLI_SHOWUSAGE;
14516 
14517    sig_pri_cli_show_channels_header(a->fd);
14518    for (span = 0; span < NUM_SPANS; ++span) {
14519       if (pris[span].pri.pri) {
14520          sig_pri_cli_show_channels(a->fd, &pris[span].pri);
14521       }
14522    }
14523    return CLI_SUCCESS;
14524 }
14525 #endif   /* defined(HAVE_PRI) */
14526 
14527 #if defined(HAVE_PRI)
14528 static char *handle_pri_show_spans(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14529 {
14530    int span;
14531 
14532    switch (cmd) {
14533    case CLI_INIT:
14534       e->command = "pri show spans";
14535       e->usage =
14536          "Usage: pri show spans\n"
14537          "       Displays PRI span information\n";
14538       return NULL;
14539    case CLI_GENERATE:
14540       return NULL;
14541    }
14542 
14543    if (a->argc != 3)
14544       return CLI_SHOWUSAGE;
14545 
14546    for (span = 0; span < NUM_SPANS; span++) {
14547       if (pris[span].pri.pri) {
14548          sig_pri_cli_show_spans(a->fd, span + 1, &pris[span].pri);
14549       }
14550    }
14551    return CLI_SUCCESS;
14552 }
14553 #endif   /* defined(HAVE_PRI) */
14554 
14555 #if defined(HAVE_PRI)
14556 static char *handle_pri_show_span(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14557 {
14558    int span;
14559 
14560    switch (cmd) {
14561    case CLI_INIT:
14562       e->command = "pri show span";
14563       e->usage =
14564          "Usage: pri show span <span>\n"
14565          "       Displays PRI Information on a given PRI span\n";
14566       return NULL;
14567    case CLI_GENERATE:
14568       return complete_span_4(a->line, a->word, a->pos, a->n);
14569    }
14570 
14571    if (a->argc < 4)
14572       return CLI_SHOWUSAGE;
14573    span = atoi(a->argv[3]);
14574    if ((span < 1) || (span > NUM_SPANS)) {
14575       ast_cli(a->fd, "Invalid span '%s'.  Should be a number from %d to %d\n", a->argv[3], 1, NUM_SPANS);
14576       return CLI_SUCCESS;
14577    }
14578    if (!pris[span-1].pri.pri) {
14579       ast_cli(a->fd, "No PRI running on span %d\n", span);
14580       return CLI_SUCCESS;
14581    }
14582 
14583    sig_pri_cli_show_span(a->fd, pris[span-1].dchannels, &pris[span-1].pri);
14584 
14585    return CLI_SUCCESS;
14586 }
14587 #endif   /* defined(HAVE_PRI) */
14588 
14589 #if defined(HAVE_PRI)
14590 static char *handle_pri_show_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14591 {
14592    int x;
14593    int span;
14594    int count=0;
14595    int debug;
14596 
14597    switch (cmd) {
14598    case CLI_INIT:
14599       e->command = "pri show debug";
14600       e->usage =
14601          "Usage: pri show debug\n"
14602          "  Show the debug state of pri spans\n";
14603       return NULL;
14604    case CLI_GENERATE:
14605       return NULL;
14606    }
14607 
14608    for (span = 0; span < NUM_SPANS; span++) {
14609       if (pris[span].pri.pri) {
14610          for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14611             if (pris[span].pri.dchans[x]) {
14612                debug = pri_get_debug(pris[span].pri.dchans[x]);
14613                ast_cli(a->fd, "Span %d: Debug: %s\tIntense: %s\n", span+1, (debug&PRI_DEBUG_Q931_STATE)? "Yes" : "No" ,(debug&PRI_DEBUG_Q921_RAW)? "Yes" : "No" );
14614                count++;
14615             }
14616          }
14617       }
14618 
14619    }
14620    ast_mutex_lock(&pridebugfdlock);
14621    if (pridebugfd >= 0)
14622       ast_cli(a->fd, "Logging PRI debug to file %s\n", pridebugfilename);
14623    ast_mutex_unlock(&pridebugfdlock);
14624 
14625    if (!count)
14626       ast_cli(a->fd, "No PRI running\n");
14627    return CLI_SUCCESS;
14628 }
14629 #endif   /* defined(HAVE_PRI) */
14630 
14631 #if defined(HAVE_PRI)
14632 static char *handle_pri_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14633 {
14634    switch (cmd) {
14635    case CLI_INIT:
14636       e->command = "pri show version";
14637       e->usage =
14638          "Usage: pri show version\n"
14639          "Show libpri version information\n";
14640       return NULL;
14641    case CLI_GENERATE:
14642       return NULL;
14643    }
14644 
14645    ast_cli(a->fd, "libpri version: %s\n", pri_get_version());
14646 
14647    return CLI_SUCCESS;
14648 }
14649 #endif   /* defined(HAVE_PRI) */
14650 
14651 #if defined(HAVE_PRI)
14652 static struct ast_cli_entry dahdi_pri_cli[] = {
14653    AST_CLI_DEFINE(handle_pri_debug, "Enables PRI debugging on a span"),
14654 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14655    AST_CLI_DEFINE(handle_pri_service_enable_channel, "Return a channel to service"),
14656    AST_CLI_DEFINE(handle_pri_service_disable_channel, "Remove a channel from service"),
14657 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14658    AST_CLI_DEFINE(handle_pri_show_channels, "Displays PRI channel information"),
14659    AST_CLI_DEFINE(handle_pri_show_spans, "Displays PRI span information"),
14660    AST_CLI_DEFINE(handle_pri_show_span, "Displays PRI span information"),
14661    AST_CLI_DEFINE(handle_pri_show_debug, "Displays current PRI debug settings"),
14662    AST_CLI_DEFINE(handle_pri_set_debug_file, "Sends PRI debug output to the specified file"),
14663    AST_CLI_DEFINE(handle_pri_version, "Displays libpri version"),
14664 };
14665 #endif   /* defined(HAVE_PRI) */
14666 
14667 #ifdef HAVE_OPENR2
14668 
14669 static char *handle_mfcr2_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14670 {
14671    switch (cmd) {
14672    case CLI_INIT:
14673       e->command = "mfcr2 show version";
14674       e->usage =
14675          "Usage: mfcr2 show version\n"
14676          "       Shows the version of the OpenR2 library being used.\n";
14677       return NULL;
14678    case CLI_GENERATE:
14679       return NULL;
14680    }
14681    ast_cli(a->fd, "OpenR2 version: %s, revision: %s\n", openr2_get_version(), openr2_get_revision());
14682    return CLI_SUCCESS;
14683 }
14684 
14685 static char *handle_mfcr2_show_variants(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14686 {
14687 #define FORMAT "%4s %40s\n"
14688    int i = 0;
14689    int numvariants = 0;
14690    const openr2_variant_entry_t *variants;
14691    switch (cmd) {
14692    case CLI_INIT:
14693       e->command = "mfcr2 show variants";
14694       e->usage =
14695          "Usage: mfcr2 show variants\n"
14696          "       Shows the list of MFC/R2 variants supported.\n";
14697       return NULL;
14698    case CLI_GENERATE:
14699       return NULL;
14700    }
14701    if (!(variants = openr2_proto_get_variant_list(&numvariants))) {
14702       ast_cli(a->fd, "Failed to get list of variants.\n");
14703       return CLI_FAILURE;
14704    }
14705    ast_cli(a->fd, FORMAT, "Variant Code", "Country");
14706    for (i = 0; i < numvariants; i++) {
14707       ast_cli(a->fd, FORMAT, variants[i].name, variants[i].country);
14708    }
14709    return CLI_SUCCESS;
14710 #undef FORMAT
14711 }
14712 
14713 static char *handle_mfcr2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14714 {
14715 #define FORMAT "%4s %-7.7s %-7.7s %-8.8s %-9.9s %-16.16s %-8.8s %-8.8s\n"
14716    int filtertype = 0;
14717    int targetnum = 0;
14718    char channo[5];
14719    char anino[5];
14720    char dnisno[5];
14721    struct dahdi_pvt *p;
14722    openr2_context_t *r2context;
14723    openr2_variant_t r2variant;
14724    switch (cmd) {
14725    case CLI_INIT:
14726       e->command = "mfcr2 show channels [group|context]";
14727       e->usage =
14728          "Usage: mfcr2 show channels [group <group> | context <context>]\n"
14729          "       Shows the DAHDI channels configured with MFC/R2 signaling.\n";
14730       return NULL;
14731    case CLI_GENERATE:
14732       return NULL;
14733    }
14734    if (!((a->argc == 3) || (a->argc == 5))) {
14735       return CLI_SHOWUSAGE;
14736    }
14737    if (a->argc == 5) {
14738       if (!strcasecmp(a->argv[3], "group")) {
14739          targetnum = atoi(a->argv[4]);
14740          if ((targetnum < 0) || (targetnum > 63))
14741             return CLI_SHOWUSAGE;
14742          targetnum = 1 << targetnum;
14743          filtertype = 1;
14744       } else if (!strcasecmp(a->argv[3], "context")) {
14745          filtertype = 2;
14746       } else {
14747          return CLI_SHOWUSAGE;
14748       }
14749    }
14750    ast_cli(a->fd, FORMAT, "Chan", "Variant", "Max ANI", "Max DNIS", "ANI First", "Immediate Accept", "Tx CAS", "Rx CAS");
14751    ast_mutex_lock(&iflock);
14752    for (p = iflist; p; p = p->next) {
14753       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14754          continue;
14755       }
14756       if (filtertype) {
14757          switch(filtertype) {
14758          case 1: /* mfcr2 show channels group <group> */
14759             if (p->group != targetnum) {
14760                continue;
14761             }
14762             break;
14763          case 2: /* mfcr2 show channels context <context> */
14764             if (strcasecmp(p->context, a->argv[4])) {
14765                continue;
14766             }
14767             break;
14768          default:
14769             ;
14770          }
14771       }
14772       r2context = openr2_chan_get_context(p->r2chan);
14773       r2variant = openr2_context_get_variant(r2context);
14774       snprintf(channo, sizeof(channo), "%d", p->channel);
14775       snprintf(anino, sizeof(anino), "%d", openr2_context_get_max_ani(r2context));
14776       snprintf(dnisno, sizeof(dnisno), "%d", openr2_context_get_max_dnis(r2context));
14777       ast_cli(a->fd, FORMAT, channo, openr2_proto_get_variant_string(r2variant),
14778             anino, dnisno, openr2_context_get_ani_first(r2context) ? "Yes" : "No",
14779             openr2_context_get_immediate_accept(r2context) ? "Yes" : "No",
14780             openr2_chan_get_tx_cas_string(p->r2chan), openr2_chan_get_rx_cas_string(p->r2chan));
14781    }
14782    ast_mutex_unlock(&iflock);
14783    return CLI_SUCCESS;
14784 #undef FORMAT
14785 }
14786 
14787 static char *handle_mfcr2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14788 {
14789    struct dahdi_pvt *p = NULL;
14790    int channo = 0;
14791    char *toklevel = NULL;
14792    char *saveptr = NULL;
14793    char *logval = NULL;
14794    openr2_log_level_t loglevel = OR2_LOG_NOTHING;
14795    openr2_log_level_t tmplevel = OR2_LOG_NOTHING;
14796    switch (cmd) {
14797    case CLI_INIT:
14798       e->command = "mfcr2 set debug";
14799       e->usage =
14800          "Usage: mfcr2 set debug <loglevel> <channel>\n"
14801          "       Set a new logging level for the specified channel.\n"
14802          "       If no channel is specified the logging level will be applied to all channels.\n";
14803       return NULL;
14804    case CLI_GENERATE:
14805       return NULL;
14806    }
14807    if (a->argc < 4) {
14808       return CLI_SHOWUSAGE;
14809    }
14810    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14811    logval = ast_strdupa(a->argv[3]);
14812    toklevel = strtok_r(logval, ",", &saveptr);
14813    if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14814       ast_cli(a->fd, "Invalid MFC/R2 logging level '%s'.\n", a->argv[3]);
14815       return CLI_FAILURE;
14816    } else if (OR2_LOG_NOTHING == tmplevel) {
14817       loglevel = tmplevel;
14818    } else {
14819       loglevel |= tmplevel;
14820       while ((toklevel = strtok_r(NULL, ",", &saveptr))) {
14821          if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14822             ast_cli(a->fd, "Ignoring invalid logging level: '%s'.\n", toklevel);
14823             continue;
14824          }
14825          loglevel |= tmplevel;
14826       }
14827    }
14828    ast_mutex_lock(&iflock);
14829    for (p = iflist; p; p = p->next) {
14830       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14831          continue;
14832       }
14833       if ((channo != -1) && (p->channel != channo )) {
14834          continue;
14835       }
14836       openr2_chan_set_log_level(p->r2chan, loglevel);
14837       if (channo != -1) {
14838          ast_cli(a->fd, "MFC/R2 debugging set to '%s' for channel %d.\n", a->argv[3], p->channel);
14839          break;
14840       }
14841    }
14842    if ((channo != -1) && !p) {
14843       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14844    }
14845    if (channo == -1) {
14846       ast_cli(a->fd, "MFC/R2 debugging set to '%s' for all channels.\n", a->argv[3]);
14847    }
14848    ast_mutex_unlock(&iflock);
14849    return CLI_SUCCESS;
14850 }
14851 
14852 static char *handle_mfcr2_call_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14853 {
14854    struct dahdi_pvt *p = NULL;
14855    int channo = 0;
14856    switch (cmd) {
14857    case CLI_INIT:
14858       e->command = "mfcr2 call files [on|off]";
14859       e->usage =
14860          "Usage: mfcr2 call files [on|off] <channel>\n"
14861          "       Enable call files creation on the specified channel.\n"
14862          "       If no channel is specified call files creation policy will be applied to all channels.\n";
14863       return NULL;
14864    case CLI_GENERATE:
14865       return NULL;
14866    }
14867    if (a->argc < 4) {
14868       return CLI_SHOWUSAGE;
14869    }
14870    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14871    ast_mutex_lock(&iflock);
14872    for (p = iflist; p; p = p->next) {
14873       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14874          continue;
14875       }
14876       if ((channo != -1) && (p->channel != channo )) {
14877          continue;
14878       }
14879       if (ast_true(a->argv[3])) {
14880          openr2_chan_enable_call_files(p->r2chan);
14881       } else {
14882          openr2_chan_disable_call_files(p->r2chan);
14883       }
14884       if (channo != -1) {
14885          if (ast_true(a->argv[3])) {
14886             ast_cli(a->fd, "MFC/R2 call files enabled for channel %d.\n", p->channel);
14887          } else {
14888             ast_cli(a->fd, "MFC/R2 call files disabled for channel %d.\n", p->channel);
14889          }
14890          break;
14891       }
14892    }
14893    if ((channo != -1) && !p) {
14894       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14895    }
14896    if (channo == -1) {
14897       if (ast_true(a->argv[3])) {
14898          ast_cli(a->fd, "MFC/R2 Call files enabled for all channels.\n");
14899       } else {
14900          ast_cli(a->fd, "MFC/R2 Call files disabled for all channels.\n");
14901       }
14902    }
14903    ast_mutex_unlock(&iflock);
14904    return CLI_SUCCESS;
14905 }
14906 
14907 static char *handle_mfcr2_set_idle(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14908 {
14909    struct dahdi_pvt *p = NULL;
14910    int channo = 0;
14911    switch (cmd) {
14912    case CLI_INIT:
14913       e->command = "mfcr2 set idle";
14914       e->usage =
14915          "Usage: mfcr2 set idle <channel>\n"
14916          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14917          "       Force the given channel into IDLE state.\n"
14918          "       If no channel is specified, all channels will be set to IDLE.\n";
14919       return NULL;
14920    case CLI_GENERATE:
14921       return NULL;
14922    }
14923    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14924    ast_mutex_lock(&iflock);
14925    for (p = iflist; p; p = p->next) {
14926       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14927          continue;
14928       }
14929       if ((channo != -1) && (p->channel != channo )) {
14930          continue;
14931       }
14932       openr2_chan_set_idle(p->r2chan);
14933       ast_mutex_lock(&p->lock);
14934       p->locallyblocked = 0;
14935       p->mfcr2call = 0;
14936       ast_mutex_unlock(&p->lock);
14937       if (channo != -1) {
14938          break;
14939       }
14940    }
14941    if ((channo != -1) && !p) {
14942       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14943    }
14944    ast_mutex_unlock(&iflock);
14945    return CLI_SUCCESS;
14946 }
14947 
14948 static char *handle_mfcr2_set_blocked(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14949 {
14950    struct dahdi_pvt *p = NULL;
14951    int channo = 0;
14952    switch (cmd) {
14953    case CLI_INIT:
14954       e->command = "mfcr2 set blocked";
14955       e->usage =
14956          "Usage: mfcr2 set blocked <channel>\n"
14957          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14958          "       Force the given channel into BLOCKED state.\n"
14959          "       If no channel is specified, all channels will be set to BLOCKED.\n";
14960       return NULL;
14961    case CLI_GENERATE:
14962       return NULL;
14963    }
14964    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14965    ast_mutex_lock(&iflock);
14966    for (p = iflist; p; p = p->next) {
14967       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14968          continue;
14969       }
14970       if ((channo != -1) && (p->channel != channo )) {
14971          continue;
14972       }
14973       openr2_chan_set_blocked(p->r2chan);
14974       ast_mutex_lock(&p->lock);
14975       p->locallyblocked = 1;
14976       ast_mutex_unlock(&p->lock);
14977       if (channo != -1) {
14978          break;
14979       }
14980    }
14981    if ((channo != -1) && !p) {
14982       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14983    }
14984    ast_mutex_unlock(&iflock);
14985    return CLI_SUCCESS;
14986 }
14987 
14988 static struct ast_cli_entry dahdi_mfcr2_cli[] = {
14989    AST_CLI_DEFINE(handle_mfcr2_version, "Show OpenR2 library version"),
14990    AST_CLI_DEFINE(handle_mfcr2_show_variants, "Show supported MFC/R2 variants"),
14991    AST_CLI_DEFINE(handle_mfcr2_show_channels, "Show MFC/R2 channels"),
14992    AST_CLI_DEFINE(handle_mfcr2_set_debug, "Set MFC/R2 channel logging level"),
14993    AST_CLI_DEFINE(handle_mfcr2_call_files, "Enable/Disable MFC/R2 call files"),
14994    AST_CLI_DEFINE(handle_mfcr2_set_idle, "Reset MFC/R2 channel forcing it to IDLE"),
14995    AST_CLI_DEFINE(handle_mfcr2_set_blocked, "Reset MFC/R2 channel forcing it to BLOCKED"),
14996 };
14997 
14998 #endif /* HAVE_OPENR2 */
14999 
15000 static char *dahdi_destroy_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15001 {
15002    int channel;
15003    int ret;
15004    switch (cmd) {
15005    case CLI_INIT:
15006       e->command = "dahdi destroy channel";
15007       e->usage =
15008          "Usage: dahdi destroy channel <chan num>\n"
15009          "  DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.  Immediately removes a given channel, whether it is in use or not\n";
15010       return NULL;
15011    case CLI_GENERATE:
15012       return NULL;
15013    }
15014    if (a->argc != 4)
15015       return CLI_SHOWUSAGE;
15016 
15017    channel = atoi(a->argv[3]);
15018    ret = dahdi_destroy_channel_bynum(channel);
15019    return ( RESULT_SUCCESS == ret ) ? CLI_SUCCESS : CLI_FAILURE;
15020 }
15021 
15022 static void dahdi_softhangup_all(void)
15023 {
15024    struct dahdi_pvt *p;
15025 retry:
15026    ast_mutex_lock(&iflock);
15027    for (p = iflist; p; p = p->next) {
15028       ast_mutex_lock(&p->lock);
15029       if (p->owner && !p->restartpending) {
15030          if (ast_channel_trylock(p->owner)) {
15031             if (option_debug > 2)
15032                ast_verbose("Avoiding deadlock\n");
15033             /* Avoid deadlock since you're not supposed to lock iflock or pvt before a channel */
15034             ast_mutex_unlock(&p->lock);
15035             ast_mutex_unlock(&iflock);
15036             goto retry;
15037          }
15038          if (option_debug > 2)
15039             ast_verbose("Softhanging up on %s\n", p->owner->name);
15040          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_EXPLICIT);
15041          p->restartpending = 1;
15042          num_restart_pending++;
15043          ast_channel_unlock(p->owner);
15044       }
15045       ast_mutex_unlock(&p->lock);
15046    }
15047    ast_mutex_unlock(&iflock);
15048 }
15049 
15050 static int setup_dahdi(int reload);
15051 static int dahdi_restart(void)
15052 {
15053 #if defined(HAVE_PRI) || defined(HAVE_SS7)
15054    int i, j;
15055 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
15056    int cancel_code;
15057    struct dahdi_pvt *p;
15058 
15059    ast_mutex_lock(&restart_lock);
15060    ast_verb(1, "Destroying channels and reloading DAHDI configuration.\n");
15061    dahdi_softhangup_all();
15062    ast_verb(4, "Initial softhangup of all DAHDI channels complete.\n");
15063 #ifdef HAVE_OPENR2
15064    dahdi_r2_destroy_links();
15065 #endif
15066 
15067 #if defined(HAVE_PRI)
15068    for (i = 0; i < NUM_SPANS; i++) {
15069       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL)) {
15070          cancel_code = pthread_cancel(pris[i].pri.master);
15071          pthread_kill(pris[i].pri.master, SIGURG);
15072          ast_debug(4, "Waiting to join thread of span %d with pid=%p, cancel_code=%d\n", i, (void *) pris[i].pri.master, cancel_code);
15073          pthread_join(pris[i].pri.master, NULL);
15074          ast_debug(4, "Joined thread of span %d\n", i);
15075       }
15076    }
15077 #endif
15078 
15079 #if defined(HAVE_SS7)
15080    for (i = 0; i < NUM_SPANS; i++) {
15081       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL)) {
15082          cancel_code = pthread_cancel(linksets[i].ss7.master);
15083          pthread_kill(linksets[i].ss7.master, SIGURG);
15084          ast_debug(4, "Waiting to join thread of span %d with pid=%p, cancel_code=%d\n", i, (void *) linksets[i].ss7.master, cancel_code);
15085          pthread_join(linksets[i].ss7.master, NULL);
15086          ast_debug(4, "Joined thread of span %d\n", i);
15087       }
15088    }
15089 #endif   /* defined(HAVE_SS7) */
15090 
15091    ast_mutex_lock(&monlock);
15092    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
15093       cancel_code = pthread_cancel(monitor_thread);
15094       pthread_kill(monitor_thread, SIGURG);
15095       ast_debug(4, "Waiting to join monitor thread with pid=%p, cancel_code=%d\n", (void *) monitor_thread, cancel_code);
15096       pthread_join(monitor_thread, NULL);
15097       ast_debug(4, "Joined monitor thread\n");
15098    }
15099    monitor_thread = AST_PTHREADT_NULL; /* prepare to restart thread in setup_dahdi once channels are reconfigured */
15100 
15101    ast_mutex_lock(&ss_thread_lock);
15102    while (ss_thread_count > 0) { /* let ss_threads finish and run dahdi_hangup before dahvi_pvts are destroyed */
15103       int x = DAHDI_FLASH;
15104       ast_debug(3, "Waiting on %d analog_ss_thread(s) to finish\n", ss_thread_count);
15105 
15106       ast_mutex_lock(&iflock);
15107       for (p = iflist; p; p = p->next) {
15108          if (p->owner) {
15109             /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
15110             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
15111          }
15112       }
15113       ast_mutex_unlock(&iflock);
15114       ast_cond_wait(&ss_thread_complete, &ss_thread_lock);
15115    }
15116 
15117    /* ensure any created channels before monitor threads were stopped are hungup */
15118    dahdi_softhangup_all();
15119    ast_verb(4, "Final softhangup of all DAHDI channels complete.\n");
15120    destroy_all_channels();
15121    ast_debug(1, "Channels destroyed. Now re-reading config. %d active channels remaining.\n", ast_active_channels());
15122 
15123    ast_mutex_unlock(&monlock);
15124 
15125 #ifdef HAVE_PRI
15126    for (i = 0; i < NUM_SPANS; i++) {
15127       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++)
15128          dahdi_close_pri_fd(&(pris[i]), j);
15129    }
15130 
15131    memset(pris, 0, sizeof(pris));
15132    for (i = 0; i < NUM_SPANS; i++) {
15133       sig_pri_init_pri(&pris[i].pri);
15134    }
15135    pri_set_error(dahdi_pri_error);
15136    pri_set_message(dahdi_pri_message);
15137 #endif
15138 #if defined(HAVE_SS7)
15139    for (i = 0; i < NUM_SPANS; i++) {
15140       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++)
15141          dahdi_close_ss7_fd(&(linksets[i]), j);
15142    }
15143 
15144    memset(linksets, 0, sizeof(linksets));
15145    for (i = 0; i < NUM_SPANS; i++) {
15146       sig_ss7_init_linkset(&linksets[i].ss7);
15147    }
15148    ss7_set_error(dahdi_ss7_error);
15149    ss7_set_message(dahdi_ss7_message);
15150 #endif   /* defined(HAVE_SS7) */
15151 
15152    if (setup_dahdi(2) != 0) {
15153       ast_log(LOG_WARNING, "Reload channels from dahdi config failed!\n");
15154       ast_mutex_unlock(&ss_thread_lock);
15155       return 1;
15156    }
15157    ast_mutex_unlock(&ss_thread_lock);
15158    ast_mutex_unlock(&restart_lock);
15159    return 0;
15160 }
15161 
15162 static char *dahdi_restart_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15163 {
15164    switch (cmd) {
15165    case CLI_INIT:
15166       e->command = "dahdi restart";
15167       e->usage =
15168          "Usage: dahdi restart\n"
15169          "  Restarts the DAHDI channels: destroys them all and then\n"
15170          "  re-reads them from chan_dahdi.conf.\n"
15171          "  Note that this will STOP any running CALL on DAHDI channels.\n"
15172          "";
15173       return NULL;
15174    case CLI_GENERATE:
15175       return NULL;
15176    }
15177    if (a->argc != 2)
15178       return CLI_SHOWUSAGE;
15179 
15180    if (dahdi_restart() != 0)
15181       return CLI_FAILURE;
15182    return CLI_SUCCESS;
15183 }
15184 
15185 static int action_dahdirestart(struct mansession *s, const struct message *m)
15186 {
15187    if (dahdi_restart() != 0) {
15188       astman_send_error(s, m, "Failed rereading DAHDI configuration");
15189       return 1;
15190    }
15191    astman_send_ack(s, m, "DAHDIRestart: Success");
15192    return 0;
15193 }
15194 
15195 static char *dahdi_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15196 {
15197 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
15198 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
15199    unsigned int targetnum = 0;
15200    int filtertype = 0;
15201    struct dahdi_pvt *tmp = NULL;
15202    char tmps[20] = "";
15203    char statestr[20] = "";
15204    char blockstr[20] = "";
15205 
15206    switch (cmd) {
15207    case CLI_INIT:
15208       e->command = "dahdi show channels [group|context]";
15209       e->usage =
15210          "Usage: dahdi show channels [ group <group> | context <context> ]\n"
15211          "  Shows a list of available channels with optional filtering\n"
15212          "  <group> must be a number between 0 and 63\n";
15213       return NULL;
15214    case CLI_GENERATE:
15215       return NULL;
15216    }
15217 
15218    /* syntax: dahdi show channels [ group <group> | context <context> ] */
15219 
15220    if (!((a->argc == 3) || (a->argc == 5)))
15221       return CLI_SHOWUSAGE;
15222 
15223    if (a->argc == 5) {
15224       if (!strcasecmp(a->argv[3], "group")) {
15225          targetnum = atoi(a->argv[4]);
15226          if ((targetnum < 0) || (targetnum > 63))
15227             return CLI_SHOWUSAGE;
15228          targetnum = 1 << targetnum;
15229          filtertype = 1;
15230       } else if (!strcasecmp(a->argv[3], "context")) {
15231          filtertype = 2;
15232       }
15233    }
15234 
15235    ast_cli(a->fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret", "Blocked", "State");
15236    ast_mutex_lock(&iflock);
15237    for (tmp = iflist; tmp; tmp = tmp->next) {
15238       if (filtertype) {
15239          switch(filtertype) {
15240          case 1: /* dahdi show channels group <group> */
15241             if (!(tmp->group & targetnum)) {
15242                continue;
15243             }
15244             break;
15245          case 2: /* dahdi show channels context <context> */
15246             if (strcasecmp(tmp->context, a->argv[4])) {
15247                continue;
15248             }
15249             break;
15250          default:
15251             break;
15252          }
15253       }
15254       if (tmp->channel > 0) {
15255          snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
15256       } else
15257          ast_copy_string(tmps, "pseudo", sizeof(tmps));
15258 
15259       if (tmp->locallyblocked)
15260          blockstr[0] = 'L';
15261       else
15262          blockstr[0] = ' ';
15263 
15264       if (tmp->remotelyblocked)
15265          blockstr[1] = 'R';
15266       else
15267          blockstr[1] = ' ';
15268 
15269       blockstr[2] = '\0';
15270 
15271       snprintf(statestr, sizeof(statestr), "%s", "In Service");
15272 
15273       ast_cli(a->fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret, blockstr, statestr);
15274    }
15275    ast_mutex_unlock(&iflock);
15276    return CLI_SUCCESS;
15277 #undef FORMAT
15278 #undef FORMAT2
15279 }
15280 
15281 static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15282 {
15283    int channel;
15284    struct dahdi_pvt *tmp = NULL;
15285    struct dahdi_confinfo ci;
15286    struct dahdi_params ps;
15287    int x;
15288 
15289    switch (cmd) {
15290    case CLI_INIT:
15291       e->command = "dahdi show channel";
15292       e->usage =
15293          "Usage: dahdi show channel <chan num>\n"
15294          "  Detailed information about a given channel\n";
15295       return NULL;
15296    case CLI_GENERATE:
15297       return NULL;
15298    }
15299 
15300    if (a->argc != 4)
15301       return CLI_SHOWUSAGE;
15302 
15303    channel = atoi(a->argv[3]);
15304 
15305    ast_mutex_lock(&iflock);
15306    for (tmp = iflist; tmp; tmp = tmp->next) {
15307       if (tmp->channel == channel) {
15308          ast_cli(a->fd, "Channel: %d\n", tmp->channel);
15309          ast_cli(a->fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].dfd);
15310          ast_cli(a->fd, "Span: %d\n", tmp->span);
15311          ast_cli(a->fd, "Extension: %s\n", tmp->exten);
15312          ast_cli(a->fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
15313          ast_cli(a->fd, "Context: %s\n", tmp->context);
15314          ast_cli(a->fd, "Caller ID: %s\n", tmp->cid_num);
15315          ast_cli(a->fd, "Calling TON: %d\n", tmp->cid_ton);
15316 #if defined(HAVE_PRI)
15317 #if defined(HAVE_PRI_SUBADDR)
15318          ast_cli(a->fd, "Caller ID subaddress: %s\n", tmp->cid_subaddr);
15319 #endif   /* defined(HAVE_PRI_SUBADDR) */
15320 #endif   /* defined(HAVE_PRI) */
15321          ast_cli(a->fd, "Caller ID name: %s\n", tmp->cid_name);
15322          ast_cli(a->fd, "Mailbox: %s\n", S_OR(tmp->mailbox, "none"));
15323          if (tmp->vars) {
15324             struct ast_variable *v;
15325             ast_cli(a->fd, "Variables:\n");
15326             for (v = tmp->vars ; v ; v = v->next)
15327                ast_cli(a->fd, "       %s = %s\n", v->name, v->value);
15328          }
15329          ast_cli(a->fd, "Destroy: %d\n", tmp->destroy);
15330          ast_cli(a->fd, "InAlarm: %d\n", tmp->inalarm);
15331          ast_cli(a->fd, "Signalling Type: %s\n", sig2str(tmp->sig));
15332          ast_cli(a->fd, "Radio: %d\n", tmp->radio);
15333          ast_cli(a->fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
15334          ast_cli(a->fd, "Real: %s%s%s\n", tmp->subs[SUB_REAL].owner ? tmp->subs[SUB_REAL].owner->name : "<None>", tmp->subs[SUB_REAL].inthreeway ? " (Confed)" : "", tmp->subs[SUB_REAL].linear ? " (Linear)" : "");
15335          ast_cli(a->fd, "Callwait: %s%s%s\n", tmp->subs[SUB_CALLWAIT].owner ? tmp->subs[SUB_CALLWAIT].owner->name : "<None>", tmp->subs[SUB_CALLWAIT].inthreeway ? " (Confed)" : "", tmp->subs[SUB_CALLWAIT].linear ? " (Linear)" : "");
15336          ast_cli(a->fd, "Threeway: %s%s%s\n", tmp->subs[SUB_THREEWAY].owner ? tmp->subs[SUB_THREEWAY].owner->name : "<None>", tmp->subs[SUB_THREEWAY].inthreeway ? " (Confed)" : "", tmp->subs[SUB_THREEWAY].linear ? " (Linear)" : "");
15337          ast_cli(a->fd, "Confno: %d\n", tmp->confno);
15338          ast_cli(a->fd, "Propagated Conference: %d\n", tmp->propconfno);
15339          ast_cli(a->fd, "Real in conference: %d\n", tmp->inconference);
15340          ast_cli(a->fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
15341          ast_cli(a->fd, "Busy Detection: %s\n", tmp->busydetect ? "yes" : "no");
15342          if (tmp->busydetect) {
15343 #if defined(BUSYDETECT_TONEONLY)
15344             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_TONEONLY\n");
15345 #elif defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
15346             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_COMPARE_TONE_AND_SILENCE\n");
15347 #endif
15348 #ifdef BUSYDETECT_DEBUG
15349             ast_cli(a->fd, "    Busy Detector Debug: Enabled\n");
15350 #endif
15351             ast_cli(a->fd, "    Busy Count: %d\n", tmp->busycount);
15352             ast_cli(a->fd, "    Busy Pattern: %d,%d\n", tmp->busy_tonelength, tmp->busy_quietlength);
15353          }
15354          ast_cli(a->fd, "TDD: %s\n", tmp->tdd ? "yes" : "no");
15355          ast_cli(a->fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
15356          ast_cli(a->fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
15357          ast_cli(a->fd, "Default law: %s\n", tmp->law_default == DAHDI_LAW_MULAW ? "ulaw" : tmp->law_default == DAHDI_LAW_ALAW ? "alaw" : "unknown");
15358          ast_cli(a->fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
15359          ast_cli(a->fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
15360          ast_cli(a->fd, "Gains (RX/TX): %.2f/%.2f\n", tmp->rxgain, tmp->txgain);
15361          ast_cli(a->fd, "Dynamic Range Compression (RX/TX): %.2f/%.2f\n", tmp->rxdrc, tmp->txdrc);
15362          ast_cli(a->fd, "DND: %s\n", dahdi_dnd(tmp, -1) ? "yes" : "no");
15363          ast_cli(a->fd, "Echo Cancellation:\n");
15364 
15365          if (tmp->echocancel.head.tap_length) {
15366             ast_cli(a->fd, "\t%d taps\n", tmp->echocancel.head.tap_length);
15367             for (x = 0; x < tmp->echocancel.head.param_count; x++) {
15368                ast_cli(a->fd, "\t\t%s: %ud\n", tmp->echocancel.params[x].name, tmp->echocancel.params[x].value);
15369             }
15370             ast_cli(a->fd, "\t%scurrently %s\n", tmp->echocanbridged ? "" : "(unless TDM bridged) ", tmp->echocanon ? "ON" : "OFF");
15371          } else {
15372             ast_cli(a->fd, "\tnone\n");
15373          }
15374          ast_cli(a->fd, "Wait for dialtone: %dms\n", tmp->waitfordialtone);
15375          if (tmp->master)
15376             ast_cli(a->fd, "Master Channel: %d\n", tmp->master->channel);
15377          for (x = 0; x < MAX_SLAVES; x++) {
15378             if (tmp->slaves[x])
15379                ast_cli(a->fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
15380          }
15381 #ifdef HAVE_OPENR2
15382          if (tmp->mfcr2) {
15383             char calldir[OR2_MAX_PATH];
15384             openr2_context_t *r2context = openr2_chan_get_context(tmp->r2chan);
15385             openr2_variant_t r2variant = openr2_context_get_variant(r2context);
15386             ast_cli(a->fd, "MFC/R2 MF State: %s\n", openr2_chan_get_mf_state_string(tmp->r2chan));
15387             ast_cli(a->fd, "MFC/R2 MF Group: %s\n", openr2_chan_get_mf_group_string(tmp->r2chan));
15388             ast_cli(a->fd, "MFC/R2 State: %s\n", openr2_chan_get_r2_state_string(tmp->r2chan));
15389             ast_cli(a->fd, "MFC/R2 Call State: %s\n", openr2_chan_get_call_state_string(tmp->r2chan));
15390             ast_cli(a->fd, "MFC/R2 Call Files Enabled: %s\n", openr2_chan_get_call_files_enabled(tmp->r2chan) ? "Yes" : "No");
15391             ast_cli(a->fd, "MFC/R2 Variant: %s\n", openr2_proto_get_variant_string(r2variant));
15392             ast_cli(a->fd, "MFC/R2 Max ANI: %d\n", openr2_context_get_max_ani(r2context));
15393             ast_cli(a->fd, "MFC/R2 Max DNIS: %d\n", openr2_context_get_max_dnis(r2context));
15394             ast_cli(a->fd, "MFC/R2 Get ANI First: %s\n", openr2_context_get_ani_first(r2context) ? "Yes" : "No");
15395 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
15396             ast_cli(a->fd, "MFC/R2 Skip Category Request: %s\n", openr2_context_get_skip_category_request(r2context) ? "Yes" : "No");
15397 #endif
15398             ast_cli(a->fd, "MFC/R2 Immediate Accept: %s\n", openr2_context_get_immediate_accept(r2context) ? "Yes" : "No");
15399             ast_cli(a->fd, "MFC/R2 Accept on Offer: %s\n", tmp->mfcr2_accept_on_offer ? "Yes" : "No");
15400             ast_cli(a->fd, "MFC/R2 Charge Calls: %s\n", tmp->mfcr2_charge_calls ? "Yes" : "No");
15401             ast_cli(a->fd, "MFC/R2 Allow Collect Calls: %s\n", tmp->mfcr2_allow_collect_calls ? "Yes" : "No");
15402             ast_cli(a->fd, "MFC/R2 Forced Release: %s\n", tmp->mfcr2_forced_release ? "Yes" : "No");
15403             ast_cli(a->fd, "MFC/R2 MF Back Timeout: %dms\n", openr2_context_get_mf_back_timeout(r2context));
15404             ast_cli(a->fd, "MFC/R2 R2 Metering Pulse Timeout: %dms\n", openr2_context_get_metering_pulse_timeout(r2context));
15405             ast_cli(a->fd, "MFC/R2 Rx CAS: %s\n", openr2_chan_get_rx_cas_string(tmp->r2chan));
15406             ast_cli(a->fd, "MFC/R2 Tx CAS: %s\n", openr2_chan_get_tx_cas_string(tmp->r2chan));
15407             ast_cli(a->fd, "MFC/R2 MF Tx Signal: %d\n", openr2_chan_get_tx_mf_signal(tmp->r2chan));
15408             ast_cli(a->fd, "MFC/R2 MF Rx Signal: %d\n", openr2_chan_get_rx_mf_signal(tmp->r2chan));
15409             ast_cli(a->fd, "MFC/R2 Call Files Directory: %s\n", openr2_context_get_log_directory(r2context, calldir, sizeof(calldir)));
15410          }
15411 #endif
15412 #if defined(HAVE_SS7)
15413          if (tmp->ss7) {
15414             struct sig_ss7_chan *chan = tmp->sig_pvt;
15415 
15416             ast_cli(a->fd, "CIC: %d\n", chan->cic);
15417          }
15418 #endif   /* defined(HAVE_SS7) */
15419 #ifdef HAVE_PRI
15420          if (tmp->pri) {
15421             struct sig_pri_chan *chan = tmp->sig_pvt;
15422 
15423             ast_cli(a->fd, "PRI Flags: ");
15424             if (chan->resetting != SIG_PRI_RESET_IDLE) {
15425                ast_cli(a->fd, "Resetting=%d ", chan->resetting);
15426             }
15427             if (chan->call)
15428                ast_cli(a->fd, "Call ");
15429             if (chan->allocated) {
15430                ast_cli(a->fd, "Allocated ");
15431             }
15432             ast_cli(a->fd, "\n");
15433             if (tmp->logicalspan)
15434                ast_cli(a->fd, "PRI Logical Span: %d\n", tmp->logicalspan);
15435             else
15436                ast_cli(a->fd, "PRI Logical Span: Implicit\n");
15437          }
15438 #endif
15439          memset(&ci, 0, sizeof(ci));
15440          ps.channo = tmp->channel;
15441          if (tmp->subs[SUB_REAL].dfd > -1) {
15442             memset(&ci, 0, sizeof(ci));
15443             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
15444                ast_cli(a->fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
15445             }
15446             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONFMUTE, &x)) {
15447                ast_cli(a->fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
15448             }
15449             memset(&ps, 0, sizeof(ps));
15450             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
15451                ast_log(LOG_WARNING, "Failed to get parameters on channel %d: %s\n", tmp->channel, strerror(errno));
15452             } else {
15453                ast_cli(a->fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
15454             }
15455          }
15456          ast_mutex_unlock(&iflock);
15457          return CLI_SUCCESS;
15458       }
15459    }
15460    ast_mutex_unlock(&iflock);
15461 
15462    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15463    return CLI_FAILURE;
15464 }
15465 
15466 static char *handle_dahdi_show_cadences(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15467 {
15468    int i, j;
15469    switch (cmd) {
15470    case CLI_INIT:
15471       e->command = "dahdi show cadences";
15472       e->usage =
15473          "Usage: dahdi show cadences\n"
15474          "       Shows all cadences currently defined\n";
15475       return NULL;
15476    case CLI_GENERATE:
15477       return NULL;
15478    }
15479    for (i = 0; i < num_cadence; i++) {
15480       char output[1024];
15481       char tmp[16], tmp2[64];
15482       snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
15483       term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
15484 
15485       for (j = 0; j < 16; j++) {
15486          if (cadences[i].ringcadence[j] == 0)
15487             break;
15488          snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
15489          if (cidrings[i] * 2 - 1 == j)
15490             term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
15491          else
15492             term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
15493          if (j != 0)
15494             strncat(output, ",", sizeof(output) - strlen(output) - 1);
15495          strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
15496       }
15497       ast_cli(a->fd,"%s\n",output);
15498    }
15499    return CLI_SUCCESS;
15500 }
15501 
15502 /* Based on irqmiss.c */
15503 static char *dahdi_show_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15504 {
15505    #define FORMAT "%-40.40s %-7.7s %-6d %-6d %-6d %-3.3s %-4.4s %-8.8s %s\n"
15506    #define FORMAT2 "%-40.40s %-7.7s %-6.6s %-6.6s %-6.6s %-3.3s %-4.4s %-8.8s %s\n"
15507    int span;
15508    int res;
15509    char alarmstr[50];
15510 
15511    int ctl;
15512    struct dahdi_spaninfo s;
15513 
15514    switch (cmd) {
15515    case CLI_INIT:
15516       e->command = "dahdi show status";
15517       e->usage =
15518          "Usage: dahdi show status\n"
15519          "       Shows a list of DAHDI cards with status\n";
15520       return NULL;
15521    case CLI_GENERATE:
15522       return NULL;
15523    }
15524    ctl = open("/dev/dahdi/ctl", O_RDWR);
15525    if (ctl < 0) {
15526       ast_cli(a->fd, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
15527       return CLI_FAILURE;
15528    }
15529    ast_cli(a->fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC", "Framing", "Coding", "Options", "LBO");
15530 
15531    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
15532       s.spanno = span;
15533       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
15534       if (res) {
15535          continue;
15536       }
15537       alarmstr[0] = '\0';
15538       if (s.alarms > 0) {
15539          if (s.alarms & DAHDI_ALARM_BLUE)
15540             strcat(alarmstr, "BLU/");
15541          if (s.alarms & DAHDI_ALARM_YELLOW)
15542             strcat(alarmstr, "YEL/");
15543          if (s.alarms & DAHDI_ALARM_RED)
15544             strcat(alarmstr, "RED/");
15545          if (s.alarms & DAHDI_ALARM_LOOPBACK)
15546             strcat(alarmstr, "LB/");
15547          if (s.alarms & DAHDI_ALARM_RECOVER)
15548             strcat(alarmstr, "REC/");
15549          if (s.alarms & DAHDI_ALARM_NOTOPEN)
15550             strcat(alarmstr, "NOP/");
15551          if (!strlen(alarmstr))
15552             strcat(alarmstr, "UUU/");
15553          if (strlen(alarmstr)) {
15554             /* Strip trailing / */
15555             alarmstr[strlen(alarmstr) - 1] = '\0';
15556          }
15557       } else {
15558          if (s.numchans)
15559             strcpy(alarmstr, "OK");
15560          else
15561             strcpy(alarmstr, "UNCONFIGURED");
15562       }
15563 
15564       ast_cli(a->fd, FORMAT, s.desc, alarmstr, s.irqmisses, s.bpvcount, s.crc4count,
15565          s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
15566          s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
15567          s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
15568          "CAS",
15569          s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
15570          s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
15571          s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
15572          "Unk",
15573          s.lineconfig & DAHDI_CONFIG_CRC4 ?
15574             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
15575             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "",
15576          lbostr[s.lbo]
15577          );
15578    }
15579    close(ctl);
15580 
15581    return CLI_SUCCESS;
15582 #undef FORMAT
15583 #undef FORMAT2
15584 }
15585 
15586 static char *dahdi_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15587 {
15588    int pseudo_fd = -1;
15589    struct dahdi_versioninfo vi;
15590 
15591    switch (cmd) {
15592    case CLI_INIT:
15593       e->command = "dahdi show version";
15594       e->usage =
15595          "Usage: dahdi show version\n"
15596          "       Shows the DAHDI version in use\n";
15597       return NULL;
15598    case CLI_GENERATE:
15599       return NULL;
15600    }
15601    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
15602       ast_cli(a->fd, "Failed to open control file to get version.\n");
15603       return CLI_SUCCESS;
15604    }
15605 
15606    strcpy(vi.version, "Unknown");
15607    strcpy(vi.echo_canceller, "Unknown");
15608 
15609    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi))
15610       ast_cli(a->fd, "Failed to get DAHDI version: %s\n", strerror(errno));
15611    else
15612       ast_cli(a->fd, "DAHDI Version: %s Echo Canceller: %s\n", vi.version, vi.echo_canceller);
15613 
15614    close(pseudo_fd);
15615 
15616    return CLI_SUCCESS;
15617 }
15618 
15619 static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15620 {
15621    int channel;
15622    int gain;
15623    int tx;
15624    struct dahdi_hwgain hwgain;
15625    struct dahdi_pvt *tmp = NULL;
15626 
15627    switch (cmd) {
15628    case CLI_INIT:
15629       e->command = "dahdi set hwgain";
15630       e->usage =
15631          "Usage: dahdi set hwgain <rx|tx> <chan#> <gain>\n"
15632          "  Sets the hardware gain on a a given channel, overriding the\n"
15633          "   value provided at module loadtime, whether the channel is in\n"
15634          "   use or not.  Changes take effect immediately.\n"
15635          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15636          "   <chan num> is the channel number relative to the device\n"
15637          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15638       return NULL;
15639    case CLI_GENERATE:
15640       return NULL;
15641    }
15642 
15643    if (a->argc != 6)
15644       return CLI_SHOWUSAGE;
15645 
15646    if (!strcasecmp("rx", a->argv[3]))
15647       tx = 0; /* rx */
15648    else if (!strcasecmp("tx", a->argv[3]))
15649       tx = 1; /* tx */
15650    else
15651       return CLI_SHOWUSAGE;
15652 
15653    channel = atoi(a->argv[4]);
15654    gain = atof(a->argv[5])*10.0;
15655 
15656    ast_mutex_lock(&iflock);
15657 
15658    for (tmp = iflist; tmp; tmp = tmp->next) {
15659 
15660       if (tmp->channel != channel)
15661          continue;
15662 
15663       if (tmp->subs[SUB_REAL].dfd == -1)
15664          break;
15665 
15666       hwgain.newgain = gain;
15667       hwgain.tx = tx;
15668       if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_HWGAIN, &hwgain) < 0) {
15669          ast_cli(a->fd, "Unable to set the hardware gain for channel %d: %s\n", channel, strerror(errno));
15670          ast_mutex_unlock(&iflock);
15671          return CLI_FAILURE;
15672       }
15673       ast_cli(a->fd, "hardware %s gain set to %d (%.1f dB) on channel %d\n",
15674          tx ? "tx" : "rx", gain, (float)gain/10.0, channel);
15675       break;
15676    }
15677 
15678    ast_mutex_unlock(&iflock);
15679 
15680    if (tmp)
15681       return CLI_SUCCESS;
15682 
15683    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15684    return CLI_FAILURE;
15685 
15686 }
15687 
15688 static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15689 {
15690    int channel;
15691    float gain;
15692    int tx;
15693    int res;
15694    struct dahdi_pvt *tmp = NULL;
15695 
15696    switch (cmd) {
15697    case CLI_INIT:
15698       e->command = "dahdi set swgain";
15699       e->usage =
15700          "Usage: dahdi set swgain <rx|tx> <chan#> <gain>\n"
15701          "  Sets the software gain on a a given channel, overriding the\n"
15702          "   value provided at module loadtime, whether the channel is in\n"
15703          "   use or not.  Changes take effect immediately.\n"
15704          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15705          "   <chan num> is the channel number relative to the device\n"
15706          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15707       return NULL;
15708    case CLI_GENERATE:
15709       return NULL;
15710    }
15711 
15712    if (a->argc != 6)
15713       return CLI_SHOWUSAGE;
15714 
15715    if (!strcasecmp("rx", a->argv[3]))
15716       tx = 0; /* rx */
15717    else if (!strcasecmp("tx", a->argv[3]))
15718       tx = 1; /* tx */
15719    else
15720       return CLI_SHOWUSAGE;
15721 
15722    channel = atoi(a->argv[4]);
15723    gain = atof(a->argv[5]);
15724 
15725    ast_mutex_lock(&iflock);
15726    for (tmp = iflist; tmp; tmp = tmp->next) {
15727 
15728       if (tmp->channel != channel)
15729          continue;
15730 
15731       if (tmp->subs[SUB_REAL].dfd == -1)
15732          break;
15733 
15734       if (tx)
15735          res = set_actual_txgain(tmp->subs[SUB_REAL].dfd, gain, tmp->txdrc, tmp->law);
15736       else
15737          res = set_actual_rxgain(tmp->subs[SUB_REAL].dfd, gain, tmp->rxdrc, tmp->law);
15738 
15739       if (res) {
15740          ast_cli(a->fd, "Unable to set the software gain for channel %d\n", channel);
15741          ast_mutex_unlock(&iflock);
15742          return CLI_FAILURE;
15743       }
15744 
15745       ast_cli(a->fd, "software %s gain set to %.1f on channel %d\n",
15746          tx ? "tx" : "rx", gain, channel);
15747       break;
15748    }
15749    ast_mutex_unlock(&iflock);
15750 
15751    if (tmp)
15752       return CLI_SUCCESS;
15753 
15754    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15755    return CLI_FAILURE;
15756 
15757 }
15758 
15759 static char *dahdi_set_dnd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15760 {
15761    int channel;
15762    int on;
15763    struct dahdi_pvt *dahdi_chan = NULL;
15764 
15765    switch (cmd) {
15766    case CLI_INIT:
15767       e->command = "dahdi set dnd";
15768       e->usage =
15769          "Usage: dahdi set dnd <chan#> <on|off>\n"
15770          "  Sets/resets DND (Do Not Disturb) mode on a channel.\n"
15771          "  Changes take effect immediately.\n"
15772          "  <chan num> is the channel number\n"
15773          "  <on|off> Enable or disable DND mode?\n"
15774          ;
15775       return NULL;
15776    case CLI_GENERATE:
15777       return NULL;
15778    }
15779 
15780    if (a->argc != 5)
15781       return CLI_SHOWUSAGE;
15782 
15783    if ((channel = atoi(a->argv[3])) <= 0) {
15784       ast_cli(a->fd, "Expected channel number, got '%s'\n", a->argv[3]);
15785       return CLI_SHOWUSAGE;
15786    }
15787 
15788    if (ast_true(a->argv[4]))
15789       on = 1;
15790    else if (ast_false(a->argv[4]))
15791       on = 0;
15792    else {
15793       ast_cli(a->fd, "Expected 'on' or 'off', got '%s'\n", a->argv[4]);
15794       return CLI_SHOWUSAGE;
15795    }
15796 
15797    ast_mutex_lock(&iflock);
15798    for (dahdi_chan = iflist; dahdi_chan; dahdi_chan = dahdi_chan->next) {
15799       if (dahdi_chan->channel != channel)
15800          continue;
15801 
15802       /* Found the channel. Actually set it */
15803       dahdi_dnd(dahdi_chan, on);
15804       break;
15805    }
15806    ast_mutex_unlock(&iflock);
15807 
15808    if (!dahdi_chan) {
15809       ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15810       return CLI_FAILURE;
15811    }
15812 
15813    return CLI_SUCCESS;
15814 }
15815 
15816 static struct ast_cli_entry dahdi_cli[] = {
15817    AST_CLI_DEFINE(handle_dahdi_show_cadences, "List cadences"),
15818    AST_CLI_DEFINE(dahdi_show_channels, "Show active DAHDI channels"),
15819    AST_CLI_DEFINE(dahdi_show_channel, "Show information on a channel"),
15820    AST_CLI_DEFINE(dahdi_destroy_channel, "Destroy a channel"),
15821    AST_CLI_DEFINE(dahdi_restart_cmd, "Fully restart DAHDI channels"),
15822    AST_CLI_DEFINE(dahdi_show_status, "Show all DAHDI cards status"),
15823    AST_CLI_DEFINE(dahdi_show_version, "Show the DAHDI version in use"),
15824    AST_CLI_DEFINE(dahdi_set_hwgain, "Set hardware gain on a channel"),
15825    AST_CLI_DEFINE(dahdi_set_swgain, "Set software gain on a channel"),
15826    AST_CLI_DEFINE(dahdi_set_dnd, "Sets/resets DND (Do Not Disturb) mode on a channel"),
15827 };
15828 
15829 #define TRANSFER  0
15830 #define HANGUP    1
15831 
15832 static int dahdi_fake_event(struct dahdi_pvt *p, int mode)
15833 {
15834    if (p) {
15835       switch (mode) {
15836       case TRANSFER:
15837          p->fake_event = DAHDI_EVENT_WINKFLASH;
15838          break;
15839       case HANGUP:
15840          p->fake_event = DAHDI_EVENT_ONHOOK;
15841          break;
15842       default:
15843          ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
15844       }
15845    }
15846    return 0;
15847 }
15848 static struct dahdi_pvt *find_channel(int channel)
15849 {
15850    struct dahdi_pvt *p;
15851 
15852    ast_mutex_lock(&iflock);
15853    for (p = iflist; p; p = p->next) {
15854       if (p->channel == channel) {
15855          break;
15856       }
15857    }
15858    ast_mutex_unlock(&iflock);
15859    return p;
15860 }
15861 
15862 /*!
15863  * \internal
15864  * \brief Get private struct using given numeric channel string.
15865  *
15866  * \param channel Numeric channel number string get private struct.
15867  *
15868  * \retval pvt on success.
15869  * \retval NULL on error.
15870  */
15871 static struct dahdi_pvt *find_channel_from_str(const char *channel)
15872 {
15873    int chan_num;
15874 
15875    if (sscanf(channel, "%30d", &chan_num) != 1) {
15876       /* Not numeric string. */
15877       return NULL;
15878    }
15879 
15880    return find_channel(chan_num);
15881 }
15882 
15883 static int action_dahdidndon(struct mansession *s, const struct message *m)
15884 {
15885    struct dahdi_pvt *p;
15886    const char *channel = astman_get_header(m, "DAHDIChannel");
15887 
15888    if (ast_strlen_zero(channel)) {
15889       astman_send_error(s, m, "No channel specified");
15890       return 0;
15891    }
15892    p = find_channel_from_str(channel);
15893    if (!p) {
15894       astman_send_error(s, m, "No such channel");
15895       return 0;
15896    }
15897    dahdi_dnd(p, 1);
15898    astman_send_ack(s, m, "DND Enabled");
15899    return 0;
15900 }
15901 
15902 static int action_dahdidndoff(struct mansession *s, const struct message *m)
15903 {
15904    struct dahdi_pvt *p;
15905    const char *channel = astman_get_header(m, "DAHDIChannel");
15906 
15907    if (ast_strlen_zero(channel)) {
15908       astman_send_error(s, m, "No channel specified");
15909       return 0;
15910    }
15911    p = find_channel_from_str(channel);
15912    if (!p) {
15913       astman_send_error(s, m, "No such channel");
15914       return 0;
15915    }
15916    dahdi_dnd(p, 0);
15917    astman_send_ack(s, m, "DND Disabled");
15918    return 0;
15919 }
15920 
15921 static int action_transfer(struct mansession *s, const struct message *m)
15922 {
15923    struct dahdi_pvt *p;
15924    const char *channel = astman_get_header(m, "DAHDIChannel");
15925 
15926    if (ast_strlen_zero(channel)) {
15927       astman_send_error(s, m, "No channel specified");
15928       return 0;
15929    }
15930    p = find_channel_from_str(channel);
15931    if (!p) {
15932       astman_send_error(s, m, "No such channel");
15933       return 0;
15934    }
15935    if (!analog_lib_handles(p->sig, 0, 0)) {
15936       astman_send_error(s, m, "Channel signaling is not analog");
15937       return 0;
15938    }
15939    dahdi_fake_event(p,TRANSFER);
15940    astman_send_ack(s, m, "DAHDITransfer");
15941    return 0;
15942 }
15943 
15944 static int action_transferhangup(struct mansession *s, const struct message *m)
15945 {
15946    struct dahdi_pvt *p;
15947    const char *channel = astman_get_header(m, "DAHDIChannel");
15948 
15949    if (ast_strlen_zero(channel)) {
15950       astman_send_error(s, m, "No channel specified");
15951       return 0;
15952    }
15953    p = find_channel_from_str(channel);
15954    if (!p) {
15955       astman_send_error(s, m, "No such channel");
15956       return 0;
15957    }
15958    if (!analog_lib_handles(p->sig, 0, 0)) {
15959       astman_send_error(s, m, "Channel signaling is not analog");
15960       return 0;
15961    }
15962    dahdi_fake_event(p,HANGUP);
15963    astman_send_ack(s, m, "DAHDIHangup");
15964    return 0;
15965 }
15966 
15967 static int action_dahdidialoffhook(struct mansession *s, const struct message *m)
15968 {
15969    struct dahdi_pvt *p;
15970    const char *channel = astman_get_header(m, "DAHDIChannel");
15971    const char *number = astman_get_header(m, "Number");
15972    int i;
15973 
15974    if (ast_strlen_zero(channel)) {
15975       astman_send_error(s, m, "No channel specified");
15976       return 0;
15977    }
15978    if (ast_strlen_zero(number)) {
15979       astman_send_error(s, m, "No number specified");
15980       return 0;
15981    }
15982    p = find_channel_from_str(channel);
15983    if (!p) {
15984       astman_send_error(s, m, "No such channel");
15985       return 0;
15986    }
15987    if (!p->owner) {
15988       astman_send_error(s, m, "Channel does not have it's owner");
15989       return 0;
15990    }
15991    for (i = 0; i < strlen(number); i++) {
15992       struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = number[i] };
15993       dahdi_queue_frame(p, &f);
15994    }
15995    astman_send_ack(s, m, "DAHDIDialOffhook");
15996    return 0;
15997 }
15998 
15999 static int action_dahdishowchannels(struct mansession *s, const struct message *m)
16000 {
16001    struct dahdi_pvt *tmp = NULL;
16002    const char *id = astman_get_header(m, "ActionID");
16003    const char *dahdichannel = astman_get_header(m, "DAHDIChannel");
16004    char idText[256] = "";
16005    int channels = 0;
16006    int dahdichanquery;
16007 
16008    if (!dahdichannel || sscanf(dahdichannel, "%30d", &dahdichanquery) != 1) {
16009       /* Not numeric string. */
16010       dahdichanquery = -1;
16011    }
16012 
16013    astman_send_ack(s, m, "DAHDI channel status will follow");
16014    if (!ast_strlen_zero(id))
16015       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
16016 
16017    ast_mutex_lock(&iflock);
16018 
16019    for (tmp = iflist; tmp; tmp = tmp->next) {
16020       if (tmp->channel > 0) {
16021          int alm;
16022 
16023          /* If a specific channel is queried for, only deliver status for that channel */
16024          if (dahdichanquery > 0 && tmp->channel != dahdichanquery)
16025             continue;
16026 
16027          alm = get_alarms(tmp);
16028          channels++;
16029          if (tmp->owner) {
16030             /* Add data if we have a current call */
16031             astman_append(s,
16032                "Event: DAHDIShowChannels\r\n"
16033                "DAHDIChannel: %d\r\n"
16034                "Channel: %s\r\n"
16035                "Uniqueid: %s\r\n"
16036                "AccountCode: %s\r\n"
16037                "Signalling: %s\r\n"
16038                "SignallingCode: %d\r\n"
16039                "Context: %s\r\n"
16040                "DND: %s\r\n"
16041                "Alarm: %s\r\n"
16042                "%s"
16043                "\r\n",
16044                tmp->channel,
16045                tmp->owner->name,
16046                tmp->owner->uniqueid,
16047                tmp->owner->accountcode,
16048                sig2str(tmp->sig),
16049                tmp->sig,
16050                tmp->context,
16051                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
16052                alarm2str(alm), idText);
16053          } else {
16054             astman_append(s,
16055                "Event: DAHDIShowChannels\r\n"
16056                "DAHDIChannel: %d\r\n"
16057                "Signalling: %s\r\n"
16058                "SignallingCode: %d\r\n"
16059                "Context: %s\r\n"
16060                "DND: %s\r\n"
16061                "Alarm: %s\r\n"
16062                "%s"
16063                "\r\n",
16064                tmp->channel, sig2str(tmp->sig), tmp->sig,
16065                tmp->context,
16066                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
16067                alarm2str(alm), idText);
16068          }
16069       }
16070    }
16071 
16072    ast_mutex_unlock(&iflock);
16073 
16074    astman_append(s,
16075       "Event: DAHDIShowChannelsComplete\r\n"
16076       "%s"
16077       "Items: %d\r\n"
16078       "\r\n",
16079       idText,
16080       channels);
16081    return 0;
16082 }
16083 
16084 #if defined(HAVE_SS7)
16085 static int linkset_addsigchan(int sigchan)
16086 {
16087    struct dahdi_ss7 *link;
16088    int res;
16089    int curfd;
16090    struct dahdi_params params;
16091    struct dahdi_bufferinfo bi;
16092    struct dahdi_spaninfo si;
16093 
16094    if (sigchan < 0) {
16095       ast_log(LOG_ERROR, "Invalid sigchan!\n");
16096       return -1;
16097    }
16098    if (cur_ss7type < 0) {
16099       ast_log(LOG_ERROR, "Unspecified or invalid ss7type\n");
16100       return -1;
16101    }
16102    if (cur_pointcode < 0) {
16103       ast_log(LOG_ERROR, "Unspecified pointcode!\n");
16104       return -1;
16105    }
16106    if (cur_adjpointcode < 0) {
16107       ast_log(LOG_ERROR, "Unspecified adjpointcode!\n");
16108       return -1;
16109    }
16110    if (cur_defaultdpc < 0) {
16111       ast_log(LOG_ERROR, "Unspecified defaultdpc!\n");
16112       return -1;
16113    }
16114    if (cur_networkindicator < 0) {
16115       ast_log(LOG_ERROR, "Invalid networkindicator!\n");
16116       return -1;
16117    }
16118    link = ss7_resolve_linkset(cur_linkset);
16119    if (!link) {
16120       ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
16121       return -1;
16122    }
16123    if (link->ss7.numsigchans >= SIG_SS7_NUM_DCHANS) {
16124       ast_log(LOG_ERROR, "Too many sigchans on linkset %d\n", cur_linkset);
16125       return -1;
16126    }
16127 
16128    curfd = link->ss7.numsigchans;
16129 
16130    /* Open signaling channel */
16131    link->ss7.fds[curfd] = open("/dev/dahdi/channel", O_RDWR, 0600);
16132    if (link->ss7.fds[curfd] < 0) {
16133       ast_log(LOG_ERROR, "Unable to open SS7 sigchan %d (%s)\n", sigchan,
16134          strerror(errno));
16135       return -1;
16136    }
16137    if (ioctl(link->ss7.fds[curfd], DAHDI_SPECIFY, &sigchan) == -1) {
16138       dahdi_close_ss7_fd(link, curfd);
16139       ast_log(LOG_ERROR, "Unable to specify SS7 sigchan %d (%s)\n", sigchan,
16140          strerror(errno));
16141       return -1;
16142    }
16143 
16144    /* Get signaling channel parameters */
16145    memset(&params, 0, sizeof(params));
16146    res = ioctl(link->ss7.fds[curfd], DAHDI_GET_PARAMS, &params);
16147    if (res) {
16148       dahdi_close_ss7_fd(link, curfd);
16149       ast_log(LOG_ERROR, "Unable to get parameters for sigchan %d (%s)\n", sigchan,
16150          strerror(errno));
16151       return -1;
16152    }
16153    if (params.sigtype != DAHDI_SIG_HDLCFCS
16154       && params.sigtype != DAHDI_SIG_HARDHDLC
16155       && params.sigtype != DAHDI_SIG_MTP2) {
16156       dahdi_close_ss7_fd(link, curfd);
16157       ast_log(LOG_ERROR, "sigchan %d is not in HDLC/FCS mode.\n", sigchan);
16158       return -1;
16159    }
16160 
16161    /* Set signaling channel buffer policy. */
16162    memset(&bi, 0, sizeof(bi));
16163    bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
16164    bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
16165    bi.numbufs = 32;
16166    bi.bufsize = 512;
16167    if (ioctl(link->ss7.fds[curfd], DAHDI_SET_BUFINFO, &bi)) {
16168       ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n",
16169          sigchan, strerror(errno));
16170       dahdi_close_ss7_fd(link, curfd);
16171       return -1;
16172    }
16173 
16174    /* Get current signaling channel alarm status. */
16175    memset(&si, 0, sizeof(si));
16176    res = ioctl(link->ss7.fds[curfd], DAHDI_SPANSTAT, &si);
16177    if (res) {
16178       dahdi_close_ss7_fd(link, curfd);
16179       ast_log(LOG_ERROR, "Unable to get span state for sigchan %d (%s)\n", sigchan,
16180          strerror(errno));
16181    }
16182 
16183    res = sig_ss7_add_sigchan(&link->ss7, curfd, cur_ss7type,
16184       (params.sigtype == DAHDI_SIG_MTP2)
16185          ? SS7_TRANSPORT_DAHDIMTP2
16186          : SS7_TRANSPORT_DAHDIDCHAN,
16187       si.alarms, cur_networkindicator, cur_pointcode, cur_adjpointcode);
16188    if (res) {
16189       dahdi_close_ss7_fd(link, curfd);
16190       return -1;
16191    }
16192 
16193    ++link->ss7.numsigchans;
16194 
16195    return 0;
16196 }
16197 #endif   /* defined(HAVE_SS7) */
16198 
16199 #if defined(HAVE_SS7)
16200 static char *handle_ss7_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16201 {
16202    int span;
16203    switch (cmd) {
16204    case CLI_INIT:
16205       e->command = "ss7 set debug {on|off} linkset";
16206       e->usage =
16207          "Usage: ss7 set debug {on|off} linkset <linkset>\n"
16208          "       Enables debugging on a given SS7 linkset\n";
16209       return NULL;
16210    case CLI_GENERATE:
16211       return NULL;
16212    }
16213    if (a->argc < 6)
16214       return CLI_SHOWUSAGE;
16215    span = atoi(a->argv[5]);
16216    if ((span < 1) || (span > NUM_SPANS)) {
16217       ast_cli(a->fd, "Invalid linkset %s.  Should be a number from %d to %d\n", a->argv[5], 1, NUM_SPANS);
16218       return CLI_SUCCESS;
16219    }
16220    if (!linksets[span-1].ss7.ss7) {
16221       ast_cli(a->fd, "No SS7 running on linkset %d\n", span);
16222    } else {
16223       if (!strcasecmp(a->argv[3], "on")) {
16224          linksets[span - 1].ss7.debug = 1;
16225          ss7_set_debug(linksets[span-1].ss7.ss7, SIG_SS7_DEBUG);
16226          ast_cli(a->fd, "Enabled debugging on linkset %d\n", span);
16227       } else {
16228          linksets[span - 1].ss7.debug = 0;
16229          ss7_set_debug(linksets[span-1].ss7.ss7, 0);
16230          ast_cli(a->fd, "Disabled debugging on linkset %d\n", span);
16231       }
16232    }
16233 
16234    return CLI_SUCCESS;
16235 }
16236 #endif   /* defined(HAVE_SS7) */
16237 
16238 #if defined(HAVE_SS7)
16239 static char *handle_ss7_block_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16240 {
16241    int linkset, cic;
16242    int blocked = -1, i;
16243    switch (cmd) {
16244    case CLI_INIT:
16245       e->command = "ss7 block cic";
16246       e->usage =
16247          "Usage: ss7 block cic <linkset> <CIC>\n"
16248          "       Sends a remote blocking request for the given CIC on the specified linkset\n";
16249       return NULL;
16250    case CLI_GENERATE:
16251       return NULL;
16252    }
16253    if (a->argc == 5)
16254       linkset = atoi(a->argv[3]);
16255    else
16256       return CLI_SHOWUSAGE;
16257 
16258    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16259       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16260       return CLI_SUCCESS;
16261    }
16262 
16263    if (!linksets[linkset-1].ss7.ss7) {
16264       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16265       return CLI_SUCCESS;
16266    }
16267 
16268    cic = atoi(a->argv[4]);
16269 
16270    if (cic < 1) {
16271       ast_cli(a->fd, "Invalid CIC specified!\n");
16272       return CLI_SUCCESS;
16273    }
16274 
16275    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16276       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
16277          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
16278          if (!blocked) {
16279             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16280             isup_blo(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16281             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16282          }
16283       }
16284    }
16285 
16286    if (blocked < 0) {
16287       ast_cli(a->fd, "Invalid CIC specified!\n");
16288       return CLI_SUCCESS;
16289    }
16290 
16291    if (!blocked)
16292       ast_cli(a->fd, "Sent blocking request for linkset %d on CIC %d\n", linkset, cic);
16293    else
16294       ast_cli(a->fd, "CIC %d already locally blocked\n", cic);
16295 
16296    /* Break poll on the linkset so it sends our messages */
16297    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16298 
16299    return CLI_SUCCESS;
16300 }
16301 #endif   /* defined(HAVE_SS7) */
16302 
16303 #if defined(HAVE_SS7)
16304 static char *handle_ss7_block_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16305 {
16306    int linkset;
16307    int i;
16308    switch (cmd) {
16309    case CLI_INIT:
16310       e->command = "ss7 block linkset";
16311       e->usage =
16312          "Usage: ss7 block linkset <linkset number>\n"
16313          "       Sends a remote blocking request for all CICs on the given linkset\n";
16314       return NULL;
16315    case CLI_GENERATE:
16316       return NULL;
16317    }
16318    if (a->argc == 4)
16319       linkset = atoi(a->argv[3]);
16320    else
16321       return CLI_SHOWUSAGE;
16322 
16323    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16324       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16325       return CLI_SUCCESS;
16326    }
16327 
16328    if (!linksets[linkset-1].ss7.ss7) {
16329       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16330       return CLI_SUCCESS;
16331    }
16332 
16333    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16334       ast_cli(a->fd, "Sending remote blocking request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
16335       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16336       isup_blo(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16337       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16338    }
16339 
16340    /* Break poll on the linkset so it sends our messages */
16341    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16342 
16343    return CLI_SUCCESS;
16344 }
16345 #endif   /* defined(HAVE_SS7) */
16346 
16347 #if defined(HAVE_SS7)
16348 static char *handle_ss7_unblock_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16349 {
16350    int linkset, cic;
16351    int i, blocked = -1;
16352    switch (cmd) {
16353    case CLI_INIT:
16354       e->command = "ss7 unblock cic";
16355       e->usage =
16356          "Usage: ss7 unblock cic <linkset> <CIC>\n"
16357          "       Sends a remote unblocking request for the given CIC on the specified linkset\n";
16358       return NULL;
16359    case CLI_GENERATE:
16360       return NULL;
16361    }
16362 
16363    if (a->argc == 5)
16364       linkset = atoi(a->argv[3]);
16365    else
16366       return CLI_SHOWUSAGE;
16367 
16368    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16369       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16370       return CLI_SUCCESS;
16371    }
16372 
16373    if (!linksets[linkset-1].ss7.ss7) {
16374       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16375       return CLI_SUCCESS;
16376    }
16377 
16378    cic = atoi(a->argv[4]);
16379 
16380    if (cic < 1) {
16381       ast_cli(a->fd, "Invalid CIC specified!\n");
16382       return CLI_SUCCESS;
16383    }
16384 
16385    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16386       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
16387          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
16388          if (blocked) {
16389             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16390             isup_ubl(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16391             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16392          }
16393       }
16394    }
16395 
16396    if (blocked > 0)
16397       ast_cli(a->fd, "Sent unblocking request for linkset %d on CIC %d\n", linkset, cic);
16398 
16399    /* Break poll on the linkset so it sends our messages */
16400    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16401 
16402    return CLI_SUCCESS;
16403 }
16404 #endif   /* defined(HAVE_SS7) */
16405 
16406 #if defined(HAVE_SS7)
16407 static char *handle_ss7_unblock_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16408 {
16409    int linkset;
16410    int i;
16411    switch (cmd) {
16412    case CLI_INIT:
16413       e->command = "ss7 unblock linkset";
16414       e->usage =
16415          "Usage: ss7 unblock linkset <linkset number>\n"
16416          "       Sends a remote unblocking request for all CICs on the specified linkset\n";
16417       return NULL;
16418    case CLI_GENERATE:
16419       return NULL;
16420    }
16421 
16422    if (a->argc == 4)
16423       linkset = atoi(a->argv[3]);
16424    else
16425       return CLI_SHOWUSAGE;
16426 
16427    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16428       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16429       return CLI_SUCCESS;
16430    }
16431 
16432    if (!linksets[linkset-1].ss7.ss7) {
16433       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16434       return CLI_SUCCESS;
16435    }
16436 
16437    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16438       ast_cli(a->fd, "Sending remote unblock request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
16439       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16440       isup_ubl(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16441       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16442    }
16443 
16444    /* Break poll on the linkset so it sends our messages */
16445    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16446 
16447    return CLI_SUCCESS;
16448 }
16449 #endif   /* defined(HAVE_SS7) */
16450 
16451 #if defined(HAVE_SS7)
16452 static char *handle_ss7_show_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16453 {
16454    int linkset;
16455    struct sig_ss7_linkset *ss7;
16456    switch (cmd) {
16457    case CLI_INIT:
16458       e->command = "ss7 show linkset";
16459       e->usage =
16460          "Usage: ss7 show linkset <span>\n"
16461          "       Shows the status of an SS7 linkset.\n";
16462       return NULL;
16463    case CLI_GENERATE:
16464       return NULL;
16465    }
16466 
16467    if (a->argc < 4)
16468       return CLI_SHOWUSAGE;
16469    linkset = atoi(a->argv[3]);
16470    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16471       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16472       return CLI_SUCCESS;
16473    }
16474    ss7 = &linksets[linkset - 1].ss7;
16475    if (!ss7->ss7) {
16476       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16477       return CLI_SUCCESS;
16478    }
16479 
16480    ast_cli(a->fd, "SS7 linkset %d status: %s\n", linkset, (ss7->state == LINKSET_STATE_UP) ? "Up" : "Down");
16481 
16482    return CLI_SUCCESS;
16483 }
16484 #endif   /* defined(HAVE_SS7) */
16485 
16486 #if defined(HAVE_SS7)
16487 static char *handle_ss7_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16488 {
16489    int linkset;
16490 
16491    switch (cmd) {
16492    case CLI_INIT:
16493       e->command = "ss7 show channels";
16494       e->usage =
16495          "Usage: ss7 show channels\n"
16496          "       Displays SS7 channel information at a glance.\n";
16497       return NULL;
16498    case CLI_GENERATE:
16499       return NULL;
16500    }
16501 
16502    if (a->argc != 3)
16503       return CLI_SHOWUSAGE;
16504 
16505    sig_ss7_cli_show_channels_header(a->fd);
16506    for (linkset = 0; linkset < NUM_SPANS; ++linkset) {
16507       if (linksets[linkset].ss7.ss7) {
16508          sig_ss7_cli_show_channels(a->fd, &linksets[linkset].ss7);
16509       }
16510    }
16511    return CLI_SUCCESS;
16512 }
16513 #endif   /* defined(HAVE_SS7) */
16514 
16515 #if defined(HAVE_SS7)
16516 static char *handle_ss7_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16517 {
16518    switch (cmd) {
16519    case CLI_INIT:
16520       e->command = "ss7 show version";
16521       e->usage =
16522          "Usage: ss7 show version\n"
16523          "  Show the libss7 version\n";
16524       return NULL;
16525    case CLI_GENERATE:
16526       return NULL;
16527    }
16528 
16529    ast_cli(a->fd, "libss7 version: %s\n", ss7_get_version());
16530 
16531    return CLI_SUCCESS;
16532 }
16533 #endif   /* defined(HAVE_SS7) */
16534 
16535 #if defined(HAVE_SS7)
16536 static struct ast_cli_entry dahdi_ss7_cli[] = {
16537    AST_CLI_DEFINE(handle_ss7_debug, "Enables SS7 debugging on a linkset"),
16538    AST_CLI_DEFINE(handle_ss7_block_cic, "Blocks the given CIC"),
16539    AST_CLI_DEFINE(handle_ss7_unblock_cic, "Unblocks the given CIC"),
16540    AST_CLI_DEFINE(handle_ss7_block_linkset, "Blocks all CICs on a linkset"),
16541    AST_CLI_DEFINE(handle_ss7_unblock_linkset, "Unblocks all CICs on a linkset"),
16542    AST_CLI_DEFINE(handle_ss7_show_linkset, "Shows the status of a linkset"),
16543    AST_CLI_DEFINE(handle_ss7_show_channels, "Displays SS7 channel information"),
16544    AST_CLI_DEFINE(handle_ss7_version, "Displays libss7 version"),
16545 };
16546 #endif   /* defined(HAVE_SS7) */
16547 
16548 #if defined(HAVE_PRI)
16549 #if defined(HAVE_PRI_CCSS)
16550 /*!
16551  * \internal
16552  * \brief CC agent initialization.
16553  * \since 1.8
16554  *
16555  * \param agent CC core agent control.
16556  * \param chan Original channel the agent will attempt to recall.
16557  *
16558  * \details
16559  * This callback is called when the CC core is initialized.  Agents should allocate
16560  * any private data necessary for the call and assign it to the private_data
16561  * on the agent.  Additionally, if any ast_cc_agent_flags are pertinent to the
16562  * specific agent type, they should be set in this function as well.
16563  *
16564  * \retval 0 on success.
16565  * \retval -1 on error.
16566  */
16567 static int dahdi_pri_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
16568 {
16569    struct dahdi_pvt *pvt;
16570    struct sig_pri_chan *pvt_chan;
16571    int res;
16572 
16573    ast_assert(!strcmp(chan->tech->type, "DAHDI"));
16574 
16575    pvt = chan->tech_pvt;
16576    if (dahdi_sig_pri_lib_handles(pvt->sig)) {
16577       pvt_chan = pvt->sig_pvt;
16578    } else {
16579       pvt_chan = NULL;
16580    }
16581    if (!pvt_chan) {
16582       return -1;
16583    }
16584 
16585    ast_module_ref(ast_module_info->self);
16586 
16587    res = sig_pri_cc_agent_init(agent, pvt_chan);
16588    if (res) {
16589       ast_module_unref(ast_module_info->self);
16590    }
16591    return res;
16592 }
16593 #endif   /* defined(HAVE_PRI_CCSS) */
16594 #endif   /* defined(HAVE_PRI) */
16595 
16596 #if defined(HAVE_PRI)
16597 #if defined(HAVE_PRI_CCSS)
16598 /*!
16599  * \internal
16600  * \brief Destroy private data on the agent.
16601  * \since 1.8
16602  *
16603  * \param agent CC core agent control.
16604  *
16605  * \details
16606  * The core will call this function upon completion
16607  * or failure of CC.
16608  *
16609  * \return Nothing
16610  */
16611 static void dahdi_pri_cc_agent_destructor(struct ast_cc_agent *agent)
16612 {
16613    sig_pri_cc_agent_destructor(agent);
16614 
16615    ast_module_unref(ast_module_info->self);
16616 }
16617 #endif   /* defined(HAVE_PRI_CCSS) */
16618 #endif   /* defined(HAVE_PRI) */
16619 
16620 #if defined(HAVE_PRI)
16621 #if defined(HAVE_PRI_CCSS)
16622 static struct ast_cc_agent_callbacks dahdi_pri_cc_agent_callbacks = {
16623    .type = dahdi_pri_cc_type,
16624    .init = dahdi_pri_cc_agent_init,
16625    .start_offer_timer = sig_pri_cc_agent_start_offer_timer,
16626    .stop_offer_timer = sig_pri_cc_agent_stop_offer_timer,
16627    .respond = sig_pri_cc_agent_req_rsp,
16628    .status_request = sig_pri_cc_agent_status_req,
16629    .stop_ringing = sig_pri_cc_agent_stop_ringing,
16630    .party_b_free = sig_pri_cc_agent_party_b_free,
16631    .start_monitoring = sig_pri_cc_agent_start_monitoring,
16632    .callee_available = sig_pri_cc_agent_callee_available,
16633    .destructor = dahdi_pri_cc_agent_destructor,
16634 };
16635 #endif   /* defined(HAVE_PRI_CCSS) */
16636 #endif   /* defined(HAVE_PRI) */
16637 
16638 #if defined(HAVE_PRI)
16639 #if defined(HAVE_PRI_CCSS)
16640 static struct ast_cc_monitor_callbacks dahdi_pri_cc_monitor_callbacks = {
16641    .type = dahdi_pri_cc_type,
16642    .request_cc = sig_pri_cc_monitor_req_cc,
16643    .suspend = sig_pri_cc_monitor_suspend,
16644    .unsuspend = sig_pri_cc_monitor_unsuspend,
16645    .status_response = sig_pri_cc_monitor_status_rsp,
16646    .cancel_available_timer = sig_pri_cc_monitor_cancel_available_timer,
16647    .destructor = sig_pri_cc_monitor_destructor,
16648 };
16649 #endif   /* defined(HAVE_PRI_CCSS) */
16650 #endif   /* defined(HAVE_PRI) */
16651 
16652 static int __unload_module(void)
16653 {
16654    struct dahdi_pvt *p;
16655 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16656    int i, j;
16657 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16658 
16659 #ifdef HAVE_PRI
16660    for (i = 0; i < NUM_SPANS; i++) {
16661       if (pris[i].pri.master != AST_PTHREADT_NULL)
16662          pthread_cancel(pris[i].pri.master);
16663    }
16664    ast_cli_unregister_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
16665    ast_unregister_application(dahdi_send_keypad_facility_app);
16666 #ifdef HAVE_PRI_PROG_W_CAUSE
16667    ast_unregister_application(dahdi_send_callrerouting_facility_app);
16668 #endif
16669 #endif
16670 #if defined(HAVE_SS7)
16671    for (i = 0; i < NUM_SPANS; i++) {
16672       if (linksets[i].ss7.master != AST_PTHREADT_NULL)
16673          pthread_cancel(linksets[i].ss7.master);
16674       }
16675    ast_cli_unregister_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
16676 #endif   /* defined(HAVE_SS7) */
16677 #if defined(HAVE_OPENR2)
16678    dahdi_r2_destroy_links();
16679    ast_cli_unregister_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
16680    ast_unregister_application(dahdi_accept_r2_call_app);
16681 #endif
16682 
16683    ast_cli_unregister_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
16684    ast_manager_unregister("DAHDIDialOffhook");
16685    ast_manager_unregister("DAHDIHangup");
16686    ast_manager_unregister("DAHDITransfer");
16687    ast_manager_unregister("DAHDIDNDoff");
16688    ast_manager_unregister("DAHDIDNDon");
16689    ast_manager_unregister("DAHDIShowChannels");
16690    ast_manager_unregister("DAHDIRestart");
16691    ast_data_unregister(NULL);
16692    ast_channel_unregister(&dahdi_tech);
16693 
16694    /* Hangup all interfaces if they have an owner */
16695    ast_mutex_lock(&iflock);
16696    for (p = iflist; p; p = p->next) {
16697       if (p->owner)
16698          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16699    }
16700    ast_mutex_unlock(&iflock);
16701 
16702    ast_mutex_lock(&monlock);
16703    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
16704       pthread_cancel(monitor_thread);
16705       pthread_kill(monitor_thread, SIGURG);
16706       pthread_join(monitor_thread, NULL);
16707    }
16708    monitor_thread = AST_PTHREADT_STOP;
16709    ast_mutex_unlock(&monlock);
16710 
16711    destroy_all_channels();
16712 
16713 #if defined(HAVE_PRI)
16714    for (i = 0; i < NUM_SPANS; i++) {
16715       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL))
16716          pthread_join(pris[i].pri.master, NULL);
16717       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++) {
16718          dahdi_close_pri_fd(&(pris[i]), j);
16719       }
16720       sig_pri_stop_pri(&pris[i].pri);
16721    }
16722 #if defined(HAVE_PRI_CCSS)
16723    ast_cc_agent_unregister(&dahdi_pri_cc_agent_callbacks);
16724    ast_cc_monitor_unregister(&dahdi_pri_cc_monitor_callbacks);
16725 #endif   /* defined(HAVE_PRI_CCSS) */
16726    sig_pri_unload();
16727 #endif
16728 
16729 #if defined(HAVE_SS7)
16730    for (i = 0; i < NUM_SPANS; i++) {
16731       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL))
16732          pthread_join(linksets[i].ss7.master, NULL);
16733       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++) {
16734          dahdi_close_ss7_fd(&(linksets[i]), j);
16735       }
16736    }
16737 #endif   /* defined(HAVE_SS7) */
16738    ast_cond_destroy(&ss_thread_complete);
16739    return 0;
16740 }
16741 
16742 static int unload_module(void)
16743 {
16744 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16745    int y;
16746 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16747 #ifdef HAVE_PRI
16748    for (y = 0; y < NUM_SPANS; y++)
16749       ast_mutex_destroy(&pris[y].pri.lock);
16750 #endif
16751 #if defined(HAVE_SS7)
16752    for (y = 0; y < NUM_SPANS; y++)
16753       ast_mutex_destroy(&linksets[y].ss7.lock);
16754 #endif   /* defined(HAVE_SS7) */
16755    return __unload_module();
16756 }
16757 
16758 static void string_replace(char *str, int char1, int char2)
16759 {
16760    for (; *str; str++) {
16761       if (*str == char1) {
16762          *str = char2;
16763       }
16764    }
16765 }
16766 
16767 static char *parse_spanchan(char *chanstr, char **subdir)
16768 {
16769    char *p;
16770 
16771    if ((p = strrchr(chanstr, '!')) == NULL) {
16772       *subdir = NULL;
16773       return chanstr;
16774    }
16775    *p++ = '\0';
16776    string_replace(chanstr, '!', '/');
16777    *subdir = chanstr;
16778    return p;
16779 }
16780 
16781 static int build_channels(struct dahdi_chan_conf *conf, const char *value, int reload, int lineno, int *found_pseudo)
16782 {
16783    char *c, *chan;
16784    char *subdir;
16785    int x, start, finish;
16786    struct dahdi_pvt *tmp;
16787 
16788    if ((reload == 0) && (conf->chan.sig < 0) && !conf->is_sig_auto) {
16789       ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
16790       return -1;
16791    }
16792 
16793    c = ast_strdupa(value);
16794    c = parse_spanchan(c, &subdir);
16795 
16796    while ((chan = strsep(&c, ","))) {
16797       if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
16798          /* Range */
16799       } else if (sscanf(chan, "%30d", &start)) {
16800          /* Just one */
16801          finish = start;
16802       } else if (!strcasecmp(chan, "pseudo")) {
16803          finish = start = CHAN_PSEUDO;
16804          if (found_pseudo)
16805             *found_pseudo = 1;
16806       } else {
16807          ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
16808          return -1;
16809       }
16810       if (finish < start) {
16811          ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
16812          x = finish;
16813          finish = start;
16814          start = x;
16815       }
16816 
16817       for (x = start; x <= finish; x++) {
16818          char fn[PATH_MAX];
16819          int real_channel = x;
16820 
16821          if (!ast_strlen_zero(subdir)) {
16822             real_channel = device2chan(subdir, x, fn, sizeof(fn));
16823             if (real_channel < 0) {
16824                if (conf->ignore_failed_channels) {
16825                   ast_log(LOG_WARNING, "Failed configuring %s!%d, (got %d). But moving on to others.\n",
16826                         subdir, x, real_channel);
16827                   continue;
16828                } else {
16829                   ast_log(LOG_ERROR, "Failed configuring %s!%d, (got %d).\n",
16830                         subdir, x, real_channel);
16831                   return -1;
16832                }
16833             }
16834          }
16835          tmp = mkintf(real_channel, conf, reload);
16836 
16837          if (tmp) {
16838             ast_verb(3, "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", real_channel, sig2str(tmp->sig));
16839          } else {
16840             ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
16841                   (reload == 1) ? "reconfigure" : "register", value);
16842             return -1;
16843          }
16844       }
16845    }
16846 
16847    return 0;
16848 }
16849 
16850 /** The length of the parameters list of 'dahdichan'.
16851  * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
16852 #define MAX_CHANLIST_LEN 80
16853 
16854 static void process_echocancel(struct dahdi_chan_conf *confp, const char *data, unsigned int line)
16855 {
16856    char *parse = ast_strdupa(data);
16857    char *params[DAHDI_MAX_ECHOCANPARAMS + 1];
16858    unsigned int param_count;
16859    unsigned int x;
16860 
16861    if (!(param_count = ast_app_separate_args(parse, ',', params, ARRAY_LEN(params))))
16862       return;
16863 
16864    memset(&confp->chan.echocancel, 0, sizeof(confp->chan.echocancel));
16865 
16866    /* first parameter is tap length, process it here */
16867 
16868    x = ast_strlen_zero(params[0]) ? 0 : atoi(params[0]);
16869 
16870    if ((x == 32) || (x == 64) || (x == 128) || (x == 256) || (x == 512) || (x == 1024))
16871       confp->chan.echocancel.head.tap_length = x;
16872    else if ((confp->chan.echocancel.head.tap_length = ast_true(params[0])))
16873       confp->chan.echocancel.head.tap_length = 128;
16874 
16875    /* now process any remaining parameters */
16876 
16877    for (x = 1; x < param_count; x++) {
16878       struct {
16879          char *name;
16880          char *value;
16881       } param;
16882 
16883       if (ast_app_separate_args(params[x], '=', (char **) &param, 2) < 1) {
16884          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, params[x]);
16885          continue;
16886       }
16887 
16888       if (ast_strlen_zero(param.name) || (strlen(param.name) > sizeof(confp->chan.echocancel.params[0].name)-1)) {
16889          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, param.name);
16890          continue;
16891       }
16892 
16893       strcpy(confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].name, param.name);
16894 
16895       if (param.value) {
16896          if (sscanf(param.value, "%30d", &confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].value) != 1) {
16897             ast_log(LOG_WARNING, "Invalid echocancel parameter value supplied at line %d: '%s'\n", line, param.value);
16898             continue;
16899          }
16900       }
16901       confp->chan.echocancel.head.param_count++;
16902    }
16903 }
16904 
16905 /*! process_dahdi() - ignore keyword 'channel' and similar */
16906 #define PROC_DAHDI_OPT_NOCHAN  (1 << 0)
16907 /*! process_dahdi() - No warnings on non-existing cofiguration keywords */
16908 #define PROC_DAHDI_OPT_NOWARN  (1 << 1)
16909 
16910 static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct ast_variable *v, int reload, int options)
16911 {
16912    struct dahdi_pvt *tmp;
16913    int y;
16914    int found_pseudo = 0;
16915    struct ast_variable *dahdichan = NULL;
16916 
16917    for (; v; v = v->next) {
16918       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16919          continue;
16920 
16921       /* Create the interface list */
16922       if (!strcasecmp(v->name, "channel") || !strcasecmp(v->name, "channels")) {
16923          if (options & PROC_DAHDI_OPT_NOCHAN) {
16924             ast_log(LOG_WARNING, "Channel '%s' ignored.\n", v->value);
16925             continue;
16926          }
16927          if (build_channels(confp, v->value, reload, v->lineno, &found_pseudo)) {
16928             if (confp->ignore_failed_channels) {
16929                ast_log(LOG_WARNING, "Channel '%s' failure ignored: ignore_failed_channels.\n", v->value);
16930                continue;
16931             } else {
16932                return -1;
16933             }
16934          }
16935          ast_log(LOG_DEBUG, "Channel '%s' configured.\n", v->value);
16936       } else if (!strcasecmp(v->name, "ignore_failed_channels")) {
16937          confp->ignore_failed_channels = ast_true(v->value);
16938       } else if (!strcasecmp(v->name, "buffers")) {
16939          if (parse_buffers_policy(v->value, &confp->chan.buf_no, &confp->chan.buf_policy)) {
16940             ast_log(LOG_WARNING, "Using default buffer policy.\n");
16941             confp->chan.buf_no = numbufs;
16942             confp->chan.buf_policy = DAHDI_POLICY_IMMEDIATE;
16943          }
16944       } else if (!strcasecmp(v->name, "faxbuffers")) {
16945          if (!parse_buffers_policy(v->value, &confp->chan.faxbuf_no, &confp->chan.faxbuf_policy)) {
16946             confp->chan.usefaxbuffers = 1;
16947          }
16948       } else if (!strcasecmp(v->name, "dahdichan")) {
16949          /* Only process the last dahdichan value. */
16950          dahdichan = v;
16951       } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
16952          usedistinctiveringdetection = ast_true(v->value);
16953       } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
16954          distinctiveringaftercid = ast_true(v->value);
16955       } else if (!strcasecmp(v->name, "dring1context")) {
16956          ast_copy_string(confp->chan.drings.ringContext[0].contextData,v->value,sizeof(confp->chan.drings.ringContext[0].contextData));
16957       } else if (!strcasecmp(v->name, "dring2context")) {
16958          ast_copy_string(confp->chan.drings.ringContext[1].contextData,v->value,sizeof(confp->chan.drings.ringContext[1].contextData));
16959       } else if (!strcasecmp(v->name, "dring3context")) {
16960          ast_copy_string(confp->chan.drings.ringContext[2].contextData,v->value,sizeof(confp->chan.drings.ringContext[2].contextData));
16961       } else if (!strcasecmp(v->name, "dring1range")) {
16962          confp->chan.drings.ringnum[0].range = atoi(v->value);
16963       } else if (!strcasecmp(v->name, "dring2range")) {
16964          confp->chan.drings.ringnum[1].range = atoi(v->value);
16965       } else if (!strcasecmp(v->name, "dring3range")) {
16966          confp->chan.drings.ringnum[2].range = atoi(v->value);
16967       } else if (!strcasecmp(v->name, "dring1")) {
16968          sscanf(v->value, "%30d,%30d,%30d", &confp->chan.drings.ringnum[0].ring[0], &confp->chan.drings.ringnum[0].ring[1], &confp->chan.drings.ringnum[0].ring[2]);
16969       } else if (!strcasecmp(v->name, "dring2")) {
16970          sscanf(v->value, "%30d,%30d,%30d", &confp->chan.drings.ringnum[1].ring[0], &confp->chan.drings.ringnum[1].ring[1], &confp->chan.drings.ringnum[1].ring[2]);
16971       } else if (!strcasecmp(v->name, "dring3")) {
16972          sscanf(v->value, "%30d,%30d,%30d", &confp->chan.drings.ringnum[2].ring[0], &confp->chan.drings.ringnum[2].ring[1], &confp->chan.drings.ringnum[2].ring[2]);
16973       } else if (!strcasecmp(v->name, "usecallerid")) {
16974          confp->chan.use_callerid = ast_true(v->value);
16975       } else if (!strcasecmp(v->name, "cidsignalling")) {
16976          if (!strcasecmp(v->value, "bell"))
16977             confp->chan.cid_signalling = CID_SIG_BELL;
16978          else if (!strcasecmp(v->value, "v23"))
16979             confp->chan.cid_signalling = CID_SIG_V23;
16980          else if (!strcasecmp(v->value, "dtmf"))
16981             confp->chan.cid_signalling = CID_SIG_DTMF;
16982          else if (!strcasecmp(v->value, "smdi"))
16983             confp->chan.cid_signalling = CID_SIG_SMDI;
16984          else if (!strcasecmp(v->value, "v23_jp"))
16985             confp->chan.cid_signalling = CID_SIG_V23_JP;
16986          else if (ast_true(v->value))
16987             confp->chan.cid_signalling = CID_SIG_BELL;
16988       } else if (!strcasecmp(v->name, "cidstart")) {
16989          if (!strcasecmp(v->value, "ring"))
16990             confp->chan.cid_start = CID_START_RING;
16991          else if (!strcasecmp(v->value, "polarity_in"))
16992             confp->chan.cid_start = CID_START_POLARITY_IN;
16993          else if (!strcasecmp(v->value, "polarity"))
16994             confp->chan.cid_start = CID_START_POLARITY;
16995          else if (!strcasecmp(v->value, "dtmf"))
16996             confp->chan.cid_start = CID_START_DTMF_NOALERT;
16997          else if (ast_true(v->value))
16998             confp->chan.cid_start = CID_START_RING;
16999       } else if (!strcasecmp(v->name, "threewaycalling")) {
17000          confp->chan.threewaycalling = ast_true(v->value);
17001       } else if (!strcasecmp(v->name, "cancallforward")) {
17002          confp->chan.cancallforward = ast_true(v->value);
17003       } else if (!strcasecmp(v->name, "relaxdtmf")) {
17004          if (ast_true(v->value))
17005             confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
17006          else
17007             confp->chan.dtmfrelax = 0;
17008       } else if (!strcasecmp(v->name, "mailbox")) {
17009          ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
17010       } else if (!strcasecmp(v->name, "hasvoicemail")) {
17011          if (ast_true(v->value) && ast_strlen_zero(confp->chan.mailbox)) {
17012             ast_copy_string(confp->chan.mailbox, cat, sizeof(confp->chan.mailbox));
17013          }
17014       } else if (!strcasecmp(v->name, "adsi")) {
17015          confp->chan.adsi = ast_true(v->value);
17016       } else if (!strcasecmp(v->name, "usesmdi")) {
17017          confp->chan.use_smdi = ast_true(v->value);
17018       } else if (!strcasecmp(v->name, "smdiport")) {
17019          ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
17020       } else if (!strcasecmp(v->name, "transfer")) {
17021          confp->chan.transfer = ast_true(v->value);
17022       } else if (!strcasecmp(v->name, "canpark")) {
17023          confp->chan.canpark = ast_true(v->value);
17024       } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
17025          confp->chan.echocanbridged = ast_true(v->value);
17026       } else if (!strcasecmp(v->name, "busydetect")) {
17027          confp->chan.busydetect = ast_true(v->value);
17028       } else if (!strcasecmp(v->name, "busycount")) {
17029          confp->chan.busycount = atoi(v->value);
17030       } else if (!strcasecmp(v->name, "busypattern")) {
17031          if (sscanf(v->value, "%30d,%30d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
17032             ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength at line %d.\n", v->lineno);
17033          }
17034       } else if (!strcasecmp(v->name, "callprogress")) {
17035          confp->chan.callprogress &= ~CALLPROGRESS_PROGRESS;
17036          if (ast_true(v->value))
17037             confp->chan.callprogress |= CALLPROGRESS_PROGRESS;
17038       } else if (!strcasecmp(v->name, "waitfordialtone")) {
17039          confp->chan.waitfordialtone = atoi(v->value);
17040       } else if (!strcasecmp(v->name, "faxdetect")) {
17041          confp->chan.callprogress &= ~CALLPROGRESS_FAX;
17042          if (!strcasecmp(v->value, "incoming")) {
17043             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING;
17044          } else if (!strcasecmp(v->value, "outgoing")) {
17045             confp->chan.callprogress |= CALLPROGRESS_FAX_OUTGOING;
17046          } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
17047             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING;
17048       } else if (!strcasecmp(v->name, "echocancel")) {
17049          process_echocancel(confp, v->value, v->lineno);
17050       } else if (!strcasecmp(v->name, "echotraining")) {
17051          if (sscanf(v->value, "%30d", &y) == 1) {
17052             if ((y < 10) || (y > 4000)) {
17053                ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d.\n", v->lineno);
17054             } else {
17055                confp->chan.echotraining = y;
17056             }
17057          } else if (ast_true(v->value)) {
17058             confp->chan.echotraining = 400;
17059          } else
17060             confp->chan.echotraining = 0;
17061       } else if (!strcasecmp(v->name, "hidecallerid")) {
17062          confp->chan.hidecallerid = ast_true(v->value);
17063       } else if (!strcasecmp(v->name, "hidecalleridname")) {
17064          confp->chan.hidecalleridname = ast_true(v->value);
17065       } else if (!strcasecmp(v->name, "pulsedial")) {
17066          confp->chan.pulse = ast_true(v->value);
17067       } else if (!strcasecmp(v->name, "callreturn")) {
17068          confp->chan.callreturn = ast_true(v->value);
17069       } else if (!strcasecmp(v->name, "callwaiting")) {
17070          confp->chan.callwaiting = ast_true(v->value);
17071       } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
17072          confp->chan.callwaitingcallerid = ast_true(v->value);
17073       } else if (!strcasecmp(v->name, "context")) {
17074          ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
17075       } else if (!strcasecmp(v->name, "language")) {
17076          ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
17077       } else if (!strcasecmp(v->name, "progzone")) {
17078          ast_copy_string(progzone, v->value, sizeof(progzone));
17079       } else if (!strcasecmp(v->name, "mohinterpret")
17080          ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
17081          ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
17082       } else if (!strcasecmp(v->name, "mohsuggest")) {
17083          ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
17084       } else if (!strcasecmp(v->name, "parkinglot")) {
17085          ast_copy_string(confp->chan.parkinglot, v->value, sizeof(confp->chan.parkinglot));
17086       } else if (!strcasecmp(v->name, "stripmsd")) {
17087          ast_log(LOG_NOTICE, "Configuration option \"%s\" has been deprecated. Please use dialplan instead\n", v->name);
17088          confp->chan.stripmsd = atoi(v->value);
17089       } else if (!strcasecmp(v->name, "jitterbuffers")) {
17090          numbufs = atoi(v->value);
17091       } else if (!strcasecmp(v->name, "group")) {
17092          confp->chan.group = ast_get_group(v->value);
17093       } else if (!strcasecmp(v->name, "callgroup")) {
17094          if (!strcasecmp(v->value, "none"))
17095             confp->chan.callgroup = 0;
17096          else
17097             confp->chan.callgroup = ast_get_group(v->value);
17098       } else if (!strcasecmp(v->name, "pickupgroup")) {
17099          if (!strcasecmp(v->value, "none"))
17100             confp->chan.pickupgroup = 0;
17101          else
17102             confp->chan.pickupgroup = ast_get_group(v->value);
17103       } else if (!strcasecmp(v->name, "setvar")) {
17104          char *varname = ast_strdupa(v->value), *varval = NULL;
17105          struct ast_variable *tmpvar;
17106          if (varname && (varval = strchr(varname, '='))) {
17107             *varval++ = '\0';
17108             if ((tmpvar = ast_variable_new(varname, varval, ""))) {
17109                tmpvar->next = confp->chan.vars;
17110                confp->chan.vars = tmpvar;
17111             }
17112          }
17113       } else if (!strcasecmp(v->name, "immediate")) {
17114          confp->chan.immediate = ast_true(v->value);
17115       } else if (!strcasecmp(v->name, "transfertobusy")) {
17116          confp->chan.transfertobusy = ast_true(v->value);
17117       } else if (!strcasecmp(v->name, "mwimonitor")) {
17118          confp->chan.mwimonitor_neon = 0;
17119          confp->chan.mwimonitor_fsk = 0;
17120          confp->chan.mwimonitor_rpas = 0;
17121          if (strcasestr(v->value, "fsk")) {
17122             confp->chan.mwimonitor_fsk = 1;
17123          }
17124          if (strcasestr(v->value, "rpas")) {
17125             confp->chan.mwimonitor_rpas = 1;
17126          }
17127          if (strcasestr(v->value, "neon")) {
17128             confp->chan.mwimonitor_neon = 1;
17129          }
17130          /* If set to true or yes, assume that simple fsk is desired */
17131          if (ast_true(v->value)) {
17132             confp->chan.mwimonitor_fsk = 1;
17133          }
17134       } else if (!strcasecmp(v->name, "cid_rxgain")) {
17135          if (sscanf(v->value, "%30f", &confp->chan.cid_rxgain) != 1) {
17136             ast_log(LOG_WARNING, "Invalid cid_rxgain: %s at line %d.\n", v->value, v->lineno);
17137          }
17138       } else if (!strcasecmp(v->name, "rxgain")) {
17139          if (sscanf(v->value, "%30f", &confp->chan.rxgain) != 1) {
17140             ast_log(LOG_WARNING, "Invalid rxgain: %s at line %d.\n", v->value, v->lineno);
17141          }
17142       } else if (!strcasecmp(v->name, "txgain")) {
17143          if (sscanf(v->value, "%30f", &confp->chan.txgain) != 1) {
17144             ast_log(LOG_WARNING, "Invalid txgain: %s at line %d.\n", v->value, v->lineno);
17145          }
17146       } else if (!strcasecmp(v->name, "txdrc")) {
17147          if (sscanf(v->value, "%f", &confp->chan.txdrc) != 1) {
17148             ast_log(LOG_WARNING, "Invalid txdrc: %s\n", v->value);
17149          }
17150       } else if (!strcasecmp(v->name, "rxdrc")) {
17151          if (sscanf(v->value, "%f", &confp->chan.rxdrc) != 1) {
17152             ast_log(LOG_WARNING, "Invalid rxdrc: %s\n", v->value);
17153          }
17154       } else if (!strcasecmp(v->name, "tonezone")) {
17155          if (sscanf(v->value, "%30d", &confp->chan.tonezone) != 1) {
17156             ast_log(LOG_WARNING, "Invalid tonezone: %s at line %d.\n", v->value, v->lineno);
17157          }
17158       } else if (!strcasecmp(v->name, "callerid")) {
17159          if (!strcasecmp(v->value, "asreceived")) {
17160             confp->chan.cid_num[0] = '\0';
17161             confp->chan.cid_name[0] = '\0';
17162          } else {
17163             ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
17164          }
17165       } else if (!strcasecmp(v->name, "fullname")) {
17166          ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
17167       } else if (!strcasecmp(v->name, "cid_number")) {
17168          ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
17169       } else if (!strcasecmp(v->name, "cid_tag")) {
17170          ast_copy_string(confp->chan.cid_tag, v->value, sizeof(confp->chan.cid_tag));
17171       } else if (!strcasecmp(v->name, "useincomingcalleridondahditransfer")) {
17172          confp->chan.dahditrcallerid = ast_true(v->value);
17173       } else if (!strcasecmp(v->name, "restrictcid")) {
17174          confp->chan.restrictcid = ast_true(v->value);
17175       } else if (!strcasecmp(v->name, "usecallingpres")) {
17176          confp->chan.use_callingpres = ast_true(v->value);
17177       } else if (!strcasecmp(v->name, "accountcode")) {
17178          ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
17179       } else if (!strcasecmp(v->name, "amaflags")) {
17180          y = ast_cdr_amaflags2int(v->value);
17181          if (y < 0)
17182             ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d.\n", v->value, v->lineno);
17183          else
17184             confp->chan.amaflags = y;
17185       } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
17186          confp->chan.polarityonanswerdelay = atoi(v->value);
17187       } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
17188          confp->chan.answeronpolarityswitch = ast_true(v->value);
17189       } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
17190          confp->chan.hanguponpolarityswitch = ast_true(v->value);
17191       } else if (!strcasecmp(v->name, "sendcalleridafter")) {
17192          confp->chan.sendcalleridafter = atoi(v->value);
17193       } else if (!strcasecmp(v->name, "mwimonitornotify")) {
17194          ast_copy_string(mwimonitornotify, v->value, sizeof(mwimonitornotify));
17195       } else if (ast_cc_is_config_param(v->name)) {
17196          ast_cc_set_param(confp->chan.cc_params, v->name, v->value);
17197       } else if (!strcasecmp(v->name, "mwisendtype")) {
17198 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI  /* backward compatibility for older dahdi VMWI implementation */
17199          if (!strcasecmp(v->value, "rpas")) { /* Ring Pulse Alert Signal */
17200             mwisend_rpas = 1;
17201          } else {
17202             mwisend_rpas = 0;
17203          }
17204 #else
17205          /* Default is fsk, to turn it off you must specify nofsk */
17206          memset(&confp->chan.mwisend_setting, 0, sizeof(confp->chan.mwisend_setting));
17207          if (strcasestr(v->value, "nofsk")) {      /* NoFSK */
17208             confp->chan.mwisend_fsk = 0;
17209          } else {             /* Default FSK */
17210             confp->chan.mwisend_fsk = 1;
17211          }
17212          if (strcasestr(v->value, "rpas")) {       /* Ring Pulse Alert Signal, normally followed by FSK */
17213             confp->chan.mwisend_rpas = 1;
17214          } else {
17215             confp->chan.mwisend_rpas = 0;
17216          }
17217          if (strcasestr(v->value, "lrev")) {       /* Line Reversal */
17218             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_LREV;
17219          }
17220          if (strcasestr(v->value, "hvdc")) {       /* HV 90VDC */
17221             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVDC;
17222          }
17223          if ( (strcasestr(v->value, "neon")) || (strcasestr(v->value, "hvac")) ){   /* 90V DC pulses */
17224             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVAC;
17225          }
17226 #endif
17227       } else if (reload != 1) {
17228           if (!strcasecmp(v->name, "signalling") || !strcasecmp(v->name, "signaling")) {
17229             int orig_radio = confp->chan.radio;
17230             int orig_outsigmod = confp->chan.outsigmod;
17231             int orig_auto = confp->is_sig_auto;
17232 
17233             confp->chan.radio = 0;
17234             confp->chan.outsigmod = -1;
17235             confp->is_sig_auto = 0;
17236             if (!strcasecmp(v->value, "em")) {
17237                confp->chan.sig = SIG_EM;
17238             } else if (!strcasecmp(v->value, "em_e1")) {
17239                confp->chan.sig = SIG_EM_E1;
17240             } else if (!strcasecmp(v->value, "em_w")) {
17241                confp->chan.sig = SIG_EMWINK;
17242             } else if (!strcasecmp(v->value, "fxs_ls")) {
17243                confp->chan.sig = SIG_FXSLS;
17244             } else if (!strcasecmp(v->value, "fxs_gs")) {
17245                confp->chan.sig = SIG_FXSGS;
17246             } else if (!strcasecmp(v->value, "fxs_ks")) {
17247                confp->chan.sig = SIG_FXSKS;
17248             } else if (!strcasecmp(v->value, "fxo_ls")) {
17249                confp->chan.sig = SIG_FXOLS;
17250             } else if (!strcasecmp(v->value, "fxo_gs")) {
17251                confp->chan.sig = SIG_FXOGS;
17252             } else if (!strcasecmp(v->value, "fxo_ks")) {
17253                confp->chan.sig = SIG_FXOKS;
17254             } else if (!strcasecmp(v->value, "fxs_rx")) {
17255                confp->chan.sig = SIG_FXSKS;
17256                confp->chan.radio = 1;
17257             } else if (!strcasecmp(v->value, "fxo_rx")) {
17258                confp->chan.sig = SIG_FXOLS;
17259                confp->chan.radio = 1;
17260             } else if (!strcasecmp(v->value, "fxs_tx")) {
17261                confp->chan.sig = SIG_FXSLS;
17262                confp->chan.radio = 1;
17263             } else if (!strcasecmp(v->value, "fxo_tx")) {
17264                confp->chan.sig = SIG_FXOGS;
17265                confp->chan.radio = 1;
17266             } else if (!strcasecmp(v->value, "em_rx")) {
17267                confp->chan.sig = SIG_EM;
17268                confp->chan.radio = 1;
17269             } else if (!strcasecmp(v->value, "em_tx")) {
17270                confp->chan.sig = SIG_EM;
17271                confp->chan.radio = 1;
17272             } else if (!strcasecmp(v->value, "em_rxtx")) {
17273                confp->chan.sig = SIG_EM;
17274                confp->chan.radio = 2;
17275             } else if (!strcasecmp(v->value, "em_txrx")) {
17276                confp->chan.sig = SIG_EM;
17277                confp->chan.radio = 2;
17278             } else if (!strcasecmp(v->value, "sf")) {
17279                confp->chan.sig = SIG_SF;
17280             } else if (!strcasecmp(v->value, "sf_w")) {
17281                confp->chan.sig = SIG_SFWINK;
17282             } else if (!strcasecmp(v->value, "sf_featd")) {
17283                confp->chan.sig = SIG_FEATD;
17284             } else if (!strcasecmp(v->value, "sf_featdmf")) {
17285                confp->chan.sig = SIG_FEATDMF;
17286             } else if (!strcasecmp(v->value, "sf_featb")) {
17287                confp->chan.sig = SIG_SF_FEATB;
17288             } else if (!strcasecmp(v->value, "sf")) {
17289                confp->chan.sig = SIG_SF;
17290             } else if (!strcasecmp(v->value, "sf_rx")) {
17291                confp->chan.sig = SIG_SF;
17292                confp->chan.radio = 1;
17293             } else if (!strcasecmp(v->value, "sf_tx")) {
17294                confp->chan.sig = SIG_SF;
17295                confp->chan.radio = 1;
17296             } else if (!strcasecmp(v->value, "sf_rxtx")) {
17297                confp->chan.sig = SIG_SF;
17298                confp->chan.radio = 2;
17299             } else if (!strcasecmp(v->value, "sf_txrx")) {
17300                confp->chan.sig = SIG_SF;
17301                confp->chan.radio = 2;
17302             } else if (!strcasecmp(v->value, "featd")) {
17303                confp->chan.sig = SIG_FEATD;
17304             } else if (!strcasecmp(v->value, "featdmf")) {
17305                confp->chan.sig = SIG_FEATDMF;
17306             } else if (!strcasecmp(v->value, "featdmf_ta")) {
17307                confp->chan.sig = SIG_FEATDMF_TA;
17308             } else if (!strcasecmp(v->value, "e911")) {
17309                confp->chan.sig = SIG_E911;
17310             } else if (!strcasecmp(v->value, "fgccama")) {
17311                confp->chan.sig = SIG_FGC_CAMA;
17312             } else if (!strcasecmp(v->value, "fgccamamf")) {
17313                confp->chan.sig = SIG_FGC_CAMAMF;
17314             } else if (!strcasecmp(v->value, "featb")) {
17315                confp->chan.sig = SIG_FEATB;
17316 #ifdef HAVE_PRI
17317             } else if (!strcasecmp(v->value, "pri_net")) {
17318                confp->chan.sig = SIG_PRI;
17319                confp->pri.pri.nodetype = PRI_NETWORK;
17320             } else if (!strcasecmp(v->value, "pri_cpe")) {
17321                confp->chan.sig = SIG_PRI;
17322                confp->pri.pri.nodetype = PRI_CPE;
17323             } else if (!strcasecmp(v->value, "bri_cpe")) {
17324                confp->chan.sig = SIG_BRI;
17325                confp->pri.pri.nodetype = PRI_CPE;
17326             } else if (!strcasecmp(v->value, "bri_net")) {
17327                confp->chan.sig = SIG_BRI;
17328                confp->pri.pri.nodetype = PRI_NETWORK;
17329             } else if (!strcasecmp(v->value, "bri_cpe_ptmp")) {
17330                confp->chan.sig = SIG_BRI_PTMP;
17331                confp->pri.pri.nodetype = PRI_CPE;
17332             } else if (!strcasecmp(v->value, "bri_net_ptmp")) {
17333 #if defined(HAVE_PRI_CALL_HOLD)
17334                confp->chan.sig = SIG_BRI_PTMP;
17335                confp->pri.pri.nodetype = PRI_NETWORK;
17336 #else
17337                ast_log(LOG_WARNING, "How cool would it be if someone implemented this mode!  For now, sucks for you. (line %d)\n", v->lineno);
17338 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
17339 #endif
17340 #if defined(HAVE_SS7)
17341             } else if (!strcasecmp(v->value, "ss7")) {
17342                confp->chan.sig = SIG_SS7;
17343 #endif   /* defined(HAVE_SS7) */
17344 #ifdef HAVE_OPENR2
17345             } else if (!strcasecmp(v->value, "mfcr2")) {
17346                confp->chan.sig = SIG_MFCR2;
17347 #endif
17348             } else if (!strcasecmp(v->value, "auto")) {
17349                confp->is_sig_auto = 1;
17350             } else {
17351                confp->chan.outsigmod = orig_outsigmod;
17352                confp->chan.radio = orig_radio;
17353                confp->is_sig_auto = orig_auto;
17354                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
17355             }
17356           } else if (!strcasecmp(v->name, "outsignalling") || !strcasecmp(v->name, "outsignaling")) {
17357             if (!strcasecmp(v->value, "em")) {
17358                confp->chan.outsigmod = SIG_EM;
17359             } else if (!strcasecmp(v->value, "em_e1")) {
17360                confp->chan.outsigmod = SIG_EM_E1;
17361             } else if (!strcasecmp(v->value, "em_w")) {
17362                confp->chan.outsigmod = SIG_EMWINK;
17363             } else if (!strcasecmp(v->value, "sf")) {
17364                confp->chan.outsigmod = SIG_SF;
17365             } else if (!strcasecmp(v->value, "sf_w")) {
17366                confp->chan.outsigmod = SIG_SFWINK;
17367             } else if (!strcasecmp(v->value, "sf_featd")) {
17368                confp->chan.outsigmod = SIG_FEATD;
17369             } else if (!strcasecmp(v->value, "sf_featdmf")) {
17370                confp->chan.outsigmod = SIG_FEATDMF;
17371             } else if (!strcasecmp(v->value, "sf_featb")) {
17372                confp->chan.outsigmod = SIG_SF_FEATB;
17373             } else if (!strcasecmp(v->value, "sf")) {
17374                confp->chan.outsigmod = SIG_SF;
17375             } else if (!strcasecmp(v->value, "featd")) {
17376                confp->chan.outsigmod = SIG_FEATD;
17377             } else if (!strcasecmp(v->value, "featdmf")) {
17378                confp->chan.outsigmod = SIG_FEATDMF;
17379             } else if (!strcasecmp(v->value, "featdmf_ta")) {
17380                confp->chan.outsigmod = SIG_FEATDMF_TA;
17381             } else if (!strcasecmp(v->value, "e911")) {
17382                confp->chan.outsigmod = SIG_E911;
17383             } else if (!strcasecmp(v->value, "fgccama")) {
17384                confp->chan.outsigmod = SIG_FGC_CAMA;
17385             } else if (!strcasecmp(v->value, "fgccamamf")) {
17386                confp->chan.outsigmod = SIG_FGC_CAMAMF;
17387             } else if (!strcasecmp(v->value, "featb")) {
17388                confp->chan.outsigmod = SIG_FEATB;
17389             } else {
17390                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
17391             }
17392 #ifdef HAVE_PRI
17393          } else if (!strcasecmp(v->name, "pridialplan")) {
17394             if (!strcasecmp(v->value, "national")) {
17395                confp->pri.pri.dialplan = PRI_NATIONAL_ISDN + 1;
17396             } else if (!strcasecmp(v->value, "unknown")) {
17397                confp->pri.pri.dialplan = PRI_UNKNOWN + 1;
17398             } else if (!strcasecmp(v->value, "private")) {
17399                confp->pri.pri.dialplan = PRI_PRIVATE + 1;
17400             } else if (!strcasecmp(v->value, "international")) {
17401                confp->pri.pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
17402             } else if (!strcasecmp(v->value, "local")) {
17403                confp->pri.pri.dialplan = PRI_LOCAL_ISDN + 1;
17404             } else if (!strcasecmp(v->value, "dynamic")) {
17405                confp->pri.pri.dialplan = -1;
17406             } else if (!strcasecmp(v->value, "redundant")) {
17407                confp->pri.pri.dialplan = -2;
17408             } else {
17409                ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
17410             }
17411          } else if (!strcasecmp(v->name, "prilocaldialplan")) {
17412             if (!strcasecmp(v->value, "national")) {
17413                confp->pri.pri.localdialplan = PRI_NATIONAL_ISDN + 1;
17414             } else if (!strcasecmp(v->value, "unknown")) {
17415                confp->pri.pri.localdialplan = PRI_UNKNOWN + 1;
17416             } else if (!strcasecmp(v->value, "private")) {
17417                confp->pri.pri.localdialplan = PRI_PRIVATE + 1;
17418             } else if (!strcasecmp(v->value, "international")) {
17419                confp->pri.pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
17420             } else if (!strcasecmp(v->value, "local")) {
17421                confp->pri.pri.localdialplan = PRI_LOCAL_ISDN + 1;
17422             } else if (!strcasecmp(v->value, "dynamic")) {
17423                confp->pri.pri.localdialplan = -1;
17424             } else if (!strcasecmp(v->value, "redundant")) {
17425                confp->pri.pri.localdialplan = -2;
17426             } else {
17427                ast_log(LOG_WARNING, "Unknown PRI localdialplan '%s' at line %d.\n", v->value, v->lineno);
17428             }
17429          } else if (!strcasecmp(v->name, "switchtype")) {
17430             if (!strcasecmp(v->value, "national"))
17431                confp->pri.pri.switchtype = PRI_SWITCH_NI2;
17432             else if (!strcasecmp(v->value, "ni1"))
17433                confp->pri.pri.switchtype = PRI_SWITCH_NI1;
17434             else if (!strcasecmp(v->value, "dms100"))
17435                confp->pri.pri.switchtype = PRI_SWITCH_DMS100;
17436             else if (!strcasecmp(v->value, "4ess"))
17437                confp->pri.pri.switchtype = PRI_SWITCH_ATT4ESS;
17438             else if (!strcasecmp(v->value, "5ess"))
17439                confp->pri.pri.switchtype = PRI_SWITCH_LUCENT5E;
17440             else if (!strcasecmp(v->value, "euroisdn"))
17441                confp->pri.pri.switchtype = PRI_SWITCH_EUROISDN_E1;
17442             else if (!strcasecmp(v->value, "qsig"))
17443                confp->pri.pri.switchtype = PRI_SWITCH_QSIG;
17444             else {
17445                ast_log(LOG_ERROR, "Unknown switchtype '%s' at line %d.\n", v->value, v->lineno);
17446                return -1;
17447             }
17448          } else if (!strcasecmp(v->name, "msn")) {
17449             ast_copy_string(confp->pri.pri.msn_list, v->value,
17450                sizeof(confp->pri.pri.msn_list));
17451          } else if (!strcasecmp(v->name, "nsf")) {
17452             if (!strcasecmp(v->value, "sdn"))
17453                confp->pri.pri.nsf = PRI_NSF_SDN;
17454             else if (!strcasecmp(v->value, "megacom"))
17455                confp->pri.pri.nsf = PRI_NSF_MEGACOM;
17456             else if (!strcasecmp(v->value, "tollfreemegacom"))
17457                confp->pri.pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
17458             else if (!strcasecmp(v->value, "accunet"))
17459                confp->pri.pri.nsf = PRI_NSF_ACCUNET;
17460             else if (!strcasecmp(v->value, "none"))
17461                confp->pri.pri.nsf = PRI_NSF_NONE;
17462             else {
17463                ast_log(LOG_WARNING, "Unknown network-specific facility '%s' at line %d.\n", v->value, v->lineno);
17464                confp->pri.pri.nsf = PRI_NSF_NONE;
17465             }
17466          } else if (!strcasecmp(v->name, "priindication")) {
17467             if (!strcasecmp(v->value, "outofband"))
17468                confp->chan.priindication_oob = 1;
17469             else if (!strcasecmp(v->value, "inband"))
17470                confp->chan.priindication_oob = 0;
17471             else
17472                ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d.\n",
17473                   v->value, v->lineno);
17474          } else if (!strcasecmp(v->name, "priexclusive")) {
17475             confp->chan.priexclusive = ast_true(v->value);
17476          } else if (!strcasecmp(v->name, "internationalprefix")) {
17477             ast_copy_string(confp->pri.pri.internationalprefix, v->value, sizeof(confp->pri.pri.internationalprefix));
17478          } else if (!strcasecmp(v->name, "nationalprefix")) {
17479             ast_copy_string(confp->pri.pri.nationalprefix, v->value, sizeof(confp->pri.pri.nationalprefix));
17480          } else if (!strcasecmp(v->name, "localprefix")) {
17481             ast_copy_string(confp->pri.pri.localprefix, v->value, sizeof(confp->pri.pri.localprefix));
17482          } else if (!strcasecmp(v->name, "privateprefix")) {
17483             ast_copy_string(confp->pri.pri.privateprefix, v->value, sizeof(confp->pri.pri.privateprefix));
17484          } else if (!strcasecmp(v->name, "unknownprefix")) {
17485             ast_copy_string(confp->pri.pri.unknownprefix, v->value, sizeof(confp->pri.pri.unknownprefix));
17486          } else if (!strcasecmp(v->name, "resetinterval")) {
17487             if (!strcasecmp(v->value, "never"))
17488                confp->pri.pri.resetinterval = -1;
17489             else if (atoi(v->value) >= 60)
17490                confp->pri.pri.resetinterval = atoi(v->value);
17491             else
17492                ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d.\n",
17493                   v->value, v->lineno);
17494          } else if (!strcasecmp(v->name, "minunused")) {
17495             confp->pri.pri.minunused = atoi(v->value);
17496          } else if (!strcasecmp(v->name, "minidle")) {
17497             confp->pri.pri.minidle = atoi(v->value);
17498          } else if (!strcasecmp(v->name, "idleext")) {
17499             ast_copy_string(confp->pri.pri.idleext, v->value, sizeof(confp->pri.pri.idleext));
17500          } else if (!strcasecmp(v->name, "idledial")) {
17501             ast_copy_string(confp->pri.pri.idledial, v->value, sizeof(confp->pri.pri.idledial));
17502          } else if (!strcasecmp(v->name, "overlapdial")) {
17503             if (ast_true(v->value)) {
17504                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
17505             } else if (!strcasecmp(v->value, "incoming")) {
17506                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_INCOMING;
17507             } else if (!strcasecmp(v->value, "outgoing")) {
17508                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_OUTGOING;
17509             } else if (!strcasecmp(v->value, "both") || ast_true(v->value)) {
17510                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
17511             } else {
17512                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_NONE;
17513             }
17514 #ifdef HAVE_PRI_PROG_W_CAUSE
17515          } else if (!strcasecmp(v->name, "qsigchannelmapping")) {
17516             if (!strcasecmp(v->value, "logical")) {
17517                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_LOGICAL;
17518             } else if (!strcasecmp(v->value, "physical")) {
17519                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
17520             } else {
17521                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
17522             }
17523 #endif
17524          } else if (!strcasecmp(v->name, "discardremoteholdretrieval")) {
17525             confp->pri.pri.discardremoteholdretrieval = ast_true(v->value);
17526 #if defined(HAVE_PRI_SERVICE_MESSAGES)
17527          } else if (!strcasecmp(v->name, "service_message_support")) {
17528             /* assuming switchtype for this channel group has been configured already */
17529             if ((confp->pri.pri.switchtype == PRI_SWITCH_ATT4ESS 
17530                || confp->pri.pri.switchtype == PRI_SWITCH_LUCENT5E
17531                || confp->pri.pri.switchtype == PRI_SWITCH_NI2) && ast_true(v->value)) {
17532                confp->pri.pri.enable_service_message_support = 1;
17533             } else {
17534                confp->pri.pri.enable_service_message_support = 0;
17535             }
17536 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
17537 #ifdef HAVE_PRI_INBANDDISCONNECT
17538          } else if (!strcasecmp(v->name, "inbanddisconnect")) {
17539             confp->pri.pri.inbanddisconnect = ast_true(v->value);
17540 #endif
17541          } else if (!strcasecmp(v->name, "pritimer")) {
17542 #ifdef PRI_GETSET_TIMERS
17543             char tmp[20];
17544             char *timerc;
17545             char *c;
17546             int timer;
17547             int timeridx;
17548 
17549             ast_copy_string(tmp, v->value, sizeof(tmp));
17550             c = tmp;
17551             timerc = strsep(&c, ",");
17552             if (!ast_strlen_zero(timerc) && !ast_strlen_zero(c)) {
17553                timeridx = pri_timer2idx(timerc);
17554                timer = atoi(c);
17555                if (timeridx < 0 || PRI_MAX_TIMERS <= timeridx) {
17556                   ast_log(LOG_WARNING,
17557                      "'%s' is not a valid ISDN timer at line %d.\n", timerc,
17558                      v->lineno);
17559                } else if (!timer) {
17560                   ast_log(LOG_WARNING,
17561                      "'%s' is not a valid value for ISDN timer '%s' at line %d.\n",
17562                      c, timerc, v->lineno);
17563                } else {
17564                   confp->pri.pri.pritimers[timeridx] = timer;
17565                }
17566             } else {
17567                ast_log(LOG_WARNING,
17568                   "'%s' is not a valid ISDN timer configuration string at line %d.\n",
17569                   v->value, v->lineno);
17570             }
17571 #endif /* PRI_GETSET_TIMERS */
17572          } else if (!strcasecmp(v->name, "facilityenable")) {
17573             confp->pri.pri.facilityenable = ast_true(v->value);
17574 #if defined(HAVE_PRI_AOC_EVENTS)
17575          } else if (!strcasecmp(v->name, "aoc_enable")) {
17576             confp->pri.pri.aoc_passthrough_flag = 0;
17577             if (strchr(v->value, 's') || strchr(v->value, 'S')) {
17578                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_S;
17579             }
17580             if (strchr(v->value, 'd') || strchr(v->value, 'D')) {
17581                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_D;
17582             }
17583             if (strchr(v->value, 'e') || strchr(v->value, 'E')) {
17584                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_E;
17585             }
17586          } else if (!strcasecmp(v->name, "aoce_delayhangup")) {
17587             confp->pri.pri.aoce_delayhangup = ast_true(v->value);
17588 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
17589 #if defined(HAVE_PRI_CALL_HOLD)
17590          } else if (!strcasecmp(v->name, "hold_disconnect_transfer")) {
17591             confp->pri.pri.hold_disconnect_transfer = ast_true(v->value);
17592 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
17593 #if defined(HAVE_PRI_CCSS)
17594          } else if (!strcasecmp(v->name, "cc_ptmp_recall_mode")) {
17595             if (!strcasecmp(v->value, "global")) {
17596                confp->pri.pri.cc_ptmp_recall_mode = 0;/* globalRecall */
17597             } else if (!strcasecmp(v->value, "specific")) {
17598                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
17599             } else {
17600                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
17601             }
17602          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_req")) {
17603             if (!strcasecmp(v->value, "release")) {
17604                confp->pri.pri.cc_qsig_signaling_link_req = 0;/* release */
17605             } else if (!strcasecmp(v->value, "retain")) {
17606                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
17607             } else if (!strcasecmp(v->value, "do_not_care")) {
17608                confp->pri.pri.cc_qsig_signaling_link_req = 2;/* do-not-care */
17609             } else {
17610                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
17611             }
17612          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_rsp")) {
17613             if (!strcasecmp(v->value, "release")) {
17614                confp->pri.pri.cc_qsig_signaling_link_rsp = 0;/* release */
17615             } else if (!strcasecmp(v->value, "retain")) {
17616                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
17617             } else {
17618                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
17619             }
17620 #endif   /* defined(HAVE_PRI_CCSS) */
17621 #if defined(HAVE_PRI_CALL_WAITING)
17622          } else if (!strcasecmp(v->name, "max_call_waiting_calls")) {
17623             confp->pri.pri.max_call_waiting_calls = atoi(v->value);
17624             if (confp->pri.pri.max_call_waiting_calls < 0) {
17625                /* Negative values are not allowed. */
17626                confp->pri.pri.max_call_waiting_calls = 0;
17627             }
17628          } else if (!strcasecmp(v->name, "allow_call_waiting_calls")) {
17629             confp->pri.pri.allow_call_waiting_calls = ast_true(v->value);
17630 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
17631 #if defined(HAVE_PRI_MWI)
17632          } else if (!strcasecmp(v->name, "mwi_mailboxes")) {
17633             ast_copy_string(confp->pri.pri.mwi_mailboxes, v->value,
17634                sizeof(confp->pri.pri.mwi_mailboxes));
17635 #endif   /* defined(HAVE_PRI_MWI) */
17636          } else if (!strcasecmp(v->name, "append_msn_to_cid_tag")) {
17637             confp->pri.pri.append_msn_to_user_tag = ast_true(v->value);
17638          } else if (!strcasecmp(v->name, "layer1_presence")) {
17639             if (!strcasecmp(v->value, "required")) {
17640                confp->pri.pri.layer1_ignored = 0;
17641             } else if (!strcasecmp(v->value, "ignore")) {
17642                confp->pri.pri.layer1_ignored = 1;
17643             } else {
17644                /* Default */
17645                confp->pri.pri.layer1_ignored = 0;
17646             }
17647 #if defined(HAVE_PRI_L2_PERSISTENCE)
17648          } else if (!strcasecmp(v->name, "layer2_persistence")) {
17649             if (!strcasecmp(v->value, "keep_up")) {
17650                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_KEEP_UP;
17651             } else if (!strcasecmp(v->value, "leave_down")) {
17652                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_LEAVE_DOWN;
17653             } else {
17654                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_DEFAULT;
17655             }
17656 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
17657 #endif /* HAVE_PRI */
17658 #if defined(HAVE_SS7)
17659          } else if (!strcasecmp(v->name, "ss7type")) {
17660             if (!strcasecmp(v->value, "itu")) {
17661                cur_ss7type = SS7_ITU;
17662             } else if (!strcasecmp(v->value, "ansi")) {
17663                cur_ss7type = SS7_ANSI;
17664             } else
17665                ast_log(LOG_WARNING, "'%s' is an unknown ss7 switch type at line %d.!\n", v->value, v->lineno);
17666          } else if (!strcasecmp(v->name, "linkset")) {
17667             cur_linkset = atoi(v->value);
17668          } else if (!strcasecmp(v->name, "pointcode")) {
17669             cur_pointcode = parse_pointcode(v->value);
17670          } else if (!strcasecmp(v->name, "adjpointcode")) {
17671             cur_adjpointcode = parse_pointcode(v->value);
17672          } else if (!strcasecmp(v->name, "defaultdpc")) {
17673             cur_defaultdpc = parse_pointcode(v->value);
17674          } else if (!strcasecmp(v->name, "cicbeginswith")) {
17675             cur_cicbeginswith = atoi(v->value);
17676          } else if (!strcasecmp(v->name, "networkindicator")) {
17677             if (!strcasecmp(v->value, "national"))
17678                cur_networkindicator = SS7_NI_NAT;
17679             else if (!strcasecmp(v->value, "national_spare"))
17680                cur_networkindicator = SS7_NI_NAT_SPARE;
17681             else if (!strcasecmp(v->value, "international"))
17682                cur_networkindicator = SS7_NI_INT;
17683             else if (!strcasecmp(v->value, "international_spare"))
17684                cur_networkindicator = SS7_NI_INT_SPARE;
17685             else
17686                cur_networkindicator = -1;
17687          } else if (!strcasecmp(v->name, "ss7_internationalprefix")) {
17688             ast_copy_string(confp->ss7.ss7.internationalprefix, v->value, sizeof(confp->ss7.ss7.internationalprefix));
17689          } else if (!strcasecmp(v->name, "ss7_nationalprefix")) {
17690             ast_copy_string(confp->ss7.ss7.nationalprefix, v->value, sizeof(confp->ss7.ss7.nationalprefix));
17691          } else if (!strcasecmp(v->name, "ss7_subscriberprefix")) {
17692             ast_copy_string(confp->ss7.ss7.subscriberprefix, v->value, sizeof(confp->ss7.ss7.subscriberprefix));
17693          } else if (!strcasecmp(v->name, "ss7_unknownprefix")) {
17694             ast_copy_string(confp->ss7.ss7.unknownprefix, v->value, sizeof(confp->ss7.ss7.unknownprefix));
17695          } else if (!strcasecmp(v->name, "ss7_called_nai")) {
17696             if (!strcasecmp(v->value, "national")) {
17697                confp->ss7.ss7.called_nai = SS7_NAI_NATIONAL;
17698             } else if (!strcasecmp(v->value, "international")) {
17699                confp->ss7.ss7.called_nai = SS7_NAI_INTERNATIONAL;
17700             } else if (!strcasecmp(v->value, "subscriber")) {
17701                confp->ss7.ss7.called_nai = SS7_NAI_SUBSCRIBER;
17702             } else if (!strcasecmp(v->value, "unknown")) {
17703                confp->ss7.ss7.called_nai = SS7_NAI_UNKNOWN;
17704             } else if (!strcasecmp(v->value, "dynamic")) {
17705                confp->ss7.ss7.called_nai = SS7_NAI_DYNAMIC;
17706             } else {
17707                ast_log(LOG_WARNING, "Unknown SS7 called_nai '%s' at line %d.\n", v->value, v->lineno);
17708             }
17709          } else if (!strcasecmp(v->name, "ss7_calling_nai")) {
17710             if (!strcasecmp(v->value, "national")) {
17711                confp->ss7.ss7.calling_nai = SS7_NAI_NATIONAL;
17712             } else if (!strcasecmp(v->value, "international")) {
17713                confp->ss7.ss7.calling_nai = SS7_NAI_INTERNATIONAL;
17714             } else if (!strcasecmp(v->value, "subscriber")) {
17715                confp->ss7.ss7.calling_nai = SS7_NAI_SUBSCRIBER;
17716             } else if (!strcasecmp(v->value, "unknown")) {
17717                confp->ss7.ss7.calling_nai = SS7_NAI_UNKNOWN;
17718             } else if (!strcasecmp(v->value, "dynamic")) {
17719                confp->ss7.ss7.calling_nai = SS7_NAI_DYNAMIC;
17720             } else {
17721                ast_log(LOG_WARNING, "Unknown SS7 calling_nai '%s' at line %d.\n", v->value, v->lineno);
17722             }
17723          } else if (!strcasecmp(v->name, "sigchan")) {
17724             int sigchan, res;
17725             sigchan = atoi(v->value);
17726             res = linkset_addsigchan(sigchan);
17727             if (res < 0)
17728                return -1;
17729 
17730          } else if (!strcasecmp(v->name, "ss7_explicitacm")) {
17731             struct dahdi_ss7 *link;
17732             link = ss7_resolve_linkset(cur_linkset);
17733             if (!link) {
17734                ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
17735                return -1;
17736             }
17737             if (ast_true(v->value))
17738                link->ss7.flags |= LINKSET_FLAG_EXPLICITACM;
17739 #endif   /* defined(HAVE_SS7) */
17740 #ifdef HAVE_OPENR2
17741          } else if (!strcasecmp(v->name, "mfcr2_advanced_protocol_file")) {
17742             ast_copy_string(confp->mfcr2.r2proto_file, v->value, sizeof(confp->mfcr2.r2proto_file));
17743             ast_log(LOG_WARNING, "MFC/R2 Protocol file '%s' will be used, you only should use this if you *REALLY KNOW WHAT YOU ARE DOING*.\n", confp->mfcr2.r2proto_file);
17744          } else if (!strcasecmp(v->name, "mfcr2_logdir")) {
17745             ast_copy_string(confp->mfcr2.logdir, v->value, sizeof(confp->mfcr2.logdir));
17746          } else if (!strcasecmp(v->name, "mfcr2_variant")) {
17747             confp->mfcr2.variant = openr2_proto_get_variant(v->value);
17748             if (OR2_VAR_UNKNOWN == confp->mfcr2.variant) {
17749                ast_log(LOG_WARNING, "Unknown MFC/R2 variant '%s' at line %d, defaulting to ITU.\n", v->value, v->lineno);
17750                confp->mfcr2.variant = OR2_VAR_ITU;
17751             }
17752          } else if (!strcasecmp(v->name, "mfcr2_mfback_timeout")) {
17753             confp->mfcr2.mfback_timeout = atoi(v->value);
17754             if (!confp->mfcr2.mfback_timeout) {
17755                ast_log(LOG_WARNING, "MF timeout of 0? hum, I will protect you from your ignorance. Setting default.\n");
17756                confp->mfcr2.mfback_timeout = -1;
17757             } else if (confp->mfcr2.mfback_timeout > 0 && confp->mfcr2.mfback_timeout < 500) {
17758                ast_log(LOG_WARNING, "MF timeout less than 500ms is not recommended, you have been warned!\n");
17759             }
17760          } else if (!strcasecmp(v->name, "mfcr2_metering_pulse_timeout")) {
17761             confp->mfcr2.metering_pulse_timeout = atoi(v->value);
17762             if (confp->mfcr2.metering_pulse_timeout > 500) {
17763                ast_log(LOG_WARNING, "Metering pulse timeout greater than 500ms is not recommended, you have been warned!\n");
17764             }
17765          } else if (!strcasecmp(v->name, "mfcr2_get_ani_first")) {
17766             confp->mfcr2.get_ani_first = ast_true(v->value) ? 1 : 0;
17767          } else if (!strcasecmp(v->name, "mfcr2_double_answer")) {
17768             confp->mfcr2.double_answer = ast_true(v->value) ? 1 : 0;
17769          } else if (!strcasecmp(v->name, "mfcr2_charge_calls")) {
17770             confp->mfcr2.charge_calls = ast_true(v->value) ? 1 : 0;
17771          } else if (!strcasecmp(v->name, "mfcr2_accept_on_offer")) {
17772             confp->mfcr2.accept_on_offer = ast_true(v->value) ? 1 : 0;
17773          } else if (!strcasecmp(v->name, "mfcr2_allow_collect_calls")) {
17774             confp->mfcr2.allow_collect_calls = ast_true(v->value) ? 1 : 0;
17775          } else if (!strcasecmp(v->name, "mfcr2_forced_release")) {
17776             confp->mfcr2.forced_release = ast_true(v->value) ? 1 : 0;
17777          } else if (!strcasecmp(v->name, "mfcr2_immediate_accept")) {
17778             confp->mfcr2.immediate_accept = ast_true(v->value) ? 1 : 0;
17779 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
17780          } else if (!strcasecmp(v->name, "mfcr2_skip_category")) {
17781             confp->mfcr2.skip_category_request = ast_true(v->value) ? 1 : 0;
17782 #endif
17783          } else if (!strcasecmp(v->name, "mfcr2_call_files")) {
17784             confp->mfcr2.call_files = ast_true(v->value) ? 1 : 0;
17785          } else if (!strcasecmp(v->name, "mfcr2_max_ani")) {
17786             confp->mfcr2.max_ani = atoi(v->value);
17787             if (confp->mfcr2.max_ani >= AST_MAX_EXTENSION){
17788                confp->mfcr2.max_ani = AST_MAX_EXTENSION - 1;
17789             }
17790          } else if (!strcasecmp(v->name, "mfcr2_max_dnis")) {
17791             confp->mfcr2.max_dnis = atoi(v->value);
17792             if (confp->mfcr2.max_dnis >= AST_MAX_EXTENSION){
17793                confp->mfcr2.max_dnis = AST_MAX_EXTENSION - 1;
17794             }
17795          } else if (!strcasecmp(v->name, "mfcr2_category")) {
17796             confp->mfcr2.category = openr2_proto_get_category(v->value);
17797             if (OR2_CALLING_PARTY_CATEGORY_UNKNOWN == confp->mfcr2.category) {
17798                confp->mfcr2.category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER;
17799                ast_log(LOG_WARNING, "Invalid MFC/R2 caller category '%s' at line %d. Using national subscriber as default.\n",
17800                      v->value, v->lineno);
17801             }
17802          } else if (!strcasecmp(v->name, "mfcr2_logging")) {
17803             openr2_log_level_t tmplevel;
17804             char *clevel;
17805             char *logval = ast_strdupa(v->value);
17806             while (logval) {
17807                clevel = strsep(&logval,",");
17808                if (-1 == (tmplevel = openr2_log_get_level(clevel))) {
17809                   ast_log(LOG_WARNING, "Ignoring invalid logging level: '%s' at line %d.\n", clevel, v->lineno);
17810                   continue;
17811                }
17812                confp->mfcr2.loglevel |= tmplevel;
17813             }
17814 #endif /* HAVE_OPENR2 */
17815          } else if (!strcasecmp(v->name, "cadence")) {
17816             /* setup to scan our argument */
17817             int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
17818             int i;
17819             struct dahdi_ring_cadence new_cadence;
17820             int cid_location = -1;
17821             int firstcadencepos = 0;
17822             char original_args[80];
17823             int cadence_is_ok = 1;
17824 
17825             ast_copy_string(original_args, v->value, sizeof(original_args));
17826             /* 16 cadences allowed (8 pairs) */
17827             element_count = sscanf(v->value, "%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d,%30d", &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], &c[8], &c[9], &c[10], &c[11], &c[12], &c[13], &c[14], &c[15]);
17828 
17829             /* Cadence must be even (on/off) */
17830             if (element_count % 2 == 1) {
17831                ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s at line %d.\n", original_args, v->lineno);
17832                cadence_is_ok = 0;
17833             }
17834 
17835             /* Ring cadences cannot be negative */
17836             for (i = 0; i < element_count; i++) {
17837                if (c[i] == 0) {
17838                   ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s at line %d.\n", original_args, v->lineno);
17839                   cadence_is_ok = 0;
17840                   break;
17841                } else if (c[i] < 0) {
17842                   if (i % 2 == 1) {
17843                      /* Silence duration, negative possibly okay */
17844                      if (cid_location == -1) {
17845                         cid_location = i;
17846                         c[i] *= -1;
17847                      } else {
17848                         ast_log(LOG_ERROR, "CID location specified twice: %s at line %d.\n", original_args, v->lineno);
17849                         cadence_is_ok = 0;
17850                         break;
17851                      }
17852                   } else {
17853                      if (firstcadencepos == 0) {
17854                         firstcadencepos = i; /* only recorded to avoid duplicate specification */
17855                                  /* duration will be passed negative to the DAHDI driver */
17856                      } else {
17857                          ast_log(LOG_ERROR, "First cadence position specified twice: %s at line %d.\n", original_args, v->lineno);
17858                         cadence_is_ok = 0;
17859                         break;
17860                      }
17861                   }
17862                }
17863             }
17864 
17865             /* Substitute our scanned cadence */
17866             for (i = 0; i < 16; i++) {
17867                new_cadence.ringcadence[i] = c[i];
17868             }
17869 
17870             if (cadence_is_ok) {
17871                /* ---we scanned it without getting annoyed; now some sanity checks--- */
17872                if (element_count < 2) {
17873                   ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s at line %d.\n", original_args, v->lineno);
17874                } else {
17875                   if (cid_location == -1) {
17876                      /* user didn't say; default to first pause */
17877                      cid_location = 1;
17878                   } else {
17879                      /* convert element_index to cidrings value */
17880                      cid_location = (cid_location + 1) / 2;
17881                   }
17882                   /* ---we like their cadence; try to install it--- */
17883                   if (!user_has_defined_cadences++)
17884                      /* this is the first user-defined cadence; clear the default user cadences */
17885                      num_cadence = 0;
17886                   if ((num_cadence+1) >= NUM_CADENCE_MAX)
17887                      ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s at line %d.\n", NUM_CADENCE_MAX, original_args, v->lineno);
17888                   else {
17889                      cadences[num_cadence] = new_cadence;
17890                      cidrings[num_cadence++] = cid_location;
17891                      ast_verb(3, "cadence 'r%d' added: %s\n",num_cadence,original_args);
17892                   }
17893                }
17894             }
17895          } else if (!strcasecmp(v->name, "ringtimeout")) {
17896             ringt_base = (atoi(v->value) * 8) / READ_SIZE;
17897          } else if (!strcasecmp(v->name, "prewink")) {
17898             confp->timing.prewinktime = atoi(v->value);
17899          } else if (!strcasecmp(v->name, "preflash")) {
17900             confp->timing.preflashtime = atoi(v->value);
17901          } else if (!strcasecmp(v->name, "wink")) {
17902             confp->timing.winktime = atoi(v->value);
17903          } else if (!strcasecmp(v->name, "flash")) {
17904             confp->timing.flashtime = atoi(v->value);
17905          } else if (!strcasecmp(v->name, "start")) {
17906             confp->timing.starttime = atoi(v->value);
17907          } else if (!strcasecmp(v->name, "rxwink")) {
17908             confp->timing.rxwinktime = atoi(v->value);
17909          } else if (!strcasecmp(v->name, "rxflash")) {
17910             confp->timing.rxflashtime = atoi(v->value);
17911          } else if (!strcasecmp(v->name, "debounce")) {
17912             confp->timing.debouncetime = atoi(v->value);
17913          } else if (!strcasecmp(v->name, "toneduration")) {
17914             int toneduration;
17915             int ctlfd;
17916             int res;
17917             struct dahdi_dialparams dps;
17918 
17919             ctlfd = open("/dev/dahdi/ctl", O_RDWR);
17920             if (ctlfd == -1) {
17921                ast_log(LOG_ERROR, "Unable to open /dev/dahdi/ctl to set toneduration at line %d.\n", v->lineno);
17922                return -1;
17923             }
17924 
17925             toneduration = atoi(v->value);
17926             if (toneduration > -1) {
17927                memset(&dps, 0, sizeof(dps));
17928 
17929                dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
17930                res = ioctl(ctlfd, DAHDI_SET_DIALPARAMS, &dps);
17931                if (res < 0) {
17932                   ast_log(LOG_ERROR, "Invalid tone duration: %d ms at line %d: %s\n", toneduration, v->lineno, strerror(errno));
17933                   close(ctlfd);
17934                   return -1;
17935                }
17936             }
17937             close(ctlfd);
17938          } else if (!strcasecmp(v->name, "defaultcic")) {
17939             ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
17940          } else if (!strcasecmp(v->name, "defaultozz")) {
17941             ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
17942          } else if (!strcasecmp(v->name, "mwilevel")) {
17943             mwilevel = atoi(v->value);
17944          } else if (!strcasecmp(v->name, "dtmfcidlevel")) {
17945             dtmfcid_level = atoi(v->value);
17946          } else if (!strcasecmp(v->name, "reportalarms")) {
17947             if (!strcasecmp(v->value, "all"))
17948                report_alarms = REPORT_CHANNEL_ALARMS | REPORT_SPAN_ALARMS;
17949             if (!strcasecmp(v->value, "none"))
17950                report_alarms = 0;
17951             else if (!strcasecmp(v->value, "channels"))
17952                report_alarms = REPORT_CHANNEL_ALARMS;
17953             else if (!strcasecmp(v->value, "spans"))
17954                report_alarms = REPORT_SPAN_ALARMS;
17955           }
17956       } else if (!(options & PROC_DAHDI_OPT_NOWARN) )
17957          ast_log(LOG_WARNING, "Ignoring any changes to '%s' (on reload) at line %d.\n", v->name, v->lineno);
17958    }
17959 
17960    /* Since confp has already filled invidual dahdi_pvt objects with channels at this point, clear the variables in confp's pvt. */
17961    if (confp->chan.vars) {
17962       ast_variables_destroy(confp->chan.vars);
17963       confp->chan.vars = NULL;
17964    }
17965 
17966    if (dahdichan) {
17967       /* Process the deferred dahdichan value. */
17968       if (build_channels(confp, dahdichan->value, reload, dahdichan->lineno,
17969          &found_pseudo)) {
17970          if (confp->ignore_failed_channels) {
17971             ast_log(LOG_WARNING,
17972                "Dahdichan '%s' failure ignored: ignore_failed_channels.\n",
17973                dahdichan->value);
17974          } else {
17975             return -1;
17976          }
17977       }
17978    }
17979 
17980    /* mark the first channels of each DAHDI span to watch for their span alarms */
17981    for (tmp = iflist, y=-1; tmp; tmp = tmp->next) {
17982       if (!tmp->destroy && tmp->span != y) {
17983          tmp->manages_span_alarms = 1;
17984          y = tmp->span; 
17985       } else {
17986          tmp->manages_span_alarms = 0;
17987       }
17988    }
17989 
17990    /*< \todo why check for the pseudo in the per-channel section.
17991     * Any actual use for manual setup of the pseudo channel? */
17992    if (!found_pseudo && reload != 1 && !(options & PROC_DAHDI_OPT_NOCHAN)) {
17993       /* use the default configuration for a channel, so
17994          that any settings from real configured channels
17995          don't "leak" into the pseudo channel config
17996       */
17997       struct dahdi_chan_conf conf = dahdi_chan_conf_default();
17998 
17999       if (conf.chan.cc_params) {
18000          tmp = mkintf(CHAN_PSEUDO, &conf, reload);
18001       } else {
18002          tmp = NULL;
18003       }
18004       if (tmp) {
18005          ast_verb(3, "Automatically generated pseudo channel\n");
18006       } else {
18007          ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
18008       }
18009       ast_cc_config_params_destroy(conf.chan.cc_params);
18010    }
18011    return 0;
18012 }
18013 
18014 /*!
18015  * \internal
18016  * \brief Deep copy struct dahdi_chan_conf.
18017  * \since 1.8
18018  *
18019  * \param dest Destination.
18020  * \param src Source.
18021  *
18022  * \return Nothing
18023  */
18024 static void deep_copy_dahdi_chan_conf(struct dahdi_chan_conf *dest, const struct dahdi_chan_conf *src)
18025 {
18026    struct ast_cc_config_params *cc_params;
18027 
18028    cc_params = dest->chan.cc_params;
18029    *dest = *src;
18030    dest->chan.cc_params = cc_params;
18031    ast_cc_copy_config_params(dest->chan.cc_params, src->chan.cc_params);
18032 }
18033 
18034 /*!
18035  * \internal
18036  * \brief Setup DAHDI channel driver.
18037  *
18038  * \param reload enum: load_module(0), reload(1), restart(2).
18039  * \param default_conf Default config parameters.  So cc_params can be properly destroyed.
18040  * \param base_conf Default config parameters per section.  So cc_params can be properly destroyed.
18041  * \param conf Local config parameters.  So cc_params can be properly destroyed.
18042  *
18043  * \retval 0 on success.
18044  * \retval -1 on error.
18045  */
18046 static int setup_dahdi_int(int reload, struct dahdi_chan_conf *default_conf, struct dahdi_chan_conf *base_conf, struct dahdi_chan_conf *conf)
18047 {
18048    struct ast_config *cfg;
18049    struct ast_config *ucfg;
18050    struct ast_variable *v;
18051    struct ast_flags config_flags = { reload == 1 ? CONFIG_FLAG_FILEUNCHANGED : 0 };
18052    const char *chans;
18053    const char *cat;
18054    int res;
18055 
18056 #ifdef HAVE_PRI
18057    char *c;
18058    int spanno;
18059    int i;
18060    int logicalspan;
18061    int trunkgroup;
18062    int dchannels[SIG_PRI_NUM_DCHANS];
18063 #endif
18064    int have_cfg_now;
18065    static int had_cfg_before = 1;/* So initial load will complain if we don't have cfg. */
18066 
18067    cfg = ast_config_load(config, config_flags);
18068    have_cfg_now = !!cfg;
18069    if (!cfg) {
18070       /* Error if we have no config file */
18071       if (had_cfg_before) {
18072          ast_log(LOG_ERROR, "Unable to load config %s\n", config);
18073          ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18074       }
18075       cfg = ast_config_new();/* Dummy config */
18076       if (!cfg) {
18077          return 0;
18078       }
18079       ucfg = ast_config_load("users.conf", config_flags);
18080       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
18081          ast_config_destroy(cfg);
18082          return 0;
18083       }
18084       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18085          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18086          ast_config_destroy(cfg);
18087          return 0;
18088       }
18089    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
18090       ucfg = ast_config_load("users.conf", config_flags);
18091       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
18092          return 0;
18093       }
18094       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18095          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18096          return 0;
18097       }
18098       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18099       cfg = ast_config_load(config, config_flags);
18100       have_cfg_now = !!cfg;
18101       if (!cfg) {
18102          if (had_cfg_before) {
18103             /* We should have been able to load the config. */
18104             ast_log(LOG_ERROR, "Bad. Unable to load config %s\n", config);
18105             ast_config_destroy(ucfg);
18106             return 0;
18107          }
18108          cfg = ast_config_new();/* Dummy config */
18109          if (!cfg) {
18110             ast_config_destroy(ucfg);
18111             return 0;
18112          }
18113       } else if (cfg == CONFIG_STATUS_FILEINVALID) {
18114          ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
18115          ast_config_destroy(ucfg);
18116          return 0;
18117       }
18118    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
18119       ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
18120       return 0;
18121    } else {
18122       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18123       ucfg = ast_config_load("users.conf", config_flags);
18124       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18125          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18126          ast_config_destroy(cfg);
18127          return 0;
18128       }
18129    }
18130    had_cfg_before = have_cfg_now;
18131 
18132    /* It's a little silly to lock it, but we might as well just to be sure */
18133    ast_mutex_lock(&iflock);
18134 #ifdef HAVE_PRI
18135    if (reload != 1) {
18136       /* Process trunkgroups first */
18137       v = ast_variable_browse(cfg, "trunkgroups");
18138       while (v) {
18139          if (!strcasecmp(v->name, "trunkgroup")) {
18140             trunkgroup = atoi(v->value);
18141             if (trunkgroup > 0) {
18142                if ((c = strchr(v->value, ','))) {
18143                   i = 0;
18144                   memset(dchannels, 0, sizeof(dchannels));
18145                   while (c && (i < SIG_PRI_NUM_DCHANS)) {
18146                      dchannels[i] = atoi(c + 1);
18147                      if (dchannels[i] < 0) {
18148                         ast_log(LOG_WARNING, "D-channel for trunk group %d must be a postiive number at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18149                      } else
18150                         i++;
18151                      c = strchr(c + 1, ',');
18152                   }
18153                   if (i) {
18154                      if (pri_create_trunkgroup(trunkgroup, dchannels)) {
18155                         ast_log(LOG_WARNING, "Unable to create trunk group %d with Primary D-channel %d at line %d of chan_dahdi.conf\n", trunkgroup, dchannels[0], v->lineno);
18156                   } else
18157                         ast_verb(2, "Created trunk group %d with Primary D-channel %d and %d backup%s\n", trunkgroup, dchannels[0], i - 1, (i == 1) ? "" : "s");
18158                   } else
18159                      ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18160                } else
18161                   ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18162             } else
18163                ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of chan_dahdi.conf\n", v->lineno);
18164          } else if (!strcasecmp(v->name, "spanmap")) {
18165             spanno = atoi(v->value);
18166             if (spanno > 0) {
18167                if ((c = strchr(v->value, ','))) {
18168                   trunkgroup = atoi(c + 1);
18169                   if (trunkgroup > 0) {
18170                      if ((c = strchr(c + 1, ',')))
18171                         logicalspan = atoi(c + 1);
18172                      else
18173                         logicalspan = 0;
18174                      if (logicalspan >= 0) {
18175                         if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
18176                            ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
18177                      } else
18178                            ast_verb(2, "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
18179                      } else
18180                         ast_log(LOG_WARNING, "Logical span must be a postive number, or '0' (for unspecified) at line %d of chan_dahdi.conf\n", v->lineno);
18181                   } else
18182                      ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of chan_dahdi.conf\n", v->lineno);
18183                } else
18184                   ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of chan_dahdi.conf\n", v->lineno);
18185             } else
18186                ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of chan_dahdi.conf\n", v->lineno);
18187          } else {
18188             ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
18189          }
18190          v = v->next;
18191       }
18192    }
18193 #endif
18194 
18195    /* Copy the default jb config over global_jbconf */
18196    memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
18197 
18198    mwimonitornotify[0] = '\0';
18199 
18200    v = ast_variable_browse(cfg, "channels");
18201    if ((res = process_dahdi(base_conf,
18202       "" /* Must be empty for the channels category.  Silly voicemail mailbox. */,
18203       v, reload, 0))) {
18204       ast_mutex_unlock(&iflock);
18205       ast_config_destroy(cfg);
18206       if (ucfg) {
18207          ast_config_destroy(ucfg);
18208       }
18209       return res;
18210    }
18211 
18212    /* Now get configuration from all normal sections in chan_dahdi.conf: */
18213    for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
18214       /* [channels] and [trunkgroups] are used. Let's also reserve
18215        * [globals] and [general] for future use
18216        */
18217       if (!strcasecmp(cat, "general") ||
18218          !strcasecmp(cat, "trunkgroups") ||
18219          !strcasecmp(cat, "globals") ||
18220          !strcasecmp(cat, "channels")) {
18221          continue;
18222       }
18223 
18224       chans = ast_variable_retrieve(cfg, cat, "dahdichan");
18225       if (ast_strlen_zero(chans)) {
18226          /* Section is useless without a dahdichan value present. */
18227          continue;
18228       }
18229 
18230       /* Copy base_conf to conf. */
18231       deep_copy_dahdi_chan_conf(conf, base_conf);
18232 
18233       if ((res = process_dahdi(conf, cat, ast_variable_browse(cfg, cat), reload, PROC_DAHDI_OPT_NOCHAN))) {
18234          ast_mutex_unlock(&iflock);
18235          ast_config_destroy(cfg);
18236          if (ucfg) {
18237             ast_config_destroy(ucfg);
18238          }
18239          return res;
18240       }
18241    }
18242 
18243    ast_config_destroy(cfg);
18244 
18245    if (ucfg) {
18246       /* Reset base_conf, so things don't leak from chan_dahdi.conf */
18247       deep_copy_dahdi_chan_conf(base_conf, default_conf);
18248       process_dahdi(base_conf,
18249          "" /* Must be empty for the general category.  Silly voicemail mailbox. */,
18250          ast_variable_browse(ucfg, "general"), 1, 0);
18251 
18252       for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
18253          if (!strcasecmp(cat, "general")) {
18254             continue;
18255          }
18256 
18257          chans = ast_variable_retrieve(ucfg, cat, "dahdichan");
18258          if (ast_strlen_zero(chans)) {
18259             /* Section is useless without a dahdichan value present. */
18260             continue;
18261          }
18262 
18263          /* Copy base_conf to conf. */
18264          deep_copy_dahdi_chan_conf(conf, base_conf);
18265 
18266          if ((res = process_dahdi(conf, cat, ast_variable_browse(ucfg, cat), reload, PROC_DAHDI_OPT_NOCHAN | PROC_DAHDI_OPT_NOWARN))) {
18267             ast_config_destroy(ucfg);
18268             ast_mutex_unlock(&iflock);
18269             return res;
18270          }
18271       }
18272       ast_config_destroy(ucfg);
18273    }
18274    ast_mutex_unlock(&iflock);
18275 
18276 #ifdef HAVE_PRI
18277    if (reload != 1) {
18278       int x;
18279       for (x = 0; x < NUM_SPANS; x++) {
18280          if (pris[x].pri.pvts[0]) {
18281             prepare_pri(pris + x);
18282             if (sig_pri_start_pri(&pris[x].pri)) {
18283                ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
18284                return -1;
18285             } else
18286                ast_verb(2, "Starting D-Channel on span %d\n", x + 1);
18287          }
18288       }
18289    }
18290 #endif
18291 #if defined(HAVE_SS7)
18292    if (reload != 1) {
18293       int x;
18294       for (x = 0; x < NUM_SPANS; x++) {
18295          if (linksets[x].ss7.ss7) {
18296             linksets[x].ss7.calls = &dahdi_ss7_callbacks;
18297             if (ast_pthread_create(&linksets[x].ss7.master, NULL, ss7_linkset, &linksets[x].ss7)) {
18298                ast_log(LOG_ERROR, "Unable to start SS7 linkset on span %d\n", x + 1);
18299                return -1;
18300             } else
18301                ast_verb(2, "Starting SS7 linkset on span %d\n", x + 1);
18302          }
18303       }
18304    }
18305 #endif   /* defined(HAVE_SS7) */
18306 #ifdef HAVE_OPENR2
18307    if (reload != 1) {
18308       int x;
18309       for (x = 0; x < r2links_count; x++) {
18310          if (ast_pthread_create(&r2links[x]->r2master, NULL, mfcr2_monitor, r2links[x])) {
18311             ast_log(LOG_ERROR, "Unable to start R2 monitor on channel group %d\n", x + 1);
18312             return -1;
18313          } else {
18314             ast_verb(2, "Starting R2 monitor on channel group %d\n", x + 1);
18315          }
18316       }
18317    }
18318 #endif
18319    /* And start the monitor for the first time */
18320    restart_monitor();
18321    return 0;
18322 }
18323 
18324 /*!
18325  * \internal
18326  * \brief Setup DAHDI channel driver.
18327  *
18328  * \param reload enum: load_module(0), reload(1), restart(2).
18329  *
18330  * \retval 0 on success.
18331  * \retval -1 on error.
18332  */
18333 static int setup_dahdi(int reload)
18334 {
18335    int res;
18336    struct dahdi_chan_conf default_conf = dahdi_chan_conf_default();
18337    struct dahdi_chan_conf base_conf = dahdi_chan_conf_default();
18338    struct dahdi_chan_conf conf = dahdi_chan_conf_default();
18339 
18340    if (default_conf.chan.cc_params && base_conf.chan.cc_params && conf.chan.cc_params) {
18341       res = setup_dahdi_int(reload, &default_conf, &base_conf, &conf);
18342    } else {
18343       res = -1;
18344    }
18345    ast_cc_config_params_destroy(default_conf.chan.cc_params);
18346    ast_cc_config_params_destroy(base_conf.chan.cc_params);
18347    ast_cc_config_params_destroy(conf.chan.cc_params);
18348 
18349    return res;
18350 }
18351 
18352 /*!
18353  * \internal
18354  * \brief Callback used to generate the dahdi status tree.
18355  * \param[in] search The search pattern tree.
18356  * \retval NULL on error.
18357  * \retval non-NULL The generated tree.
18358  */
18359 static int dahdi_status_data_provider_get(const struct ast_data_search *search,
18360       struct ast_data *data_root)
18361 {
18362    int ctl, res, span;
18363    struct ast_data *data_span, *data_alarms;
18364    struct dahdi_spaninfo s;
18365 
18366    ctl = open("/dev/dahdi/ctl", O_RDWR);
18367    if (ctl < 0) {
18368       ast_log(LOG_ERROR, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
18369       return -1;
18370    }
18371    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
18372       s.spanno = span;
18373       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
18374       if (res) {
18375          continue;
18376       }
18377 
18378       data_span = ast_data_add_node(data_root, "span");
18379       if (!data_span) {
18380          continue;
18381       }
18382       ast_data_add_str(data_span, "description", s.desc);
18383 
18384       /* insert the alarms status */
18385       data_alarms = ast_data_add_node(data_span, "alarms");
18386       if (!data_alarms) {
18387          continue;
18388       }
18389 
18390       ast_data_add_bool(data_alarms, "BLUE", s.alarms & DAHDI_ALARM_BLUE);
18391       ast_data_add_bool(data_alarms, "YELLOW", s.alarms & DAHDI_ALARM_YELLOW);
18392       ast_data_add_bool(data_alarms, "RED", s.alarms & DAHDI_ALARM_RED);
18393       ast_data_add_bool(data_alarms, "LOOPBACK", s.alarms & DAHDI_ALARM_LOOPBACK);
18394       ast_data_add_bool(data_alarms, "RECOVER", s.alarms & DAHDI_ALARM_RECOVER);
18395       ast_data_add_bool(data_alarms, "NOTOPEN", s.alarms & DAHDI_ALARM_NOTOPEN);
18396 
18397       ast_data_add_int(data_span, "irqmisses", s.irqmisses);
18398       ast_data_add_int(data_span, "bpviol", s.bpvcount);
18399       ast_data_add_int(data_span, "crc4", s.crc4count);
18400       ast_data_add_str(data_span, "framing", s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
18401                      s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
18402                      s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
18403                      "CAS");
18404       ast_data_add_str(data_span, "coding",  s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
18405                      s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
18406                      s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
18407                      "Unknown");
18408       ast_data_add_str(data_span, "options", s.lineconfig & DAHDI_CONFIG_CRC4 ?
18409                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
18410                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "");
18411       ast_data_add_str(data_span, "lbo", lbostr[s.lbo]);
18412 
18413       /* if this span doesn't match remove it. */
18414       if (!ast_data_search_match(search, data_span)) {
18415          ast_data_remove_node(data_root, data_span);
18416       }
18417    }
18418    close(ctl);
18419 
18420    return 0;
18421 }
18422 
18423 /*!
18424  * \internal
18425  * \brief Callback used to generate the dahdi channels tree.
18426  * \param[in] search The search pattern tree.
18427  * \retval NULL on error.
18428  * \retval non-NULL The generated tree.
18429  */
18430 static int dahdi_channels_data_provider_get(const struct ast_data_search *search,
18431       struct ast_data *data_root)
18432 {
18433    struct dahdi_pvt *tmp;
18434    struct ast_data *data_channel;
18435 
18436    ast_mutex_lock(&iflock);
18437    for (tmp = iflist; tmp; tmp = tmp->next) {
18438       data_channel = ast_data_add_node(data_root, "channel");
18439       if (!data_channel) {
18440          continue;
18441       }
18442 
18443       ast_data_add_structure(dahdi_pvt, data_channel, tmp);
18444 
18445       /* if this channel doesn't match remove it. */
18446       if (!ast_data_search_match(search, data_channel)) {
18447          ast_data_remove_node(data_root, data_channel);
18448       }
18449    }
18450    ast_mutex_unlock(&iflock);
18451 
18452    return 0;
18453 }
18454 
18455 /*!
18456  * \internal
18457  * \brief Callback used to generate the dahdi channels tree.
18458  * \param[in] search The search pattern tree.
18459  * \retval NULL on error.
18460  * \retval non-NULL The generated tree.
18461  */
18462 static int dahdi_version_data_provider_get(const struct ast_data_search *search,
18463       struct ast_data *data_root)
18464 {
18465    int pseudo_fd = -1;
18466    struct dahdi_versioninfo vi = {
18467       .version = "Unknown",
18468       .echo_canceller = "Unknown"
18469    };
18470 
18471    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
18472       ast_log(LOG_ERROR, "Failed to open control file to get version.\n");
18473       return -1;
18474    }
18475 
18476    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi)) {
18477       ast_log(LOG_ERROR, "Failed to get DAHDI version: %s\n", strerror(errno));
18478    }
18479 
18480    close(pseudo_fd);
18481 
18482    ast_data_add_str(data_root, "value", vi.version);
18483    ast_data_add_str(data_root, "echocanceller", vi.echo_canceller);
18484 
18485    return 0;
18486 }
18487 
18488 static const struct ast_data_handler dahdi_status_data_provider = {
18489    .version = AST_DATA_HANDLER_VERSION,
18490    .get = dahdi_status_data_provider_get
18491 };
18492 
18493 static const struct ast_data_handler dahdi_channels_data_provider = {
18494    .version = AST_DATA_HANDLER_VERSION,
18495    .get = dahdi_channels_data_provider_get
18496 };
18497 
18498 static const struct ast_data_handler dahdi_version_data_provider = {
18499    .version = AST_DATA_HANDLER_VERSION,
18500    .get = dahdi_version_data_provider_get
18501 };
18502 
18503 static const struct ast_data_entry dahdi_data_providers[] = {
18504    AST_DATA_ENTRY("asterisk/channel/dahdi/status", &dahdi_status_data_provider),
18505    AST_DATA_ENTRY("asterisk/channel/dahdi/channels", &dahdi_channels_data_provider),
18506    AST_DATA_ENTRY("asterisk/channel/dahdi/version", &dahdi_version_data_provider)
18507 };
18508 
18509 static int load_module(void)
18510 {
18511    int res;
18512 #if defined(HAVE_PRI) || defined(HAVE_SS7)
18513    int y;
18514 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
18515 
18516 #ifdef HAVE_PRI
18517    memset(pris, 0, sizeof(pris));
18518    for (y = 0; y < NUM_SPANS; y++) {
18519       sig_pri_init_pri(&pris[y].pri);
18520    }
18521    pri_set_error(dahdi_pri_error);
18522    pri_set_message(dahdi_pri_message);
18523    ast_register_application_xml(dahdi_send_keypad_facility_app, dahdi_send_keypad_facility_exec);
18524 #ifdef HAVE_PRI_PROG_W_CAUSE
18525    ast_register_application_xml(dahdi_send_callrerouting_facility_app, dahdi_send_callrerouting_facility_exec);
18526 #endif
18527 #if defined(HAVE_PRI_CCSS)
18528    if (ast_cc_agent_register(&dahdi_pri_cc_agent_callbacks)
18529       || ast_cc_monitor_register(&dahdi_pri_cc_monitor_callbacks)) {
18530       __unload_module();
18531       return AST_MODULE_LOAD_FAILURE;
18532    }
18533 #endif   /* defined(HAVE_PRI_CCSS) */
18534    if (sig_pri_load(
18535 #if defined(HAVE_PRI_CCSS)
18536       dahdi_pri_cc_type
18537 #else
18538       NULL
18539 #endif   /* defined(HAVE_PRI_CCSS) */
18540       )) {
18541       __unload_module();
18542       return AST_MODULE_LOAD_FAILURE;
18543    }
18544 #endif
18545 #if defined(HAVE_SS7)
18546    memset(linksets, 0, sizeof(linksets));
18547    for (y = 0; y < NUM_SPANS; y++) {
18548       sig_ss7_init_linkset(&linksets[y].ss7);
18549    }
18550    ss7_set_error(dahdi_ss7_error);
18551    ss7_set_message(dahdi_ss7_message);
18552 #endif   /* defined(HAVE_SS7) */
18553    res = setup_dahdi(0);
18554    /* Make sure we can register our DAHDI channel type */
18555    if (res)
18556       return AST_MODULE_LOAD_DECLINE;
18557    if (ast_channel_register(&dahdi_tech)) {
18558       ast_log(LOG_ERROR, "Unable to register channel class 'DAHDI'\n");
18559       __unload_module();
18560       return AST_MODULE_LOAD_FAILURE;
18561    }
18562 #ifdef HAVE_PRI
18563    ast_cli_register_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
18564 #endif
18565 #if defined(HAVE_SS7)
18566    ast_cli_register_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
18567 #endif   /* defined(HAVE_SS7) */
18568 #ifdef HAVE_OPENR2
18569    ast_cli_register_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
18570    ast_register_application_xml(dahdi_accept_r2_call_app, dahdi_accept_r2_call_exec);
18571 #endif
18572 
18573    ast_cli_register_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
18574    /* register all the data providers */
18575    ast_data_register_multiple(dahdi_data_providers, ARRAY_LEN(dahdi_data_providers));
18576    memset(round_robin, 0, sizeof(round_robin));
18577    ast_manager_register_xml("DAHDITransfer", 0, action_transfer);
18578    ast_manager_register_xml("DAHDIHangup", 0, action_transferhangup);
18579    ast_manager_register_xml("DAHDIDialOffhook", 0, action_dahdidialoffhook);
18580    ast_manager_register_xml("DAHDIDNDon", 0, action_dahdidndon);
18581    ast_manager_register_xml("DAHDIDNDoff", 0, action_dahdidndoff);
18582    ast_manager_register_xml("DAHDIShowChannels", 0, action_dahdishowchannels);
18583    ast_manager_register_xml("DAHDIRestart", 0, action_dahdirestart);
18584 
18585    ast_cond_init(&ss_thread_complete, NULL);
18586 
18587    return res;
18588 }
18589 
18590 static int dahdi_sendtext(struct ast_channel *c, const char *text)
18591 {
18592 #define  END_SILENCE_LEN 400
18593 #define  HEADER_MS 50
18594 #define  TRAILER_MS 5
18595 #define  HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
18596 #define  ASCII_BYTES_PER_CHAR 80
18597 
18598    unsigned char *buf,*mybuf;
18599    struct dahdi_pvt *p = c->tech_pvt;
18600    struct pollfd fds[1];
18601    int size,res,fd,len,x;
18602    int bytes=0;
18603    /* Initial carrier (imaginary) */
18604    float cr = 1.0;
18605    float ci = 0.0;
18606    float scont = 0.0;
18607    int idx;
18608 
18609    idx = dahdi_get_index(c, p, 0);
18610    if (idx < 0) {
18611       ast_log(LOG_WARNING, "Huh?  I don't exist?\n");
18612       return -1;
18613    }
18614    if (!text[0]) return(0); /* if nothing to send, don't */
18615    if ((!p->tdd) && (!p->mate)) return(0);  /* if not in TDD mode, just return */
18616    if (p->mate)
18617       buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
18618    else
18619       buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
18620    if (!buf)
18621       return -1;
18622    mybuf = buf;
18623    if (p->mate) {
18624       int codec = AST_LAW(p);
18625       for (x = 0; x < HEADER_MS; x++) {   /* 50 ms of Mark */
18626          PUT_CLID_MARKMS;
18627       }
18628       /* Put actual message */
18629       for (x = 0; text[x]; x++) {
18630          PUT_CLID(text[x]);
18631       }
18632       for (x = 0; x < TRAILER_MS; x++) {  /* 5 ms of Mark */
18633          PUT_CLID_MARKMS;
18634       }
18635       len = bytes;
18636       buf = mybuf;
18637    } else {
18638       len = tdd_generate(p->tdd, buf, text);
18639       if (len < 1) {
18640          ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
18641          ast_free(mybuf);
18642          return -1;
18643       }
18644    }
18645    memset(buf + len, 0x7f, END_SILENCE_LEN);
18646    len += END_SILENCE_LEN;
18647    fd = p->subs[idx].dfd;
18648    while (len) {
18649       if (ast_check_hangup(c)) {
18650          ast_free(mybuf);
18651          return -1;
18652       }
18653       size = len;
18654       if (size > READ_SIZE)
18655          size = READ_SIZE;
18656       fds[0].fd = fd;
18657       fds[0].events = POLLOUT | POLLPRI;
18658       fds[0].revents = 0;
18659       res = poll(fds, 1, -1);
18660       if (!res) {
18661          ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
18662          continue;
18663       }
18664       /* if got exception */
18665       if (fds[0].revents & POLLPRI) {
18666          ast_free(mybuf);
18667          return -1;
18668       }
18669       if (!(fds[0].revents & POLLOUT)) {
18670          ast_debug(1, "write fd not ready on channel %d\n", p->channel);
18671          continue;
18672       }
18673       res = write(fd, buf, size);
18674       if (res != size) {
18675          if (res == -1) {
18676             ast_free(mybuf);
18677             return -1;
18678          }
18679          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
18680          break;
18681       }
18682       len -= size;
18683       buf += size;
18684    }
18685    ast_free(mybuf);
18686    return(0);
18687 }
18688 
18689 
18690 static int reload(void)
18691 {
18692    int res = 0;
18693 
18694    res = setup_dahdi(1);
18695    if (res) {
18696       ast_log(LOG_WARNING, "Reload of chan_dahdi.so is unsuccessful!\n");
18697       return -1;
18698    }
18699    return 0;
18700 }
18701 
18702 /* This is a workaround so that menuselect displays a proper description
18703  * AST_MODULE_INFO(, , "DAHDI Telephony"
18704  */
18705 
18706 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, tdesc,
18707    .load = load_module,
18708    .unload = unload_module,
18709    .reload = reload,
18710    .load_pri = AST_MODPRI_CHANNEL_DRIVER,
18711       .nonoptreq = "res_smdi",
18712    );

Generated on 30 Aug 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1