Mon May 14 2012 03:42:29

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: 355952 $")
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 *cidrings, 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       *cidrings = 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       *cidrings = 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)
02604 /*!
02605  * \internal
02606  * \brief Open the PRI 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_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) */
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    if (x) {
03099       ast_log(LOG_NOTICE, "PRI got event: %s (%d) on D-channel of span %d\n", event2str(x), x, pri->span);
03100    }
03101    /* Keep track of alarm state */
03102    switch (x) {
03103    case DAHDI_EVENT_ALARM:
03104       pri_event_alarm(pri, index, 0);
03105       break;
03106    case DAHDI_EVENT_NOALARM:
03107       pri_event_noalarm(pri, index, 0);
03108       break;
03109    default:
03110       break;
03111    }
03112 }
03113 #endif   /* defined(HAVE_PRI) */
03114 
03115 #if defined(HAVE_PRI)
03116 static int my_pri_play_tone(void *pvt, enum sig_pri_tone tone)
03117 {
03118    struct dahdi_pvt *p = pvt;
03119 
03120    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_pri_tone_to_dahditone(tone));
03121 }
03122 #endif   /* defined(HAVE_PRI) */
03123 
03124 #if defined(HAVE_PRI) || defined(HAVE_SS7)
03125 /*!
03126  * \internal
03127  * \brief Set the caller id information.
03128  * \since 1.8
03129  *
03130  * \param pvt DAHDI private structure
03131  * \param caller Caller-id information to set.
03132  *
03133  * \return Nothing
03134  */
03135 static void my_set_callerid(void *pvt, const struct ast_party_caller *caller)
03136 {
03137    struct dahdi_pvt *p = pvt;
03138 
03139    ast_copy_string(p->cid_num,
03140       S_COR(caller->id.number.valid, caller->id.number.str, ""),
03141       sizeof(p->cid_num));
03142    ast_copy_string(p->cid_name,
03143       S_COR(caller->id.name.valid, caller->id.name.str, ""),
03144       sizeof(p->cid_name));
03145    ast_copy_string(p->cid_subaddr,
03146       S_COR(caller->id.subaddress.valid, caller->id.subaddress.str, ""),
03147       sizeof(p->cid_subaddr));
03148    p->cid_ton = caller->id.number.plan;
03149    p->callingpres = ast_party_id_presentation(&caller->id);
03150    if (caller->id.tag) {
03151       ast_copy_string(p->cid_tag, caller->id.tag, sizeof(p->cid_tag));
03152    }
03153    ast_copy_string(p->cid_ani,
03154       S_COR(caller->ani.number.valid, caller->ani.number.str, ""),
03155       sizeof(p->cid_ani));
03156    p->cid_ani2 = caller->ani2;
03157 }
03158 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03159 
03160 #if defined(HAVE_PRI) || defined(HAVE_SS7)
03161 /*!
03162  * \internal
03163  * \brief Set the Dialed Number Identifier.
03164  * \since 1.8
03165  *
03166  * \param pvt DAHDI private structure
03167  * \param dnid Dialed Number Identifier string.
03168  *
03169  * \return Nothing
03170  */
03171 static void my_set_dnid(void *pvt, const char *dnid)
03172 {
03173    struct dahdi_pvt *p = pvt;
03174 
03175    ast_copy_string(p->dnid, dnid, sizeof(p->dnid));
03176 }
03177 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03178 
03179 #if defined(HAVE_PRI)
03180 /*!
03181  * \internal
03182  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
03183  * \since 1.8
03184  *
03185  * \param pvt DAHDI private structure
03186  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
03187  *
03188  * \return Nothing
03189  */
03190 static void my_set_rdnis(void *pvt, const char *rdnis)
03191 {
03192    struct dahdi_pvt *p = pvt;
03193 
03194    ast_copy_string(p->rdnis, rdnis, sizeof(p->rdnis));
03195 }
03196 #endif   /* defined(HAVE_PRI) */
03197 
03198 #if defined(HAVE_PRI)
03199 /*!
03200  * \internal
03201  * \brief Make a dialstring for native ISDN CC to recall properly.
03202  * \since 1.8
03203  *
03204  * \param priv Channel private control structure.
03205  * \param buf Where to put the modified dialstring.
03206  * \param buf_size Size of modified dialstring buffer.
03207  *
03208  * \details
03209  * original dialstring:
03210  * DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03211  *
03212  * The modified dialstring will have prefixed the channel-group section
03213  * with the ISDN channel restriction.
03214  *
03215  * buf:
03216  * DAHDI/i<span>-(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03217  *
03218  * The routine will check to see if the ISDN channel restriction is already
03219  * in the original dialstring.
03220  *
03221  * \return Nothing
03222  */
03223 static void my_pri_make_cc_dialstring(void *priv, char *buf, size_t buf_size)
03224 {
03225    char *dial;
03226    struct dahdi_pvt *pvt;
03227    AST_DECLARE_APP_ARGS(args,
03228       AST_APP_ARG(tech);   /* channel technology token */
03229       AST_APP_ARG(group);  /* channel/group token */
03230       //AST_APP_ARG(ext);  /* extension token */
03231       //AST_APP_ARG(opts); /* options token */
03232       //AST_APP_ARG(other);   /* Any remining unused arguments */
03233    );
03234 
03235    pvt = priv;
03236    dial = ast_strdupa(pvt->dialstring);
03237    AST_NONSTANDARD_APP_ARGS(args, dial, '/');
03238    if (!args.tech) {
03239       ast_copy_string(buf, pvt->dialstring, buf_size);
03240       return;
03241    }
03242    if (!args.group) {
03243       /* Append the ISDN span channel restriction to the dialstring. */
03244       snprintf(buf, buf_size, "%s/i%d-", args.tech, pvt->pri->span);
03245       return;
03246    }
03247    if (isdigit(args.group[0]) || args.group[0] == 'i' || strchr(args.group, '!')) {
03248       /* The ISDN span channel restriction is not needed or already
03249        * in the dialstring. */
03250       ast_copy_string(buf, pvt->dialstring, buf_size);
03251       return;
03252    }
03253    /* Insert the ISDN span channel restriction into the dialstring. */
03254    snprintf(buf, buf_size, "%s/i%d-%s", args.tech, pvt->pri->span, args.group);
03255 }
03256 #endif   /* defined(HAVE_PRI) */
03257 
03258 #if defined(HAVE_PRI)
03259 /*!
03260  * \internal
03261  * \brief Reevaluate the PRI span device state.
03262  * \since 1.8
03263  *
03264  * \param pri Asterisk D channel control structure.
03265  *
03266  * \return Nothing
03267  *
03268  * \note Assumes the pri->lock is already obtained.
03269  */
03270 static void dahdi_pri_update_span_devstate(struct sig_pri_span *pri)
03271 {
03272    unsigned idx;
03273    unsigned num_b_chans;   /* Number of B channels provisioned on the span. */
03274    unsigned in_use;     /* Number of B channels in use on the span. */
03275    unsigned in_alarm;      /* TRUE if the span is in alarm condition. */
03276    enum ast_device_state new_state;
03277 
03278    /* Count the number of B channels and the number of B channels in use. */
03279    num_b_chans = 0;
03280    in_use = 0;
03281    in_alarm = 1;
03282    for (idx = pri->numchans; idx--;) {
03283       if (pri->pvts[idx] && !pri->pvts[idx]->no_b_channel) {
03284          /* This is a B channel interface. */
03285          ++num_b_chans;
03286          if (!sig_pri_is_chan_available(pri->pvts[idx])) {
03287             ++in_use;
03288          }
03289          if (!pri->pvts[idx]->inalarm) {
03290             /* There is a channel that is not in alarm. */
03291             in_alarm = 0;
03292          }
03293       }
03294    }
03295 
03296    /* Update the span congestion device state and report any change. */
03297    if (in_alarm) {
03298       new_state = AST_DEVICE_UNAVAILABLE;
03299    } else {
03300       new_state = num_b_chans == in_use ? AST_DEVICE_BUSY : AST_DEVICE_NOT_INUSE;
03301    }
03302    if (pri->congestion_devstate != new_state) {
03303       pri->congestion_devstate = new_state;
03304       ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/congestion", pri->span);
03305    }
03306 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
03307    /* Update the span threshold device state and report any change. */
03308    if (in_alarm) {
03309       new_state = AST_DEVICE_UNAVAILABLE;
03310    } else if (!in_use) {
03311       new_state = AST_DEVICE_NOT_INUSE;
03312    } else if (!pri->user_busy_threshold) {
03313       new_state = in_use < num_b_chans ? AST_DEVICE_INUSE : AST_DEVICE_BUSY;
03314    } else {
03315       new_state = in_use < pri->user_busy_threshold ? AST_DEVICE_INUSE
03316          : AST_DEVICE_BUSY;
03317    }
03318    if (pri->threshold_devstate != new_state) {
03319       pri->threshold_devstate = new_state;
03320       ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/threshold", pri->span);
03321    }
03322 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
03323 }
03324 #endif   /* defined(HAVE_PRI) */
03325 
03326 #if defined(HAVE_PRI)
03327 /*!
03328  * \internal
03329  * \brief Reference this module.
03330  * \since 1.8
03331  *
03332  * \return Nothing
03333  */
03334 static void my_module_ref(void)
03335 {
03336    ast_module_ref(ast_module_info->self);
03337 }
03338 #endif   /* defined(HAVE_PRI) */
03339 
03340 #if defined(HAVE_PRI)
03341 /*!
03342  * \internal
03343  * \brief Unreference this module.
03344  * \since 1.8
03345  *
03346  * \return Nothing
03347  */
03348 static void my_module_unref(void)
03349 {
03350    ast_module_unref(ast_module_info->self);
03351 }
03352 #endif   /* defined(HAVE_PRI) */
03353 
03354 #if defined(HAVE_PRI)
03355 #if defined(HAVE_PRI_CALL_WAITING)
03356 static void my_pri_init_config(void *priv, struct sig_pri_span *pri);
03357 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03358 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri);
03359 
03360 static struct sig_pri_callback dahdi_pri_callbacks =
03361 {
03362    .handle_dchan_exception = my_handle_dchan_exception,
03363    .play_tone = my_pri_play_tone,
03364    .set_echocanceller = my_set_echocanceller,
03365    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03366    .lock_private = my_lock_private,
03367    .unlock_private = my_unlock_private,
03368    .new_ast_channel = my_new_pri_ast_channel,
03369    .fixup_chans = my_pri_fixup_chans,
03370    .set_alarm = my_set_alarm,
03371    .set_dialing = my_set_dialing,
03372    .set_outgoing = my_set_outgoing,
03373    .set_digital = my_set_digital,
03374    .set_callerid = my_set_callerid,
03375    .set_dnid = my_set_dnid,
03376    .set_rdnis = my_set_rdnis,
03377    .new_nobch_intf = dahdi_new_pri_nobch_channel,
03378 #if defined(HAVE_PRI_CALL_WAITING)
03379    .init_config = my_pri_init_config,
03380 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03381    .get_orig_dialstring = my_get_orig_dialstring,
03382    .make_cc_dialstring = my_pri_make_cc_dialstring,
03383    .update_span_devstate = dahdi_pri_update_span_devstate,
03384    .module_ref = my_module_ref,
03385    .module_unref = my_module_unref,
03386    .dial_digits = my_pri_dial_digits,
03387    .open_media = my_pri_open_media,
03388    .ami_channel_event = my_ami_channel_event,
03389 };
03390 #endif   /* defined(HAVE_PRI) */
03391 
03392 #if defined(HAVE_SS7)
03393 /*!
03394  * \internal
03395  * \brief Handle the SS7 link exception.
03396  * \since 1.8
03397  *
03398  * \param linkset Controlling linkset for the channel.
03399  * \param which Link index of the signaling channel.
03400  *
03401  * \return Nothing
03402  */
03403 static void my_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
03404 {
03405    int event;
03406 
03407    if (ioctl(linkset->fds[which], DAHDI_GETEVENT, &event)) {
03408       ast_log(LOG_ERROR, "SS7: Error in exception retrieval on span %d/%d!\n",
03409          linkset->span, which);
03410       return;
03411    }
03412    switch (event) {
03413    case DAHDI_EVENT_NONE:
03414       break;
03415    case DAHDI_EVENT_ALARM:
03416       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03417          event2str(event), event, linkset->span, which);
03418       sig_ss7_link_alarm(linkset, which);
03419       break;
03420    case DAHDI_EVENT_NOALARM:
03421       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03422          event2str(event), event, linkset->span, which);
03423       sig_ss7_link_noalarm(linkset, which);
03424       break;
03425    default:
03426       ast_log(LOG_NOTICE, "SS7 got event: %s(%d) on span %d/%d\n",
03427          event2str(event), event, linkset->span, which);
03428       break;
03429    }
03430 }
03431 #endif   /* defined(HAVE_SS7) */
03432 
03433 #if defined(HAVE_SS7)
03434 static void my_ss7_set_loopback(void *pvt, int enable)
03435 {
03436    struct dahdi_pvt *p = pvt;
03437 
03438    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
03439       ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel,
03440          strerror(errno));
03441    }
03442 }
03443 #endif   /* defined(HAVE_SS7) */
03444 
03445 #if defined(HAVE_SS7)
03446 /*!
03447  * \internal
03448  * \brief Create a new asterisk channel structure for SS7.
03449  * \since 1.8
03450  *
03451  * \param pvt Private channel structure.
03452  * \param state Initial state of new channel.
03453  * \param law Combanding law to use.
03454  * \param exten Dialplan extension for incoming call.
03455  * \param requestor Channel requesting this new channel.
03456  *
03457  * \retval ast_channel on success.
03458  * \retval NULL on error.
03459  */
03460 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)
03461 {
03462    struct dahdi_pvt *p = pvt;
03463    int audio;
03464    int newlaw;
03465 
03466    /* Set to audio mode at this point */
03467    audio = 1;
03468    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1)
03469       ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
03470          p->channel, audio, strerror(errno));
03471 
03472    if (law != SIG_SS7_DEFLAW) {
03473       dahdi_setlaw(p->subs[SUB_REAL].dfd,
03474          (law == SIG_SS7_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
03475    }
03476 
03477    ast_copy_string(p->exten, exten, sizeof(p->exten));
03478 
03479    newlaw = -1;
03480    switch (law) {
03481    case SIG_SS7_DEFLAW:
03482       newlaw = 0;
03483       break;
03484    case SIG_SS7_ALAW:
03485       newlaw = DAHDI_LAW_ALAW;
03486       break;
03487    case SIG_SS7_ULAW:
03488       newlaw = DAHDI_LAW_MULAW;
03489       break;
03490    }
03491    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
03492 }
03493 #endif   /* defined(HAVE_SS7) */
03494 
03495 #if defined(HAVE_SS7)
03496 static int sig_ss7_tone_to_dahditone(enum sig_ss7_tone tone)
03497 {
03498    switch (tone) {
03499    case SIG_SS7_TONE_RINGTONE:
03500       return DAHDI_TONE_RINGTONE;
03501    case SIG_SS7_TONE_STUTTER:
03502       return DAHDI_TONE_STUTTER;
03503    case SIG_SS7_TONE_CONGESTION:
03504       return DAHDI_TONE_CONGESTION;
03505    case SIG_SS7_TONE_DIALTONE:
03506       return DAHDI_TONE_DIALTONE;
03507    case SIG_SS7_TONE_DIALRECALL:
03508       return DAHDI_TONE_DIALRECALL;
03509    case SIG_SS7_TONE_INFO:
03510       return DAHDI_TONE_INFO;
03511    case SIG_SS7_TONE_BUSY:
03512       return DAHDI_TONE_BUSY;
03513    default:
03514       return -1;
03515    }
03516 }
03517 #endif   /* defined(HAVE_SS7) */
03518 
03519 #if defined(HAVE_SS7)
03520 static int my_ss7_play_tone(void *pvt, enum sig_ss7_tone tone)
03521 {
03522    struct dahdi_pvt *p = pvt;
03523 
03524    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_ss7_tone_to_dahditone(tone));
03525 }
03526 #endif   /* defined(HAVE_SS7) */
03527 
03528 #if defined(HAVE_SS7)
03529 static struct sig_ss7_callback dahdi_ss7_callbacks =
03530 {
03531    .lock_private = my_lock_private,
03532    .unlock_private = my_unlock_private,
03533 
03534    .set_echocanceller = my_set_echocanceller,
03535    .set_loopback = my_ss7_set_loopback,
03536 
03537    .new_ast_channel = my_new_ss7_ast_channel,
03538    .play_tone = my_ss7_play_tone,
03539 
03540    .handle_link_exception = my_handle_link_exception,
03541    .set_alarm = my_set_alarm,
03542    .set_dialing = my_set_dialing,
03543    .set_outgoing = my_set_outgoing,
03544    .set_digital = my_set_digital,
03545    .set_inservice = my_set_inservice,
03546    .set_locallyblocked = my_set_locallyblocked,
03547    .set_remotelyblocked = my_set_remotelyblocked,
03548    .set_callerid = my_set_callerid,
03549    .set_dnid = my_set_dnid,
03550 };
03551 #endif   /* defined(HAVE_SS7) */
03552 
03553 /*!
03554  * \brief Send MWI state change
03555  *
03556  * \arg mailbox_full This is the mailbox associated with the FXO line that the
03557  *      MWI state has changed on.
03558  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
03559  *      whether there are messages waiting or not.
03560  *
03561  *  \return nothing
03562  *
03563  * This function does two things:
03564  *
03565  * 1) It generates an internal Asterisk event notifying any other module that
03566  *    cares about MWI that the state of a mailbox has changed.
03567  *
03568  * 2) It runs the script specified by the mwimonitornotify option to allow
03569  *    some custom handling of the state change.
03570  */
03571 static void notify_message(char *mailbox_full, int thereornot)
03572 {
03573    char s[sizeof(mwimonitornotify) + 80];
03574    struct ast_event *event;
03575    char *mailbox, *context;
03576 
03577    /* Strip off @default */
03578    context = mailbox = ast_strdupa(mailbox_full);
03579    strsep(&context, "@");
03580    if (ast_strlen_zero(context))
03581       context = "default";
03582 
03583    if (!(event = ast_event_new(AST_EVENT_MWI,
03584          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
03585          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
03586          AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03587          AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03588          AST_EVENT_IE_END))) {
03589       return;
03590    }
03591 
03592    ast_event_queue_and_cache(event);
03593 
03594    if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
03595       snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
03596       ast_safe_system(s);
03597    }
03598 }
03599 
03600 static void my_handle_notify_message(struct ast_channel *chan, void *pvt, int cid_flags, int neon_mwievent)
03601 {
03602    struct dahdi_pvt *p = pvt;
03603 
03604    if (neon_mwievent > -1 && !p->mwimonitor_neon)
03605       return;
03606 
03607    if (neon_mwievent == ANALOG_EVENT_NEONMWI_ACTIVE || cid_flags & CID_MSGWAITING) {
03608       ast_log(LOG_NOTICE, "MWI: Channel %d message waiting, mailbox %s\n", p->channel, p->mailbox);
03609       notify_message(p->mailbox, 1);
03610    } else if (neon_mwievent == ANALOG_EVENT_NEONMWI_INACTIVE || cid_flags & CID_NOMSGWAITING) {
03611       ast_log(LOG_NOTICE, "MWI: Channel %d no message waiting, mailbox %s\n", p->channel, p->mailbox);
03612       notify_message(p->mailbox, 0);
03613    }
03614    /* If the CID had Message waiting payload, assume that this for MWI only and hangup the call */
03615    /* If generated using Ring Pulse Alert, then ring has been answered as a call and needs to be hungup */
03616    if (neon_mwievent == -1 && p->mwimonitor_rpas) {
03617       ast_hangup(chan);
03618       return;
03619    }
03620 }
03621 
03622 static int my_have_progressdetect(void *pvt)
03623 {
03624    struct dahdi_pvt *p = pvt;
03625 
03626    if ((p->callprogress & CALLPROGRESS_PROGRESS)
03627       && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
03628       return 1;
03629    } else {
03630       /* Don't have progress detection. */
03631       return 0;
03632    }
03633 }
03634 
03635 static struct analog_callback dahdi_analog_callbacks =
03636 {
03637    .play_tone = my_play_tone,
03638    .get_event = my_get_event,
03639    .wait_event = my_wait_event,
03640    .is_off_hook = my_is_off_hook,
03641    .set_echocanceller = my_set_echocanceller,
03642    .ring = my_ring,
03643    .flash = my_flash,
03644    .off_hook = my_off_hook,
03645    .dial_digits = my_dial_digits,
03646    .train_echocanceller = my_train_echocanceller,
03647    .on_hook = my_on_hook,
03648    .is_dialing = my_is_dialing,
03649    .allocate_sub = my_allocate_sub,
03650    .unallocate_sub = my_unallocate_sub,
03651    .swap_subs = my_swap_subchannels,
03652    .has_voicemail = my_has_voicemail,
03653    .check_for_conference = my_check_for_conference,
03654    .conf_add = my_conf_add,
03655    .conf_del = my_conf_del,
03656    .complete_conference_update = my_complete_conference_update,
03657    .start = my_start,
03658    .all_subchannels_hungup = my_all_subchannels_hungup,
03659    .lock_private = my_lock_private,
03660    .unlock_private = my_unlock_private,
03661    .deadlock_avoidance_private = my_deadlock_avoidance_private,
03662    .handle_dtmf = my_handle_dtmf,
03663    .wink = my_wink,
03664    .new_ast_channel = my_new_analog_ast_channel,
03665    .dsp_set_digitmode = my_dsp_set_digitmode,
03666    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03667    .send_callerid = my_send_callerid,
03668    .callwait = my_callwait,
03669    .stop_callwait = my_stop_callwait,
03670    .get_callerid = my_get_callerid,
03671    .start_cid_detect = my_start_cid_detect,
03672    .stop_cid_detect = my_stop_cid_detect,
03673    .handle_notify_message = my_handle_notify_message,
03674    .increase_ss_count = my_increase_ss_count,
03675    .decrease_ss_count = my_decrease_ss_count,
03676    .distinctive_ring = my_distinctive_ring,
03677    .set_linear_mode = my_set_linear_mode,
03678    .set_inthreeway = my_set_inthreeway,
03679    .get_and_handle_alarms = my_get_and_handle_alarms,
03680    .get_sigpvt_bridged_channel = my_get_sigpvt_bridged_channel,
03681    .get_sub_fd = my_get_sub_fd,
03682    .set_cadence = my_set_cadence,
03683    .set_alarm = my_set_alarm,
03684    .set_dialing = my_set_dialing,
03685    .set_outgoing = my_set_outgoing,
03686    .set_ringtimeout = my_set_ringtimeout,
03687    .set_waitingfordt = my_set_waitingfordt,
03688    .check_waitingfordt = my_check_waitingfordt,
03689    .set_confirmanswer = my_set_confirmanswer,
03690    .check_confirmanswer = my_check_confirmanswer,
03691    .set_callwaiting = my_set_callwaiting,
03692    .cancel_cidspill = my_cancel_cidspill,
03693    .confmute = my_confmute,
03694    .set_pulsedial = my_set_pulsedial,
03695    .set_new_owner = my_set_new_owner,
03696    .get_orig_dialstring = my_get_orig_dialstring,
03697    .set_needringing = my_set_needringing,
03698    .set_polarity = my_set_polarity,
03699    .start_polarityswitch = my_start_polarityswitch,
03700    .answer_polarityswitch = my_answer_polarityswitch,
03701    .hangup_polarityswitch = my_hangup_polarityswitch,
03702    .have_progressdetect = my_have_progressdetect,
03703 };
03704 
03705 /*! Round robin search locations. */
03706 static struct dahdi_pvt *round_robin[32];
03707 
03708 #define dahdi_get_index(ast, p, nullok)   _dahdi_get_index(ast, p, nullok, __PRETTY_FUNCTION__, __LINE__)
03709 static int _dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok, const char *fname, unsigned long line)
03710 {
03711    int res;
03712    if (p->subs[SUB_REAL].owner == ast)
03713       res = 0;
03714    else if (p->subs[SUB_CALLWAIT].owner == ast)
03715       res = 1;
03716    else if (p->subs[SUB_THREEWAY].owner == ast)
03717       res = 2;
03718    else {
03719       res = -1;
03720       if (!nullok)
03721          ast_log(LOG_WARNING,
03722             "Unable to get index for '%s' on channel %d (%s(), line %lu)\n",
03723             ast ? ast->name : "", p->channel, fname, line);
03724    }
03725    return res;
03726 }
03727 
03728 /*!
03729  * \internal
03730  * \brief Obtain the specified subchannel owner lock if the owner exists.
03731  *
03732  * \param pvt Channel private struct.
03733  * \param sub_idx Subchannel owner to lock.
03734  *
03735  * \note Assumes the pvt->lock is already obtained.
03736  *
03737  * \note
03738  * Because deadlock avoidance may have been necessary, you need to confirm
03739  * the state of things before continuing.
03740  *
03741  * \return Nothing
03742  */
03743 static void dahdi_lock_sub_owner(struct dahdi_pvt *pvt, int sub_idx)
03744 {
03745    for (;;) {
03746       if (!pvt->subs[sub_idx].owner) {
03747          /* No subchannel owner pointer */
03748          break;
03749       }
03750       if (!ast_channel_trylock(pvt->subs[sub_idx].owner)) {
03751          /* Got subchannel owner lock */
03752          break;
03753       }
03754       /* We must unlock the private to avoid the possibility of a deadlock */
03755       DEADLOCK_AVOIDANCE(&pvt->lock);
03756    }
03757 }
03758 
03759 static void wakeup_sub(struct dahdi_pvt *p, int a)
03760 {
03761    dahdi_lock_sub_owner(p, a);
03762    if (p->subs[a].owner) {
03763       ast_queue_frame(p->subs[a].owner, &ast_null_frame);
03764       ast_channel_unlock(p->subs[a].owner);
03765    }
03766 }
03767 
03768 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f)
03769 {
03770    for (;;) {
03771       if (p->owner) {
03772          if (ast_channel_trylock(p->owner)) {
03773             DEADLOCK_AVOIDANCE(&p->lock);
03774          } else {
03775             ast_queue_frame(p->owner, f);
03776             ast_channel_unlock(p->owner);
03777             break;
03778          }
03779       } else
03780          break;
03781    }
03782 }
03783 
03784 static void handle_clear_alarms(struct dahdi_pvt *p)
03785 {
03786    if (report_alarms & REPORT_CHANNEL_ALARMS) {
03787       ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
03788       manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
03789    }
03790    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
03791       ast_log(LOG_NOTICE, "Alarm cleared on span %d\n", p->span);
03792       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarmClear", "Span: %d\r\n", p->span);
03793    }
03794 }
03795 
03796 #ifdef HAVE_OPENR2
03797 
03798 static int dahdi_r2_answer(struct dahdi_pvt *p)
03799 {
03800    int res = 0;
03801    /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
03802    * and does not has support for openr2_chan_answer_call_with_mode
03803    *  */
03804 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
03805    const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
03806    int wants_double_answer = ast_true(double_answer) ? 1 : 0;
03807    if (!double_answer) {
03808       /* this still can result in double answer if the channel context
03809       * was configured that way */
03810       res = openr2_chan_answer_call(p->r2chan);
03811    } else if (wants_double_answer) {
03812       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
03813    } else {
03814       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
03815    }
03816 #else
03817    res = openr2_chan_answer_call(p->r2chan);
03818 #endif
03819    return res;
03820 }
03821 
03822 
03823 
03824 /* should be called with the ast_channel locked */
03825 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
03826 {
03827    openr2_calling_party_category_t cat;
03828    const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
03829    struct dahdi_pvt *p = c->tech_pvt;
03830    if (ast_strlen_zero(catstr)) {
03831       ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
03832             c->name, openr2_proto_get_category_string(p->mfcr2_category));
03833       return p->mfcr2_category;
03834    }
03835    if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
03836       ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
03837             catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
03838       return p->mfcr2_category;
03839    }
03840    ast_debug(1, "Using category %s\n", catstr);
03841    return cat;
03842 }
03843 
03844 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
03845 {
03846    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03847    ast_mutex_lock(&p->lock);
03848    if (p->mfcr2call) {
03849       ast_mutex_unlock(&p->lock);
03850       /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
03851          interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
03852          can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
03853          the other end will see our seize as a forced release and drop the call, we will see an invalid
03854          pattern that will be seen and treated as protocol error. */
03855       ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
03856       return;
03857    }
03858    p->mfcr2call = 1;
03859    /* better safe than sorry ... */
03860    p->cid_name[0] = '\0';
03861    p->cid_num[0] = '\0';
03862    p->cid_subaddr[0] = '\0';
03863    p->rdnis[0] = '\0';
03864    p->exten[0] = '\0';
03865    p->mfcr2_ani_index = '\0';
03866    p->mfcr2_dnis_index = '\0';
03867    p->mfcr2_dnis_matched = 0;
03868    p->mfcr2_answer_pending = 0;
03869    p->mfcr2_call_accepted = 0;
03870    ast_mutex_unlock(&p->lock);
03871    ast_verbose("New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
03872 }
03873 
03874 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
03875 {
03876    int res;
03877    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03878    ast_mutex_lock(&p->lock);
03879    p->inalarm = alarm ? 1 : 0;
03880    if (p->inalarm) {
03881       res = get_alarms(p);
03882       handle_alarms(p, res);
03883    } else {
03884       handle_clear_alarms(p);
03885    }
03886    ast_mutex_unlock(&p->lock);
03887 }
03888 
03889 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
03890 {
03891    ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
03892 }
03893 
03894 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
03895 {
03896    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03897    ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
03898    if (p->owner) {
03899       p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
03900       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03901    }
03902    ast_mutex_lock(&p->lock);
03903    p->mfcr2call = 0;
03904    ast_mutex_unlock(&p->lock);
03905 }
03906 
03907 static void dahdi_r2_disconnect_call(struct dahdi_pvt *p, openr2_call_disconnect_cause_t cause)
03908 {
03909    if (openr2_chan_disconnect_call(p->r2chan, cause)) {
03910       ast_log(LOG_NOTICE, "Bad! failed to disconnect call on channel %d with reason %s, hope for the best!\n",
03911          p->channel, openr2_proto_get_disconnect_string(cause));
03912       /* force the chan to idle and release the call flag now since we will not see a clean on_call_end */
03913       openr2_chan_set_idle(p->r2chan);
03914       ast_mutex_lock(&p->lock);
03915       p->mfcr2call = 0;
03916       ast_mutex_unlock(&p->lock);
03917    }
03918 }
03919 
03920 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
03921 {
03922    struct dahdi_pvt *p;
03923    struct ast_channel *c;
03924    ast_verbose("MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
03925          openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
03926          openr2_proto_get_category_string(category));
03927    p = openr2_chan_get_client_data(r2chan);
03928    /* if collect calls are not allowed and this is a collect call, reject it! */
03929    if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
03930       ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
03931       dahdi_r2_disconnect_call(p, OR2_CAUSE_COLLECT_CALL_REJECTED);
03932       return;
03933    }
03934    ast_mutex_lock(&p->lock);
03935    p->mfcr2_recvd_category = category;
03936    /* if we're not supposed to use CID, clear whatever we have */
03937    if (!p->use_callerid) {
03938       ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
03939       p->cid_num[0] = 0;
03940       p->cid_name[0] = 0;
03941    }
03942    /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
03943    if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
03944       ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
03945       p->exten[0] = 's';
03946       p->exten[1] = 0;
03947    }
03948    ast_mutex_unlock(&p->lock);
03949    if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
03950       ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
03951             p->channel, p->exten, p->context);
03952       dahdi_r2_disconnect_call(p, OR2_CAUSE_UNALLOCATED_NUMBER);
03953       return;
03954    }
03955    if (!p->mfcr2_accept_on_offer) {
03956       /* The user wants us to start the PBX thread right away without accepting the call first */
03957       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
03958       if (c) {
03959          /* Done here, don't disable reading now since we still need to generate MF tones to accept
03960             the call or reject it and detect the tone off condition of the other end, all of this
03961             will be done in the PBX thread now */
03962          return;
03963       }
03964       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
03965       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
03966    } else if (p->mfcr2_charge_calls) {
03967       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
03968       openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
03969    } else {
03970       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
03971       openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
03972    }
03973 }
03974 
03975 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
03976 {
03977    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03978    ast_verbose("MFC/R2 call end on channel %d\n", p->channel);
03979    ast_mutex_lock(&p->lock);
03980    p->mfcr2call = 0;
03981    ast_mutex_unlock(&p->lock);
03982 }
03983 
03984 static void dahdi_enable_ec(struct dahdi_pvt *p);
03985 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
03986 {
03987    struct dahdi_pvt *p = NULL;
03988    struct ast_channel *c = NULL;
03989    p = openr2_chan_get_client_data(r2chan);
03990    dahdi_enable_ec(p);
03991    p->mfcr2_call_accepted = 1;
03992    /* if it's an incoming call ... */
03993    if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
03994       ast_verbose("MFC/R2 call has been accepted on backward channel %d\n", openr2_chan_get_number(r2chan));
03995       /* If accept on offer is not set, it means at this point the PBX thread is already
03996          launched (was launched in the 'on call offered' handler) and therefore this callback
03997          is being executed already in the PBX thread rather than the monitor thread, don't launch
03998          any other thread, just disable the openr2 reading and answer the call if needed */
03999       if (!p->mfcr2_accept_on_offer) {
04000          openr2_chan_disable_read(r2chan);
04001          if (p->mfcr2_answer_pending) {
04002             ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
04003             dahdi_r2_answer(p);
04004          }
04005          return;
04006       }
04007       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
04008       if (c) {
04009          /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
04010             library to forget about it */
04011          openr2_chan_disable_read(r2chan);
04012          return;
04013       }
04014       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
04015       /* failed to create the channel, bail out and report it as an out of order line */
04016       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
04017       return;
04018    }
04019    /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
04020    ast_verbose("MFC/R2 call has been accepted on forward channel %d\n", p->channel);
04021    p->subs[SUB_REAL].needringing = 1;
04022    p->dialing = 0;
04023    /* chan_dahdi will take care of reading from now on in the PBX thread, tell the library to forget about it */
04024    openr2_chan_disable_read(r2chan);
04025 }
04026 
04027 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
04028 {
04029    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04030    ast_verbose("MFC/R2 call has been answered on channel %d\n", openr2_chan_get_number(r2chan));
04031    p->subs[SUB_REAL].needanswer = 1;
04032 }
04033 
04034 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
04035 {
04036    /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
04037 }
04038 
04039 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
04040 {
04041    switch (cause) {
04042    case OR2_CAUSE_BUSY_NUMBER:
04043       return AST_CAUSE_BUSY;
04044    case OR2_CAUSE_NETWORK_CONGESTION:
04045       return AST_CAUSE_CONGESTION;
04046    case OR2_CAUSE_OUT_OF_ORDER:
04047       return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
04048    case OR2_CAUSE_UNALLOCATED_NUMBER:
04049       return AST_CAUSE_UNREGISTERED;
04050    case OR2_CAUSE_NO_ANSWER:
04051       return AST_CAUSE_NO_ANSWER;
04052    case OR2_CAUSE_NORMAL_CLEARING:
04053       return AST_CAUSE_NORMAL_CLEARING;
04054    case OR2_CAUSE_UNSPECIFIED:
04055    default:
04056       return AST_CAUSE_NOTDEFINED;
04057    }
04058 }
04059 
04060 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
04061 {
04062    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04063    ast_verbose("MFC/R2 call disconnected on channel %d\n", openr2_chan_get_number(r2chan));
04064    ast_mutex_lock(&p->lock);
04065    if (!p->owner) {
04066       ast_mutex_unlock(&p->lock);
04067       /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
04068       dahdi_r2_disconnect_call(p, OR2_CAUSE_NORMAL_CLEARING);
04069       return;
04070    }
04071    /* when we have an owner we don't call dahdi_r2_disconnect_call here, that will
04072       be done in dahdi_hangup */
04073    if (p->owner->_state == AST_STATE_UP) {
04074       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04075       ast_mutex_unlock(&p->lock);
04076    } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
04077       /* being the forward side we must report what happened to the call to whoever requested it */
04078       switch (cause) {
04079       case OR2_CAUSE_BUSY_NUMBER:
04080          p->subs[SUB_REAL].needbusy = 1;
04081          break;
04082       case OR2_CAUSE_NETWORK_CONGESTION:
04083       case OR2_CAUSE_OUT_OF_ORDER:
04084       case OR2_CAUSE_UNALLOCATED_NUMBER:
04085       case OR2_CAUSE_NO_ANSWER:
04086       case OR2_CAUSE_UNSPECIFIED:
04087       case OR2_CAUSE_NORMAL_CLEARING:
04088          p->subs[SUB_REAL].needcongestion = 1;
04089          break;
04090       default:
04091          p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04092       }
04093       ast_mutex_unlock(&p->lock);
04094    } else {
04095       ast_mutex_unlock(&p->lock);
04096       /* being the backward side and not UP yet, we only need to request hangup */
04097       /* TODO: what about doing this same thing when were AST_STATE_UP? */
04098       ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
04099    }
04100 }
04101 
04102 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
04103 {
04104    switch (level) {
04105    case OR2_LOG_NOTICE:
04106       ast_verbose("%s", logmessage);
04107       break;
04108    case OR2_LOG_WARNING:
04109       ast_log(LOG_WARNING, "%s", logmessage);
04110       break;
04111    case OR2_LOG_ERROR:
04112       ast_log(LOG_ERROR, "%s", logmessage);
04113       break;
04114    case OR2_LOG_STACK_TRACE:
04115    case OR2_LOG_MF_TRACE:
04116    case OR2_LOG_CAS_TRACE:
04117    case OR2_LOG_DEBUG:
04118    case OR2_LOG_EX_DEBUG:
04119       ast_log(LOG_DEBUG, "%s", logmessage);
04120       break;
04121    default:
04122       ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
04123       ast_log(LOG_DEBUG, "%s", logmessage);
04124       break;
04125    }
04126 }
04127 
04128 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
04129 {
04130    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04131    ast_mutex_lock(&p->lock);
04132    p->remotelyblocked = 1;
04133    ast_mutex_unlock(&p->lock);
04134    ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
04135 }
04136 
04137 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
04138 {
04139    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04140    ast_mutex_lock(&p->lock);
04141    p->remotelyblocked = 0;
04142    ast_mutex_unlock(&p->lock);
04143    ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
04144 }
04145 
04146 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
04147    __attribute__((format (printf, 3, 0)));
04148 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
04149 {
04150 #define CONTEXT_TAG "Context - "
04151    char logmsg[256];
04152    char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
04153    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
04154    snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
04155    dahdi_r2_write_log(level, completemsg);
04156 #undef CONTEXT_TAG
04157 }
04158 
04159 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
04160    __attribute__((format (printf, 3, 0)));
04161 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
04162 {
04163 #define CHAN_TAG "Chan "
04164    char logmsg[256];
04165    char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
04166    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
04167    snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
04168    dahdi_r2_write_log(level, completemsg);
04169 }
04170 
04171 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
04172 {
04173    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04174    /* if 'immediate' is set, let's stop requesting DNIS */
04175    if (p->immediate) {
04176       return 0;
04177    }
04178    p->exten[p->mfcr2_dnis_index] = digit;
04179    p->rdnis[p->mfcr2_dnis_index] = digit;
04180    p->mfcr2_dnis_index++;
04181    p->exten[p->mfcr2_dnis_index] = 0;
04182    p->rdnis[p->mfcr2_dnis_index] = 0;
04183    /* if the DNIS is a match and cannot match more, stop requesting DNIS */
04184    if ((p->mfcr2_dnis_matched ||
04185        (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
04186        !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
04187       return 0;
04188    }
04189    /* otherwise keep going */
04190    return 1;
04191 }
04192 
04193 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
04194 {
04195    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04196    p->cid_num[p->mfcr2_ani_index] = digit;
04197    p->cid_name[p->mfcr2_ani_index] = digit;
04198    p->mfcr2_ani_index++;
04199    p->cid_num[p->mfcr2_ani_index] = 0;
04200    p->cid_name[p->mfcr2_ani_index] = 0;
04201 }
04202 
04203 static void dahdi_r2_on_billing_pulse_received(openr2_chan_t *r2chan)
04204 {
04205    ast_verbose("MFC/R2 billing pulse received on channel %d\n", openr2_chan_get_number(r2chan));
04206 }
04207 
04208 static openr2_event_interface_t dahdi_r2_event_iface = {
04209    .on_call_init = dahdi_r2_on_call_init,
04210    .on_call_offered = dahdi_r2_on_call_offered,
04211    .on_call_accepted = dahdi_r2_on_call_accepted,
04212    .on_call_answered = dahdi_r2_on_call_answered,
04213    .on_call_disconnect = dahdi_r2_on_call_disconnect,
04214    .on_call_end = dahdi_r2_on_call_end,
04215    .on_call_read = dahdi_r2_on_call_read,
04216    .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
04217    .on_os_error = dahdi_r2_on_os_error,
04218    .on_protocol_error = dahdi_r2_on_protocol_error,
04219    .on_line_blocked = dahdi_r2_on_line_blocked,
04220    .on_line_idle = dahdi_r2_on_line_idle,
04221    /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
04222    .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
04223    .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
04224    .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
04225    /* so far we do nothing with billing pulses */
04226    .on_billing_pulse_received = dahdi_r2_on_billing_pulse_received
04227 };
04228 
04229 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
04230 {
04231    return AST_ALAW(sample);
04232 }
04233 
04234 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
04235 {
04236    return AST_LIN2A(sample);
04237 }
04238 
04239 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
04240    dahdi_r2_alaw_to_linear,
04241    dahdi_r2_linear_to_alaw
04242 };
04243 
04244 #endif /* HAVE_OPENR2 */
04245 
04246 static void swap_subs(struct dahdi_pvt *p, int a, int b)
04247 {
04248    int tchan;
04249    int tinthreeway;
04250    struct ast_channel *towner;
04251 
04252    ast_debug(1, "Swapping %d and %d\n", a, b);
04253 
04254    tchan = p->subs[a].chan;
04255    towner = p->subs[a].owner;
04256    tinthreeway = p->subs[a].inthreeway;
04257 
04258    p->subs[a].chan = p->subs[b].chan;
04259    p->subs[a].owner = p->subs[b].owner;
04260    p->subs[a].inthreeway = p->subs[b].inthreeway;
04261 
04262    p->subs[b].chan = tchan;
04263    p->subs[b].owner = towner;
04264    p->subs[b].inthreeway = tinthreeway;
04265 
04266    if (p->subs[a].owner)
04267       ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
04268    if (p->subs[b].owner)
04269       ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
04270    wakeup_sub(p, a);
04271    wakeup_sub(p, b);
04272 }
04273 
04274 static int dahdi_open(char *fn)
04275 {
04276    int fd;
04277    int isnum;
04278    int chan = 0;
04279    int bs;
04280    int x;
04281    isnum = 1;
04282    for (x = 0; x < strlen(fn); x++) {
04283       if (!isdigit(fn[x])) {
04284          isnum = 0;
04285          break;
04286       }
04287    }
04288    if (isnum) {
04289       chan = atoi(fn);
04290       if (chan < 1) {
04291          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
04292          return -1;
04293       }
04294       fn = "/dev/dahdi/channel";
04295    }
04296    fd = open(fn, O_RDWR | O_NONBLOCK);
04297    if (fd < 0) {
04298       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
04299       return -1;
04300    }
04301    if (chan) {
04302       if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
04303          x = errno;
04304          close(fd);
04305          errno = x;
04306          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
04307          return -1;
04308       }
04309    }
04310    bs = READ_SIZE;
04311    if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
04312       ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
04313       x = errno;
04314       close(fd);
04315       errno = x;
04316       return -1;
04317    }
04318    return fd;
04319 }
04320 
04321 static void dahdi_close(int fd)
04322 {
04323    if (fd > 0)
04324       close(fd);
04325 }
04326 
04327 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
04328 {
04329    dahdi_close(chan_pvt->subs[sub_num].dfd);
04330    chan_pvt->subs[sub_num].dfd = -1;
04331 }
04332 
04333 #if defined(HAVE_PRI)
04334 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
04335 {
04336    dahdi_close(pri->pri.fds[fd_num]);
04337    pri->pri.fds[fd_num] = -1;
04338 }
04339 #endif   /* defined(HAVE_PRI) */
04340 
04341 #if defined(HAVE_SS7)
04342 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
04343 {
04344    dahdi_close(ss7->ss7.fds[fd_num]);
04345    ss7->ss7.fds[fd_num] = -1;
04346 }
04347 #endif   /* defined(HAVE_SS7) */
04348 
04349 static int dahdi_setlinear(int dfd, int linear)
04350 {
04351    return ioctl(dfd, DAHDI_SETLINEAR, &linear);
04352 }
04353 
04354 
04355 static int alloc_sub(struct dahdi_pvt *p, int x)
04356 {
04357    struct dahdi_bufferinfo bi;
04358    int res;
04359    if (p->subs[x].dfd >= 0) {
04360       ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
04361       return -1;
04362    }
04363 
04364    p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
04365    if (p->subs[x].dfd <= -1) {
04366       ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
04367       return -1;
04368    }
04369 
04370    res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
04371    if (!res) {
04372       bi.txbufpolicy = p->buf_policy;
04373       bi.rxbufpolicy = p->buf_policy;
04374       bi.numbufs = p->buf_no;
04375       res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
04376       if (res < 0) {
04377          ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
04378       }
04379    } else
04380       ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
04381 
04382    if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
04383       ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
04384       dahdi_close_sub(p, x);
04385       p->subs[x].dfd = -1;
04386       return -1;
04387    }
04388    ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
04389    return 0;
04390 }
04391 
04392 static int unalloc_sub(struct dahdi_pvt *p, int x)
04393 {
04394    if (!x) {
04395       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
04396       return -1;
04397    }
04398    ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
04399    dahdi_close_sub(p, x);
04400    p->subs[x].linear = 0;
04401    p->subs[x].chan = 0;
04402    p->subs[x].owner = NULL;
04403    p->subs[x].inthreeway = 0;
04404    p->polarity = POLARITY_IDLE;
04405    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
04406    return 0;
04407 }
04408 
04409 static int digit_to_dtmfindex(char digit)
04410 {
04411    if (isdigit(digit))
04412       return DAHDI_TONE_DTMF_BASE + (digit - '0');
04413    else if (digit >= 'A' && digit <= 'D')
04414       return DAHDI_TONE_DTMF_A + (digit - 'A');
04415    else if (digit >= 'a' && digit <= 'd')
04416       return DAHDI_TONE_DTMF_A + (digit - 'a');
04417    else if (digit == '*')
04418       return DAHDI_TONE_DTMF_s;
04419    else if (digit == '#')
04420       return DAHDI_TONE_DTMF_p;
04421    else
04422       return -1;
04423 }
04424 
04425 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
04426 {
04427    struct dahdi_pvt *pvt;
04428    int idx;
04429    int dtmf = -1;
04430    int res;
04431 
04432    pvt = chan->tech_pvt;
04433 
04434    ast_mutex_lock(&pvt->lock);
04435 
04436    idx = dahdi_get_index(chan, pvt, 0);
04437 
04438    if ((idx != SUB_REAL) || !pvt->owner)
04439       goto out;
04440 
04441 #ifdef HAVE_PRI
04442    switch (pvt->sig) {
04443    case SIG_PRI_LIB_HANDLE_CASES:
04444       res = sig_pri_digit_begin(pvt->sig_pvt, chan, digit);
04445       if (!res)
04446          goto out;
04447       break;
04448    default:
04449       break;
04450    }
04451 #endif
04452    if ((dtmf = digit_to_dtmfindex(digit)) == -1)
04453       goto out;
04454 
04455    if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
04456       struct dahdi_dialoperation zo = {
04457          .op = DAHDI_DIAL_OP_APPEND,
04458       };
04459 
04460       zo.dialstr[0] = 'T';
04461       zo.dialstr[1] = digit;
04462       zo.dialstr[2] = '\0';
04463       if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
04464          ast_log(LOG_WARNING, "Couldn't dial digit %c: %s\n", digit, strerror(errno));
04465       else
04466          pvt->dialing = 1;
04467    } else {
04468       ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
04469       pvt->dialing = 1;
04470       pvt->begindigit = digit;
04471    }
04472 
04473 out:
04474    ast_mutex_unlock(&pvt->lock);
04475 
04476    return 0;
04477 }
04478 
04479 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
04480 {
04481    struct dahdi_pvt *pvt;
04482    int res = 0;
04483    int idx;
04484    int x;
04485 
04486    pvt = chan->tech_pvt;
04487 
04488    ast_mutex_lock(&pvt->lock);
04489 
04490    idx = dahdi_get_index(chan, pvt, 0);
04491 
04492    if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
04493       goto out;
04494 
04495 #ifdef HAVE_PRI
04496    /* This means that the digit was already sent via PRI signalling */
04497    if (dahdi_sig_pri_lib_handles(pvt->sig) && !pvt->begindigit) {
04498       goto out;
04499    }
04500 #endif
04501 
04502    if (pvt->begindigit) {
04503       x = -1;
04504       ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
04505       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
04506       pvt->dialing = 0;
04507       pvt->begindigit = 0;
04508    }
04509 
04510 out:
04511    ast_mutex_unlock(&pvt->lock);
04512 
04513    return res;
04514 }
04515 
04516 static const char * const events[] = {
04517    "No event",
04518    "On hook",
04519    "Ring/Answered",
04520    "Wink/Flash",
04521    "Alarm",
04522    "No more alarm",
04523    "HDLC Abort",
04524    "HDLC Overrun",
04525    "HDLC Bad FCS",
04526    "Dial Complete",
04527    "Ringer On",
04528    "Ringer Off",
04529    "Hook Transition Complete",
04530    "Bits Changed",
04531    "Pulse Start",
04532    "Timer Expired",
04533    "Timer Ping",
04534    "Polarity Reversal",
04535    "Ring Begin",
04536 };
04537 
04538 static struct {
04539    int alarm;
04540    char *name;
04541 } alarms[] = {
04542    { DAHDI_ALARM_RED, "Red Alarm" },
04543    { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
04544    { DAHDI_ALARM_BLUE, "Blue Alarm" },
04545    { DAHDI_ALARM_RECOVER, "Recovering" },
04546    { DAHDI_ALARM_LOOPBACK, "Loopback" },
04547    { DAHDI_ALARM_NOTOPEN, "Not Open" },
04548    { DAHDI_ALARM_NONE, "None" },
04549 };
04550 
04551 static char *alarm2str(int alm)
04552 {
04553    int x;
04554    for (x = 0; x < ARRAY_LEN(alarms); x++) {
04555       if (alarms[x].alarm & alm)
04556          return alarms[x].name;
04557    }
04558    return alm ? "Unknown Alarm" : "No Alarm";
04559 }
04560 
04561 static const char *event2str(int event)
04562 {
04563    static char buf[256];
04564    if ((event < (ARRAY_LEN(events))) && (event > -1))
04565       return events[event];
04566    sprintf(buf, "Event %d", event); /* safe */
04567    return buf;
04568 }
04569 
04570 static char *dahdi_sig2str(int sig)
04571 {
04572    static char buf[256];
04573    switch (sig) {
04574    case SIG_EM:
04575       return "E & M Immediate";
04576    case SIG_EMWINK:
04577       return "E & M Wink";
04578    case SIG_EM_E1:
04579       return "E & M E1";
04580    case SIG_FEATD:
04581       return "Feature Group D (DTMF)";
04582    case SIG_FEATDMF:
04583       return "Feature Group D (MF)";
04584    case SIG_FEATDMF_TA:
04585       return "Feature Groud D (MF) Tandem Access";
04586    case SIG_FEATB:
04587       return "Feature Group B (MF)";
04588    case SIG_E911:
04589       return "E911 (MF)";
04590    case SIG_FGC_CAMA:
04591       return "FGC/CAMA (Dialpulse)";
04592    case SIG_FGC_CAMAMF:
04593       return "FGC/CAMA (MF)";
04594    case SIG_FXSLS:
04595       return "FXS Loopstart";
04596    case SIG_FXSGS:
04597       return "FXS Groundstart";
04598    case SIG_FXSKS:
04599       return "FXS Kewlstart";
04600    case SIG_FXOLS:
04601       return "FXO Loopstart";
04602    case SIG_FXOGS:
04603       return "FXO Groundstart";
04604    case SIG_FXOKS:
04605       return "FXO Kewlstart";
04606    case SIG_PRI:
04607       return "ISDN PRI";
04608    case SIG_BRI:
04609       return "ISDN BRI Point to Point";
04610    case SIG_BRI_PTMP:
04611       return "ISDN BRI Point to MultiPoint";
04612    case SIG_SS7:
04613       return "SS7";
04614    case SIG_MFCR2:
04615       return "MFC/R2";
04616    case SIG_SF:
04617       return "SF (Tone) Immediate";
04618    case SIG_SFWINK:
04619       return "SF (Tone) Wink";
04620    case SIG_SF_FEATD:
04621       return "SF (Tone) with Feature Group D (DTMF)";
04622    case SIG_SF_FEATDMF:
04623       return "SF (Tone) with Feature Group D (MF)";
04624    case SIG_SF_FEATB:
04625       return "SF (Tone) with Feature Group B (MF)";
04626    case 0:
04627       return "Pseudo";
04628    default:
04629       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
04630       return buf;
04631    }
04632 }
04633 
04634 #define sig2str dahdi_sig2str
04635 
04636 static int analog_lib_handles(int signalling, int radio, int oprmode)
04637 {
04638    switch (signalling) {
04639    case SIG_FXOLS:
04640    case SIG_FXOGS:
04641    case SIG_FXOKS:
04642    case SIG_FXSLS:
04643    case SIG_FXSGS:
04644    case SIG_FXSKS:
04645    case SIG_EMWINK:
04646    case SIG_EM:
04647    case SIG_EM_E1:
04648    case SIG_FEATD:
04649    case SIG_FEATDMF:
04650    case SIG_E911:
04651    case SIG_FGC_CAMA:
04652    case SIG_FGC_CAMAMF:
04653    case SIG_FEATB:
04654    case SIG_SFWINK:
04655    case SIG_SF:
04656    case SIG_SF_FEATD:
04657    case SIG_SF_FEATDMF:
04658    case SIG_FEATDMF_TA:
04659    case SIG_SF_FEATB:
04660       break;
04661    default:
04662       /* The rest of the function should cover the remainder of signalling types */
04663       return 0;
04664    }
04665 
04666    if (radio)
04667       return 0;
04668 
04669    if (oprmode)
04670       return 0;
04671 
04672    return 1;
04673 }
04674 
04675 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
04676 {
04677    /* If the conference already exists, and we're already in it
04678       don't bother doing anything */
04679    struct dahdi_confinfo zi;
04680 
04681    memset(&zi, 0, sizeof(zi));
04682    zi.chan = 0;
04683 
04684    if (slavechannel > 0) {
04685       /* If we have only one slave, do a digital mon */
04686       zi.confmode = DAHDI_CONF_DIGITALMON;
04687       zi.confno = slavechannel;
04688    } else {
04689       if (!idx) {
04690          /* Real-side and pseudo-side both participate in conference */
04691          zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
04692             DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
04693       } else
04694          zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
04695       zi.confno = p->confno;
04696    }
04697    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
04698       return 0;
04699    if (c->dfd < 0)
04700       return 0;
04701    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04702       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
04703       return -1;
04704    }
04705    if (slavechannel < 1) {
04706       p->confno = zi.confno;
04707    }
04708    c->curconf = zi;
04709    ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04710    return 0;
04711 }
04712 
04713 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
04714 {
04715    /* If they're listening to our channel, they're ours */
04716    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
04717       return 1;
04718    /* If they're a talker on our (allocated) conference, they're ours */
04719    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
04720       return 1;
04721    return 0;
04722 }
04723 
04724 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
04725 {
04726    struct dahdi_confinfo zi;
04727    if (/* Can't delete if there's no dfd */
04728       (c->dfd < 0) ||
04729       /* Don't delete from the conference if it's not our conference */
04730       !isourconf(p, c)
04731       /* Don't delete if we don't think it's conferenced at all (implied) */
04732       ) return 0;
04733    memset(&zi, 0, sizeof(zi));
04734    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04735       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
04736       return -1;
04737    }
04738    ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04739    memcpy(&c->curconf, &zi, sizeof(c->curconf));
04740    return 0;
04741 }
04742 
04743 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
04744 {
04745    int x;
04746    int useslavenative;
04747    struct dahdi_pvt *slave = NULL;
04748    /* Start out optimistic */
04749    useslavenative = 1;
04750    /* Update conference state in a stateless fashion */
04751    for (x = 0; x < 3; x++) {
04752       /* Any three-way calling makes slave native mode *definitely* out
04753          of the question */
04754       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
04755          useslavenative = 0;
04756    }
04757    /* If we don't have any 3-way calls, check to see if we have
04758       precisely one slave */
04759    if (useslavenative) {
04760       for (x = 0; x < MAX_SLAVES; x++) {
04761          if (p->slaves[x]) {
04762             if (slave) {
04763                /* Whoops already have a slave!  No
04764                   slave native and stop right away */
04765                slave = NULL;
04766                useslavenative = 0;
04767                break;
04768             } else {
04769                /* We have one slave so far */
04770                slave = p->slaves[x];
04771             }
04772          }
04773       }
04774    }
04775    /* If no slave, slave native definitely out */
04776    if (!slave)
04777       useslavenative = 0;
04778    else if (slave->law != p->law) {
04779       useslavenative = 0;
04780       slave = NULL;
04781    }
04782    if (out)
04783       *out = slave;
04784    return useslavenative;
04785 }
04786 
04787 static int reset_conf(struct dahdi_pvt *p)
04788 {
04789    p->confno = -1;
04790    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
04791    if (p->subs[SUB_REAL].dfd > -1) {
04792       struct dahdi_confinfo zi;
04793 
04794       memset(&zi, 0, sizeof(zi));
04795       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
04796          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
04797    }
04798    return 0;
04799 }
04800 
04801 static int update_conf(struct dahdi_pvt *p)
04802 {
04803    int needconf = 0;
04804    int x;
04805    int useslavenative;
04806    struct dahdi_pvt *slave = NULL;
04807 
04808    useslavenative = isslavenative(p, &slave);
04809    /* Start with the obvious, general stuff */
04810    for (x = 0; x < 3; x++) {
04811       /* Look for three way calls */
04812       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
04813          conf_add(p, &p->subs[x], x, 0);
04814          needconf++;
04815       } else {
04816          conf_del(p, &p->subs[x], x);
04817       }
04818    }
04819    /* If we have a slave, add him to our conference now. or DAX
04820       if this is slave native */
04821    for (x = 0; x < MAX_SLAVES; x++) {
04822       if (p->slaves[x]) {
04823          if (useslavenative)
04824             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
04825          else {
04826             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
04827             needconf++;
04828          }
04829       }
04830    }
04831    /* If we're supposed to be in there, do so now */
04832    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
04833       if (useslavenative)
04834          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
04835       else {
04836          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
04837          needconf++;
04838       }
04839    }
04840    /* If we have a master, add ourselves to his conference */
04841    if (p->master) {
04842       if (isslavenative(p->master, NULL)) {
04843          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
04844       } else {
04845          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
04846       }
04847    }
04848    if (!needconf) {
04849       /* Nobody is left (or should be left) in our conference.
04850          Kill it. */
04851       p->confno = -1;
04852    }
04853    ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
04854    return 0;
04855 }
04856 
04857 static void dahdi_enable_ec(struct dahdi_pvt *p)
04858 {
04859    int res;
04860    if (!p)
04861       return;
04862    if (p->echocanon) {
04863       ast_debug(1, "Echo cancellation already on\n");
04864       return;
04865    }
04866    if (p->digital) {
04867       ast_debug(1, "Echo cancellation isn't required on digital connection\n");
04868       return;
04869    }
04870    if (p->echocancel.head.tap_length) {
04871 #if defined(HAVE_PRI) || defined(HAVE_SS7)
04872       switch (p->sig) {
04873 #if defined(HAVE_PRI)
04874       case SIG_PRI_LIB_HANDLE_CASES:
04875          if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
04876             /*
04877              * PRI nobch pseudo channel.  Does not need ec anyway.
04878              * Does not handle ioctl(DAHDI_AUDIOMODE)
04879              */
04880             return;
04881          }
04882          /* Fall through */
04883 #endif   /* defined(HAVE_PRI) */
04884 #if defined(HAVE_SS7)
04885       case SIG_SS7:
04886 #endif   /* defined(HAVE_SS7) */
04887          {
04888             int x = 1;
04889 
04890             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
04891             if (res)
04892                ast_log(LOG_WARNING,
04893                   "Unable to enable audio mode on channel %d (%s)\n",
04894                   p->channel, strerror(errno));
04895          }
04896          break;
04897       default:
04898          break;
04899       }
04900 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
04901       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
04902       if (res) {
04903          ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
04904       } else {
04905          p->echocanon = 1;
04906          ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
04907       }
04908    } else
04909       ast_debug(1, "No echo cancellation requested\n");
04910 }
04911 
04912 static void dahdi_train_ec(struct dahdi_pvt *p)
04913 {
04914    int x;
04915    int res;
04916 
04917    if (p && p->echocanon && p->echotraining) {
04918       x = p->echotraining;
04919       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
04920       if (res)
04921          ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
04922       else
04923          ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
04924    } else {
04925       ast_debug(1, "No echo training requested\n");
04926    }
04927 }
04928 
04929 static void dahdi_disable_ec(struct dahdi_pvt *p)
04930 {
04931    int res;
04932 
04933    if (p->echocanon) {
04934       struct dahdi_echocanparams ecp = { .tap_length = 0 };
04935 
04936       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
04937 
04938       if (res)
04939          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
04940       else
04941          ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
04942    }
04943 
04944    p->echocanon = 0;
04945 }
04946 
04947 /* perform a dynamic range compression transform on the given sample */
04948 static int drc_sample(int sample, float drc)
04949 {
04950    float neg;
04951    float shallow, steep;
04952    float max = SHRT_MAX;
04953    
04954    neg = (sample < 0 ? -1 : 1);
04955    steep = drc*sample;
04956    shallow = neg*(max-max/drc)+(float)sample/drc;
04957    if (abs(steep) < abs(shallow)) {
04958       sample = steep;
04959    }
04960    else {
04961       sample = shallow;
04962    }
04963 
04964    return sample;
04965 }
04966 
04967 
04968 static void fill_txgain(struct dahdi_gains *g, float gain, float drc, int law)
04969 {
04970    int j;
04971    int k;
04972 
04973    float linear_gain = pow(10.0, gain / 20.0);
04974 
04975    switch (law) {
04976    case DAHDI_LAW_ALAW:
04977       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
04978          if (gain || drc) {
04979             k = AST_ALAW(j);
04980             if (drc) {
04981                k = drc_sample(k, drc);
04982             }
04983             k = (float)k*linear_gain;
04984             if (k > 32767) k = 32767;
04985             if (k < -32767) k = -32767;
04986             g->txgain[j] = AST_LIN2A(k);
04987          } else {
04988             g->txgain[j] = j;
04989          }
04990       }
04991       break;
04992    case DAHDI_LAW_MULAW:
04993       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
04994          if (gain || drc) {
04995             k = AST_MULAW(j);
04996             if (drc) {
04997                k = drc_sample(k, drc);
04998             }
04999             k = (float)k*linear_gain;
05000             if (k > 32767) k = 32767;
05001             if (k < -32767) k = -32767;
05002             g->txgain[j] = AST_LIN2MU(k);
05003 
05004          } else {
05005             g->txgain[j] = j;
05006          }
05007       }
05008       break;
05009    }
05010 }
05011 
05012 static void fill_rxgain(struct dahdi_gains *g, float gain, float drc, int law)
05013 {
05014    int j;
05015    int k;
05016    float linear_gain = pow(10.0, gain / 20.0);
05017 
05018    switch (law) {
05019    case DAHDI_LAW_ALAW:
05020       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
05021          if (gain || drc) {
05022             k = AST_ALAW(j);
05023             if (drc) {
05024                k = drc_sample(k, drc);
05025             }
05026             k = (float)k*linear_gain;
05027             if (k > 32767) k = 32767;
05028             if (k < -32767) k = -32767;
05029             g->rxgain[j] = AST_LIN2A(k);
05030          } else {
05031             g->rxgain[j] = j;
05032          }
05033       }
05034       break;
05035    case DAHDI_LAW_MULAW:
05036       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
05037          if (gain || drc) {
05038             k = AST_MULAW(j);
05039             if (drc) {
05040                k = drc_sample(k, drc);
05041             }
05042             k = (float)k*linear_gain;
05043             if (k > 32767) k = 32767;
05044             if (k < -32767) k = -32767;
05045             g->rxgain[j] = AST_LIN2MU(k);
05046          } else {
05047             g->rxgain[j] = j;
05048          }
05049       }
05050       break;
05051    }
05052 }
05053 
05054 static int set_actual_txgain(int fd, float gain, float drc, int law)
05055 {
05056    struct dahdi_gains g;
05057    int res;
05058 
05059    memset(&g, 0, sizeof(g));
05060    res = ioctl(fd, DAHDI_GETGAINS, &g);
05061    if (res) {
05062       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
05063       return res;
05064    }
05065 
05066    fill_txgain(&g, gain, drc, law);
05067 
05068    return ioctl(fd, DAHDI_SETGAINS, &g);
05069 }
05070 
05071 static int set_actual_rxgain(int fd, float gain, float drc, int law)
05072 {
05073    struct dahdi_gains g;
05074    int res;
05075 
05076    memset(&g, 0, sizeof(g));
05077    res = ioctl(fd, DAHDI_GETGAINS, &g);
05078    if (res) {
05079       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
05080       return res;
05081    }
05082 
05083    fill_rxgain(&g, gain, drc, law);
05084 
05085    return ioctl(fd, DAHDI_SETGAINS, &g);
05086 }
05087 
05088 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law)
05089 {
05090    return set_actual_txgain(fd, txgain, txdrc, law) | set_actual_rxgain(fd, rxgain, rxdrc, law);
05091 }
05092 
05093 static int bump_gains(struct dahdi_pvt *p)
05094 {
05095    int res;
05096 
05097    /* Bump receive gain by value stored in cid_rxgain */
05098    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain + p->cid_rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05099    if (res) {
05100       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
05101       return -1;
05102    }
05103 
05104    return 0;
05105 }
05106 
05107 static int restore_gains(struct dahdi_pvt *p)
05108 {
05109    int res;
05110 
05111    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05112    if (res) {
05113       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
05114       return -1;
05115    }
05116 
05117    return 0;
05118 }
05119 
05120 static inline int dahdi_set_hook(int fd, int hs)
05121 {
05122    int x, res;
05123 
05124    x = hs;
05125    res = ioctl(fd, DAHDI_HOOK, &x);
05126 
05127    if (res < 0) {
05128       if (errno == EINPROGRESS)
05129          return 0;
05130       ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
05131       /* will expectedly fail if phone is off hook during operation, such as during a restart */
05132    }
05133 
05134    return res;
05135 }
05136 
05137 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
05138 {
05139    int x, res;
05140 
05141    x = muted;
05142 #if defined(HAVE_PRI) || defined(HAVE_SS7)
05143    switch (p->sig) {
05144 #if defined(HAVE_PRI)
05145    case SIG_PRI_LIB_HANDLE_CASES:
05146       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
05147          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
05148          break;
05149       }
05150       /* Fall through */
05151 #endif   /* defined(HAVE_PRI) */
05152 #if defined(HAVE_SS7)
05153    case SIG_SS7:
05154 #endif   /* defined(HAVE_SS7) */
05155       {
05156          int y = 1;
05157 
05158          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
05159          if (res)
05160             ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n",
05161                p->channel, strerror(errno));
05162       }
05163       break;
05164    default:
05165       break;
05166    }
05167 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
05168    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
05169    if (res < 0)
05170       ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
05171    return res;
05172 }
05173 
05174 static int save_conference(struct dahdi_pvt *p)
05175 {
05176    struct dahdi_confinfo c;
05177    int res;
05178    if (p->saveconf.confmode) {
05179       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
05180       return -1;
05181    }
05182    p->saveconf.chan = 0;
05183    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
05184    if (res) {
05185       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
05186       p->saveconf.confmode = 0;
05187       return -1;
05188    }
05189    memset(&c, 0, sizeof(c));
05190    c.confmode = DAHDI_CONF_NORMAL;
05191    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
05192    if (res) {
05193       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
05194       return -1;
05195    }
05196    ast_debug(1, "Disabled conferencing\n");
05197    return 0;
05198 }
05199 
05200 static int restore_conference(struct dahdi_pvt *p)
05201 {
05202    int res;
05203    if (p->saveconf.confmode) {
05204       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
05205       p->saveconf.confmode = 0;
05206       if (res) {
05207          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
05208          return -1;
05209       }
05210       ast_debug(1, "Restored conferencing\n");
05211    }
05212    return 0;
05213 }
05214 
05215 static int send_cwcidspill(struct dahdi_pvt *p)
05216 {
05217    p->callwaitcas = 0;
05218    p->cidcwexpire = 0;
05219    p->cid_suppress_expire = 0;
05220    if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
05221       return -1;
05222    p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
05223    /* Make sure we account for the end */
05224    p->cidlen += READ_SIZE * 4;
05225    p->cidpos = 0;
05226    send_callerid(p);
05227    ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
05228    return 0;
05229 }
05230 
05231 static int has_voicemail(struct dahdi_pvt *p)
05232 {
05233    int new_msgs;
05234    struct ast_event *event;
05235    char *mailbox, *context;
05236 
05237    mailbox = context = ast_strdupa(p->mailbox);
05238    strsep(&context, "@");
05239    if (ast_strlen_zero(context))
05240       context = "default";
05241 
05242    event = ast_event_get_cached(AST_EVENT_MWI,
05243       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
05244       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
05245       AST_EVENT_IE_END);
05246 
05247    if (event) {
05248       new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
05249       ast_event_destroy(event);
05250    } else
05251       new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
05252 
05253    return new_msgs;
05254 }
05255 
05256 
05257 
05258 static int send_callerid(struct dahdi_pvt *p)
05259 {
05260    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
05261    int res;
05262    /* Take out of linear mode if necessary */
05263    if (p->subs[SUB_REAL].linear) {
05264       p->subs[SUB_REAL].linear = 0;
05265       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
05266    }
05267    while (p->cidpos < p->cidlen) {
05268       res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
05269       ast_debug(4, "writing callerid at pos %d of %d, res = %d\n", p->cidpos, p->cidlen, res);
05270       if (res < 0) {
05271          if (errno == EAGAIN)
05272             return 0;
05273          else {
05274             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
05275             return -1;
05276          }
05277       }
05278       if (!res)
05279          return 0;
05280       p->cidpos += res;
05281    }
05282    p->cid_suppress_expire = CALLWAITING_SUPPRESS_SAMPLES;
05283    ast_free(p->cidspill);
05284    p->cidspill = NULL;
05285    if (p->callwaitcas) {
05286       /* Wait for CID/CW to expire */
05287       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
05288       p->cid_suppress_expire = p->cidcwexpire;
05289    } else
05290       restore_conference(p);
05291    return 0;
05292 }
05293 
05294 static int dahdi_callwait(struct ast_channel *ast)
05295 {
05296    struct dahdi_pvt *p = ast->tech_pvt;
05297    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
05298    if (p->cidspill) {
05299       ast_log(LOG_WARNING, "Spill already exists?!?\n");
05300       ast_free(p->cidspill);
05301    }
05302 
05303    /*
05304     * SAS: Subscriber Alert Signal, 440Hz for 300ms
05305     * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
05306     */
05307    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
05308       return -1;
05309    save_conference(p);
05310    /* Silence */
05311    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
05312    if (!p->callwaitrings && p->callwaitingcallerid) {
05313       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
05314       p->callwaitcas = 1;
05315       p->cidlen = 2400 + 680 + READ_SIZE * 4;
05316    } else {
05317       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
05318       p->callwaitcas = 0;
05319       p->cidlen = 2400 + READ_SIZE * 4;
05320    }
05321    p->cidpos = 0;
05322    send_callerid(p);
05323 
05324    return 0;
05325 }
05326 
05327 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
05328 {
05329    struct dahdi_pvt *p = ast->tech_pvt;
05330    int x, res, mysig;
05331    char dest[256]; /* must be same length as p->dialdest */
05332 
05333    ast_mutex_lock(&p->lock);
05334    ast_copy_string(dest, rdest, sizeof(dest));
05335    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
05336    if ((ast->_state == AST_STATE_BUSY)) {
05337       p->subs[SUB_REAL].needbusy = 1;
05338       ast_mutex_unlock(&p->lock);
05339       return 0;
05340    }
05341    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05342       ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
05343       ast_mutex_unlock(&p->lock);
05344       return -1;
05345    }
05346    p->waitingfordt.tv_sec = 0;
05347    p->dialednone = 0;
05348    if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
05349    {
05350       /* Special pseudo -- automatically up */
05351       ast_setstate(ast, AST_STATE_UP);
05352       ast_mutex_unlock(&p->lock);
05353       return 0;
05354    }
05355    x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
05356    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
05357    if (res)
05358       ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
05359    p->outgoing = 1;
05360 
05361    if (IS_DIGITAL(ast->transfercapability)){
05362       set_actual_gain(p->subs[SUB_REAL].dfd, 0, 0, p->rxdrc, p->txdrc, p->law);
05363    } else {
05364       set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05365    }  
05366 
05367 #ifdef HAVE_PRI
05368    if (dahdi_sig_pri_lib_handles(p->sig)) {
05369       res = sig_pri_call(p->sig_pvt, ast, rdest, timeout,
05370          (p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW);
05371       ast_mutex_unlock(&p->lock);
05372       return res;
05373    }
05374 #endif
05375 
05376 #if defined(HAVE_SS7)
05377    if (p->sig == SIG_SS7) {
05378       res = sig_ss7_call(p->sig_pvt, ast, rdest);
05379       ast_mutex_unlock(&p->lock);
05380       return res;
05381    }
05382 #endif   /* defined(HAVE_SS7) */
05383 
05384    /* If this is analog signalling we can exit here */
05385    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
05386       p->callwaitrings = 0;
05387       res = analog_call(p->sig_pvt, ast, rdest, timeout);
05388       ast_mutex_unlock(&p->lock);
05389       return res;
05390    }
05391 
05392    mysig = p->outsigmod > -1 ? p->outsigmod : p->sig;
05393    switch (mysig) {
05394    case 0:
05395       /* Special pseudo -- automatically up*/
05396       ast_setstate(ast, AST_STATE_UP);
05397       break;
05398    case SIG_MFCR2:
05399       break;
05400    default:
05401       ast_debug(1, "not yet implemented\n");
05402       ast_mutex_unlock(&p->lock);
05403       return -1;
05404    }
05405 
05406 #ifdef HAVE_OPENR2
05407    if (p->mfcr2) {
05408       openr2_calling_party_category_t chancat;
05409       int callres = 0;
05410       char *c, *l;
05411 
05412       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
05413       p->dialdest[0] = '\0';
05414 
05415       c = strchr(dest, '/');
05416       if (c) {
05417          c++;
05418       } else {
05419          c = "";
05420       }
05421       if (!p->hidecallerid) {
05422          l = ast->connected.id.number.valid ? ast->connected.id.number.str : NULL;
05423       } else {
05424          l = NULL;
05425       }
05426       if (strlen(c) < p->stripmsd) {
05427          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
05428          ast_mutex_unlock(&p->lock);
05429          return -1;
05430       }
05431       p->dialing = 1;
05432       chancat = dahdi_r2_get_channel_category(ast);
05433       callres = openr2_chan_make_call(p->r2chan, l, (c + p->stripmsd), chancat);
05434       if (-1 == callres) {
05435          ast_mutex_unlock(&p->lock);
05436          ast_log(LOG_ERROR, "unable to make new MFC/R2 call!\n");
05437          return -1;
05438       }
05439       p->mfcr2_call_accepted = 0;
05440       p->mfcr2_progress = 0;
05441       ast_setstate(ast, AST_STATE_DIALING);
05442    }
05443 #endif /* HAVE_OPENR2 */
05444    ast_mutex_unlock(&p->lock);
05445    return 0;
05446 }
05447 
05448 /*!
05449  * \internal
05450  * \brief Insert the given chan_dahdi interface structure into the interface list.
05451  * \since 1.8
05452  *
05453  * \param pvt chan_dahdi private interface structure to insert.
05454  *
05455  * \details
05456  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05457  * Any duplicates are inserted after the existing entries.
05458  *
05459  * \note The new interface must not already be in the list.
05460  *
05461  * \return Nothing
05462  */
05463 static void dahdi_iflist_insert(struct dahdi_pvt *pvt)
05464 {
05465    struct dahdi_pvt *cur;
05466 
05467    pvt->which_iflist = DAHDI_IFLIST_MAIN;
05468 
05469    /* Find place in middle of list for the new interface. */
05470    for (cur = iflist; cur; cur = cur->next) {
05471       if (pvt->channel < cur->channel) {
05472          /* New interface goes before the current interface. */
05473          pvt->prev = cur->prev;
05474          pvt->next = cur;
05475          if (cur->prev) {
05476             /* Insert into the middle of the list. */
05477             cur->prev->next = pvt;
05478          } else {
05479             /* Insert at head of list. */
05480             iflist = pvt;
05481          }
05482          cur->prev = pvt;
05483          return;
05484       }
05485    }
05486 
05487    /* New interface goes onto the end of the list */
05488    pvt->prev = ifend;
05489    pvt->next = NULL;
05490    if (ifend) {
05491       ifend->next = pvt;
05492    }
05493    ifend = pvt;
05494    if (!iflist) {
05495       /* List was empty */
05496       iflist = pvt;
05497    }
05498 }
05499 
05500 /*!
05501  * \internal
05502  * \brief Extract the given chan_dahdi interface structure from the interface list.
05503  * \since 1.8
05504  *
05505  * \param pvt chan_dahdi private interface structure to extract.
05506  *
05507  * \note
05508  * The given interface structure can be either in the interface list or a stand alone
05509  * structure that has not been put in the list if the next and prev pointers are NULL.
05510  *
05511  * \return Nothing
05512  */
05513 static void dahdi_iflist_extract(struct dahdi_pvt *pvt)
05514 {
05515    /* Extract from the forward chain. */
05516    if (pvt->prev) {
05517       pvt->prev->next = pvt->next;
05518    } else if (iflist == pvt) {
05519       /* Node is at the head of the list. */
05520       iflist = pvt->next;
05521    }
05522 
05523    /* Extract from the reverse chain. */
05524    if (pvt->next) {
05525       pvt->next->prev = pvt->prev;
05526    } else if (ifend == pvt) {
05527       /* Node is at the end of the list. */
05528       ifend = pvt->prev;
05529    }
05530 
05531    /* Node is no longer in the list. */
05532    pvt->which_iflist = DAHDI_IFLIST_NONE;
05533    pvt->prev = NULL;
05534    pvt->next = NULL;
05535 }
05536 
05537 #if defined(HAVE_PRI)
05538 /*!
05539  * \internal
05540  * \brief Insert the given chan_dahdi interface structure into the no B channel list.
05541  * \since 1.8
05542  *
05543  * \param pri sig_pri span control structure holding no B channel list.
05544  * \param pvt chan_dahdi private interface structure to insert.
05545  *
05546  * \details
05547  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05548  * Any duplicates are inserted after the existing entries.
05549  *
05550  * \note The new interface must not already be in the list.
05551  *
05552  * \return Nothing
05553  */
05554 static void dahdi_nobch_insert(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05555 {
05556    struct dahdi_pvt *cur;
05557 
05558    pvt->which_iflist = DAHDI_IFLIST_NO_B_CHAN;
05559 
05560    /* Find place in middle of list for the new interface. */
05561    for (cur = pri->no_b_chan_iflist; cur; cur = cur->next) {
05562       if (pvt->channel < cur->channel) {
05563          /* New interface goes before the current interface. */
05564          pvt->prev = cur->prev;
05565          pvt->next = cur;
05566          if (cur->prev) {
05567             /* Insert into the middle of the list. */
05568             cur->prev->next = pvt;
05569          } else {
05570             /* Insert at head of list. */
05571             pri->no_b_chan_iflist = pvt;
05572          }
05573          cur->prev = pvt;
05574          return;
05575       }
05576    }
05577 
05578    /* New interface goes onto the end of the list */
05579    pvt->prev = pri->no_b_chan_end;
05580    pvt->next = NULL;
05581    if (pri->no_b_chan_end) {
05582       ((struct dahdi_pvt *) pri->no_b_chan_end)->next = pvt;
05583    }
05584    pri->no_b_chan_end = pvt;
05585    if (!pri->no_b_chan_iflist) {
05586       /* List was empty */
05587       pri->no_b_chan_iflist = pvt;
05588    }
05589 }
05590 #endif   /* defined(HAVE_PRI) */
05591 
05592 #if defined(HAVE_PRI)
05593 /*!
05594  * \internal
05595  * \brief Extract the given chan_dahdi interface structure from the no B channel list.
05596  * \since 1.8
05597  *
05598  * \param pri sig_pri span control structure holding no B channel list.
05599  * \param pvt chan_dahdi private interface structure to extract.
05600  *
05601  * \note
05602  * The given interface structure can be either in the interface list or a stand alone
05603  * structure that has not been put in the list if the next and prev pointers are NULL.
05604  *
05605  * \return Nothing
05606  */
05607 static void dahdi_nobch_extract(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05608 {
05609    /* Extract from the forward chain. */
05610    if (pvt->prev) {
05611       pvt->prev->next = pvt->next;
05612    } else if (pri->no_b_chan_iflist == pvt) {
05613       /* Node is at the head of the list. */
05614       pri->no_b_chan_iflist = pvt->next;
05615    }
05616 
05617    /* Extract from the reverse chain. */
05618    if (pvt->next) {
05619       pvt->next->prev = pvt->prev;
05620    } else if (pri->no_b_chan_end == pvt) {
05621       /* Node is at the end of the list. */
05622       pri->no_b_chan_end = pvt->prev;
05623    }
05624 
05625    /* Node is no longer in the list. */
05626    pvt->which_iflist = DAHDI_IFLIST_NONE;
05627    pvt->prev = NULL;
05628    pvt->next = NULL;
05629 }
05630 #endif   /* defined(HAVE_PRI) */
05631 
05632 #if defined(HAVE_PRI)
05633 /*!
05634  * \internal
05635  * \brief Unlink the channel interface from the PRI private pointer array.
05636  * \since 1.8
05637  *
05638  * \param pvt chan_dahdi private interface structure to unlink.
05639  *
05640  * \return Nothing
05641  */
05642 static void dahdi_unlink_pri_pvt(struct dahdi_pvt *pvt)
05643 {
05644    unsigned idx;
05645    struct sig_pri_span *pri;
05646 
05647    pri = pvt->pri;
05648    if (!pri) {
05649       /* Not PRI signaling so cannot be in a PRI private pointer array. */
05650       return;
05651    }
05652    ast_mutex_lock(&pri->lock);
05653    for (idx = 0; idx < pri->numchans; ++idx) {
05654       if (pri->pvts[idx] == pvt->sig_pvt) {
05655          pri->pvts[idx] = NULL;
05656          ast_mutex_unlock(&pri->lock);
05657          return;
05658       }
05659    }
05660    ast_mutex_unlock(&pri->lock);
05661 }
05662 #endif   /* defined(HAVE_PRI) */
05663 
05664 #if defined(HAVE_SS7)
05665 /*!
05666  * \internal
05667  * \brief Unlink the channel interface from the SS7 private pointer array.
05668  * \since 1.8
05669  *
05670  * \param pvt chan_dahdi private interface structure to unlink.
05671  *
05672  * \return Nothing
05673  */
05674 static void dahdi_unlink_ss7_pvt(struct dahdi_pvt *pvt)
05675 {
05676    unsigned idx;
05677    struct sig_ss7_linkset *ss7;
05678 
05679    ss7 = pvt->ss7;
05680    if (!ss7) {
05681       /* Not SS7 signaling so cannot be in a SS7 private pointer array. */
05682       return;
05683    }
05684    ast_mutex_lock(&ss7->lock);
05685    for (idx = 0; idx < ss7->numchans; ++idx) {
05686       if (ss7->pvts[idx] == pvt->sig_pvt) {
05687          ss7->pvts[idx] = NULL;
05688          ast_mutex_unlock(&ss7->lock);
05689          return;
05690       }
05691    }
05692    ast_mutex_unlock(&ss7->lock);
05693 }
05694 #endif   /* defined(HAVE_SS7) */
05695 
05696 static struct dahdi_pvt *find_next_iface_in_span(struct dahdi_pvt *cur)
05697 {
05698    if (cur->next && cur->next->span == cur->span) {
05699       return cur->next;
05700    } else if (cur->prev && cur->prev->span == cur->span) {
05701       return cur->prev;
05702    }
05703 
05704    return NULL;
05705 }
05706 
05707 static void destroy_dahdi_pvt(struct dahdi_pvt *pvt)
05708 {
05709    struct dahdi_pvt *p = pvt;
05710 
05711    if (p->manages_span_alarms) {
05712       struct dahdi_pvt *next = find_next_iface_in_span(p);
05713       if (next) {
05714          next->manages_span_alarms = 1;
05715       }
05716    }
05717 
05718    /* Remove channel from the list */
05719 #if defined(HAVE_PRI)
05720    dahdi_unlink_pri_pvt(p);
05721 #endif   /* defined(HAVE_PRI) */
05722 #if defined(HAVE_SS7)
05723    dahdi_unlink_ss7_pvt(p);
05724 #endif   /* defined(HAVE_SS7) */
05725    switch (pvt->which_iflist) {
05726    case DAHDI_IFLIST_NONE:
05727       break;
05728    case DAHDI_IFLIST_MAIN:
05729       dahdi_iflist_extract(p);
05730       break;
05731 #if defined(HAVE_PRI)
05732    case DAHDI_IFLIST_NO_B_CHAN:
05733       if (p->pri) {
05734          dahdi_nobch_extract(p->pri, p);
05735       }
05736       break;
05737 #endif   /* defined(HAVE_PRI) */
05738    }
05739 
05740    if (p->sig_pvt) {
05741       if (analog_lib_handles(p->sig, 0, 0)) {
05742          analog_delete(p->sig_pvt);
05743       }
05744       switch (p->sig) {
05745 #if defined(HAVE_PRI)
05746       case SIG_PRI_LIB_HANDLE_CASES:
05747          sig_pri_chan_delete(p->sig_pvt);
05748          break;
05749 #endif   /* defined(HAVE_PRI) */
05750 #if defined(HAVE_SS7)
05751       case SIG_SS7:
05752          sig_ss7_chan_delete(p->sig_pvt);
05753          break;
05754 #endif   /* defined(HAVE_SS7) */
05755       default:
05756          break;
05757       }
05758    }
05759    ast_free(p->cidspill);
05760    if (p->use_smdi)
05761       ast_smdi_interface_unref(p->smdi_iface);
05762    if (p->mwi_event_sub)
05763       ast_event_unsubscribe(p->mwi_event_sub);
05764    if (p->vars) {
05765       ast_variables_destroy(p->vars);
05766    }
05767    if (p->cc_params) {
05768       ast_cc_config_params_destroy(p->cc_params);
05769    }
05770    ast_mutex_destroy(&p->lock);
05771    dahdi_close_sub(p, SUB_REAL);
05772    if (p->owner)
05773       p->owner->tech_pvt = NULL;
05774    ast_free(p);
05775 }
05776 
05777 static void destroy_channel(struct dahdi_pvt *cur, int now)
05778 {
05779    int i;
05780 
05781    if (!now) {
05782       /* Do not destroy the channel now if it is owned by someone. */
05783       if (cur->owner) {
05784          return;
05785       }
05786       for (i = 0; i < 3; i++) {
05787          if (cur->subs[i].owner) {
05788             return;
05789          }
05790       }
05791    }
05792    destroy_dahdi_pvt(cur);
05793 }
05794 
05795 static void destroy_all_channels(void)
05796 {
05797    int chan;
05798 #if defined(HAVE_PRI)
05799    unsigned span;
05800    struct sig_pri_span *pri;
05801 #endif   /* defined(HAVE_PRI) */
05802    struct dahdi_pvt *p;
05803 
05804    while (num_restart_pending) {
05805       usleep(1);
05806    }
05807 
05808    ast_mutex_lock(&iflock);
05809    /* Destroy all the interfaces and free their memory */
05810    while (iflist) {
05811       p = iflist;
05812 
05813       chan = p->channel;
05814 #if defined(HAVE_PRI_SERVICE_MESSAGES)
05815       {
05816          char db_chan_name[20];
05817          char db_answer[5];
05818          char state;
05819          int why = -1;
05820 
05821          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, p->span, chan);
05822          if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
05823             sscanf(db_answer, "%1c:%30d", &state, &why);
05824          }
05825          if (!why) {
05826             /* SRVST persistence is not required */
05827             ast_db_del(db_chan_name, SRVST_DBKEY);
05828          }
05829       }
05830 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
05831       /* Free associated memory */
05832       destroy_dahdi_pvt(p);
05833       ast_verb(3, "Unregistered channel %d\n", chan);
05834    }
05835    ifcount = 0;
05836    ast_mutex_unlock(&iflock);
05837 
05838 #if defined(HAVE_PRI)
05839    /* Destroy all of the no B channel interface lists */
05840    for (span = 0; span < NUM_SPANS; ++span) {
05841       if (!pris[span].dchannels[0]) {
05842          break;
05843       }
05844       pri = &pris[span].pri;
05845       ast_mutex_lock(&pri->lock);
05846       while (pri->no_b_chan_iflist) {
05847          p = pri->no_b_chan_iflist;
05848 
05849          /* Free associated memory */
05850          destroy_dahdi_pvt(p);
05851       }
05852       ast_mutex_unlock(&pri->lock);
05853    }
05854 #endif   /* defined(HAVE_PRI) */
05855 }
05856 
05857 #if defined(HAVE_PRI)
05858 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
05859 
05860 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, const char *digits)
05861 {
05862    /* Data will be our digit string */
05863    struct dahdi_pvt *p;
05864 
05865    if (ast_strlen_zero(digits)) {
05866       ast_debug(1, "No digit string sent to application!\n");
05867       return -1;
05868    }
05869 
05870    p = (struct dahdi_pvt *)chan->tech_pvt;
05871 
05872    if (!p) {
05873       ast_debug(1, "Unable to find technology private\n");
05874       return -1;
05875    }
05876 
05877    pri_send_keypad_facility_exec(p->sig_pvt, digits);
05878 
05879    return 0;
05880 }
05881 #endif   /* defined(HAVE_PRI) */
05882 
05883 #if defined(HAVE_PRI)
05884 #if defined(HAVE_PRI_PROG_W_CAUSE)
05885 static char *dahdi_send_callrerouting_facility_app = "DAHDISendCallreroutingFacility";
05886 
05887 static int dahdi_send_callrerouting_facility_exec(struct ast_channel *chan, const char *data)
05888 {
05889    /* Data will be our digit string */
05890    struct dahdi_pvt *pvt;
05891    char *parse;
05892    int res = -1;
05893    AST_DECLARE_APP_ARGS(args,
05894       AST_APP_ARG(destination);
05895       AST_APP_ARG(original);
05896       AST_APP_ARG(reason);
05897    );
05898 
05899    if (ast_strlen_zero(data)) {
05900       ast_log(LOG_DEBUG, "No data sent to application!\n");
05901       return -1;
05902    }
05903    if (chan->tech != &dahdi_tech) {
05904       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05905       return -1;
05906    }
05907    pvt = (struct dahdi_pvt *) chan->tech_pvt;
05908    if (!pvt) {
05909       ast_log(LOG_DEBUG, "Unable to find technology private\n");
05910       return -1;
05911    }
05912    switch (pvt->sig) {
05913    case SIG_PRI_LIB_HANDLE_CASES:
05914       break;
05915    default:
05916       ast_log(LOG_DEBUG, "callrerouting attempted on non-ISDN channel %s\n",
05917          chan->name);
05918       return -1;
05919    }
05920 
05921    parse = ast_strdupa(data);
05922    AST_STANDARD_APP_ARGS(args, parse);
05923 
05924    if (ast_strlen_zero(args.destination)) {
05925       ast_log(LOG_WARNING, "callrerouting facility requires at least destination number argument\n");
05926       return -1;
05927    }
05928 
05929    if (ast_strlen_zero(args.original)) {
05930       ast_log(LOG_WARNING, "Callrerouting Facility without original called number argument\n");
05931       args.original = NULL;
05932    }
05933 
05934    if (ast_strlen_zero(args.reason)) {
05935       ast_log(LOG_NOTICE, "Callrerouting Facility without diversion reason argument, defaulting to unknown\n");
05936       args.reason = NULL;
05937    }
05938 
05939    pri_send_callrerouting_facility_exec(pvt->sig_pvt, chan->_state, args.destination,
05940       args.original, args.reason);
05941 
05942    return res;
05943 }
05944 #endif   /* defined(HAVE_PRI_PROG_W_CAUSE) */
05945 #endif   /* defined(HAVE_PRI) */
05946 
05947 #if defined(HAVE_OPENR2)
05948 static const char * const dahdi_accept_r2_call_app = "DAHDIAcceptR2Call";
05949 
05950 static int dahdi_accept_r2_call_exec(struct ast_channel *chan, const char *data)
05951 {
05952    /* data is whether to accept with charge or no charge */
05953    openr2_call_mode_t accept_mode;
05954    int res, timeout, maxloops;
05955    struct ast_frame *f;
05956    struct dahdi_pvt *p;
05957    char *parse;
05958    AST_DECLARE_APP_ARGS(args,
05959          AST_APP_ARG(charge);
05960    );
05961 
05962    if (ast_strlen_zero(data)) {
05963       ast_log(LOG_DEBUG, "No data sent to application!\n");
05964       return -1;
05965    }
05966 
05967    if (chan->tech != &dahdi_tech) {
05968       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05969       return -1;
05970    }
05971 
05972    p = (struct dahdi_pvt *)chan->tech_pvt;
05973    if (!p) {
05974       ast_log(LOG_DEBUG, "Unable to find technology private!\n");
05975       return -1;
05976    }
05977 
05978    parse = ast_strdupa(data);
05979    AST_STANDARD_APP_ARGS(args, parse);
05980 
05981    if (ast_strlen_zero(args.charge)) {
05982       ast_log(LOG_WARNING, "DAHDIAcceptR2Call requires 'yes' or 'no' for the charge parameter\n");
05983       return -1;
05984    }
05985 
05986    ast_mutex_lock(&p->lock);
05987    if (!p->mfcr2 || !p->mfcr2call) {
05988       ast_mutex_unlock(&p->lock);
05989       ast_log(LOG_DEBUG, "Channel %s does not seems to be an R2 active channel!\n", chan->name);
05990       return -1;
05991    }
05992 
05993    if (p->mfcr2_call_accepted) {
05994       ast_mutex_unlock(&p->lock);
05995       ast_log(LOG_DEBUG, "MFC/R2 call already accepted on channel %s!\n", chan->name);
05996       return 0;
05997    }
05998    accept_mode = ast_true(args.charge) ? OR2_CALL_WITH_CHARGE : OR2_CALL_NO_CHARGE;
05999    if (openr2_chan_accept_call(p->r2chan, accept_mode)) {
06000       ast_mutex_unlock(&p->lock);
06001       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
06002       return -1;
06003    }
06004    ast_mutex_unlock(&p->lock);
06005 
06006    res = 0;
06007    timeout = 100;
06008    maxloops = 50; /* wait up to 5 seconds */
06009    /* we need to read() until the call is accepted */
06010    while (maxloops > 0) {
06011       maxloops--;
06012       if (ast_check_hangup(chan)) {
06013          break;
06014       }
06015       res = ast_waitfor(chan, timeout);
06016       if (res < 0) {
06017          ast_log(LOG_DEBUG, "ast_waitfor failed on channel %s, going out ...\n", chan->name);
06018          res = -1;
06019          break;
06020       }
06021       if (res == 0) {
06022          continue;
06023       }
06024       f = ast_read(chan);
06025       if (!f) {
06026          ast_log(LOG_DEBUG, "No frame read on channel %s, going out ...\n", chan->name);
06027          res = -1;
06028          break;
06029       }
06030       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
06031          ast_log(LOG_DEBUG, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
06032          ast_frfree(f);
06033          res = -1;
06034          break;
06035       }
06036       ast_frfree(f);
06037       ast_mutex_lock(&p->lock);
06038       if (p->mfcr2_call_accepted) {
06039          ast_mutex_unlock(&p->lock);
06040          ast_log(LOG_DEBUG, "Accepted MFC/R2 call!\n");
06041          break;
06042       }
06043       ast_mutex_unlock(&p->lock);
06044    }
06045    if (res == -1) {
06046       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
06047    }
06048    return res;
06049 }
06050 
06051 static openr2_call_disconnect_cause_t dahdi_ast_cause_to_r2_cause(int cause)
06052 {
06053    openr2_call_disconnect_cause_t r2cause = OR2_CAUSE_NORMAL_CLEARING;
06054    switch (cause) {
06055    case AST_CAUSE_USER_BUSY:
06056    case AST_CAUSE_CALL_REJECTED:
06057    case AST_CAUSE_INTERWORKING: /* I don't know wtf is this but is used sometimes when ekiga rejects a call */
06058       r2cause = OR2_CAUSE_BUSY_NUMBER;
06059       break;
06060 
06061    case AST_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06062    case AST_CAUSE_SWITCH_CONGESTION:
06063       r2cause = OR2_CAUSE_NETWORK_CONGESTION;
06064       break;
06065 
06066    case AST_CAUSE_UNALLOCATED:
06067       r2cause = OR2_CAUSE_UNALLOCATED_NUMBER;
06068       break;
06069 
06070    case AST_CAUSE_NETWORK_OUT_OF_ORDER:
06071    case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06072       r2cause = OR2_CAUSE_OUT_OF_ORDER;
06073       break;
06074 
06075    case AST_CAUSE_NO_ANSWER:
06076    case AST_CAUSE_NO_USER_RESPONSE:
06077       r2cause = OR2_CAUSE_NO_ANSWER;
06078       break;
06079 
06080    default:
06081       r2cause = OR2_CAUSE_NORMAL_CLEARING;
06082       break;
06083    }
06084    ast_log(LOG_DEBUG, "ast cause %d resulted in openr2 cause %d/%s\n",
06085          cause, r2cause, openr2_proto_get_disconnect_string(r2cause));
06086    return r2cause;
06087 }
06088 #endif
06089 
06090 static int revert_fax_buffers(struct dahdi_pvt *p, struct ast_channel *ast)
06091 {
06092    if (p->bufferoverrideinuse) {
06093       /* faxbuffers are in use, revert them */
06094       struct dahdi_bufferinfo bi = {
06095          .txbufpolicy = p->buf_policy,
06096          .rxbufpolicy = p->buf_policy,
06097          .bufsize = p->bufsize,
06098          .numbufs = p->buf_no
06099       };
06100       int bpres;
06101 
06102       if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
06103          ast_log(LOG_WARNING, "Channel '%s' unable to revert buffer policy: %s\n", ast->name, strerror(errno));
06104       }
06105       p->bufferoverrideinuse = 0;
06106       return bpres;
06107    }
06108 
06109    return -1;
06110 }
06111 
06112 static int dahdi_hangup(struct ast_channel *ast)
06113 {
06114    int res = 0;
06115    int idx,x;
06116    int law;
06117    /*static int restore_gains(struct dahdi_pvt *p);*/
06118    struct dahdi_pvt *p = ast->tech_pvt;
06119    struct dahdi_params par;
06120 
06121    ast_debug(1, "dahdi_hangup(%s)\n", ast->name);
06122    if (!ast->tech_pvt) {
06123       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
06124       return 0;
06125    }
06126 
06127    ast_mutex_lock(&p->lock);
06128    p->exten[0] = '\0';
06129    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06130       dahdi_confmute(p, 0);
06131       restore_gains(p);
06132       p->ignoredtmf = 0;
06133       p->waitingfordt.tv_sec = 0;
06134 
06135       res = analog_hangup(p->sig_pvt, ast);
06136       revert_fax_buffers(p, ast);
06137 
06138       goto hangup_out;
06139    } else {
06140       p->cid_num[0] = '\0';
06141       p->cid_name[0] = '\0';
06142       p->cid_subaddr[0] = '\0';
06143    }
06144 
06145 #if defined(HAVE_PRI)
06146    if (dahdi_sig_pri_lib_handles(p->sig)) {
06147       x = 1;
06148       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06149 
06150       dahdi_confmute(p, 0);
06151       p->muting = 0;
06152       restore_gains(p);
06153       if (p->dsp) {
06154          ast_dsp_free(p->dsp);
06155          p->dsp = NULL;
06156       }
06157       p->ignoredtmf = 0;
06158 
06159       /* Real channel, do some fixup */
06160       p->subs[SUB_REAL].owner = NULL;
06161       p->subs[SUB_REAL].needbusy = 0;
06162       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06163 
06164       p->owner = NULL;
06165       p->cid_tag[0] = '\0';
06166       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06167       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06168       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06169       p->outgoing = 0;
06170       p->digital = 0;
06171       p->faxhandled = 0;
06172       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06173 
06174       revert_fax_buffers(p, ast);
06175 
06176       p->law = p->law_default;
06177       law = p->law_default;
06178       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06179       if (res < 0) {
06180          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n",
06181             p->channel, strerror(errno));
06182       }
06183 
06184       sig_pri_hangup(p->sig_pvt, ast);
06185 
06186       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06187       dahdi_disable_ec(p);
06188 
06189       x = 0;
06190       ast_channel_setoption(ast, AST_OPTION_TDD, &x, sizeof(char), 0);
06191       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06192 
06193       p->rdnis[0] = '\0';
06194       update_conf(p);
06195       reset_conf(p);
06196 
06197       /* Restore data mode */
06198       x = 0;
06199       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06200 
06201       if (num_restart_pending == 0) {
06202          restart_monitor();
06203       }
06204       goto hangup_out;
06205    }
06206 #endif   /* defined(HAVE_PRI) */
06207 
06208 #if defined(HAVE_SS7)
06209    if (p->sig == SIG_SS7) {
06210       x = 1;
06211       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06212 
06213       dahdi_confmute(p, 0);
06214       p->muting = 0;
06215       restore_gains(p);
06216       if (p->dsp) {
06217          ast_dsp_free(p->dsp);
06218          p->dsp = NULL;
06219       }
06220       p->ignoredtmf = 0;
06221 
06222       /* Real channel, do some fixup */
06223       p->subs[SUB_REAL].owner = NULL;
06224       p->subs[SUB_REAL].needbusy = 0;
06225       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06226 
06227       p->owner = NULL;
06228       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06229       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06230       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06231       p->outgoing = 0;
06232       p->digital = 0;
06233       p->faxhandled = 0;
06234       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06235 
06236       revert_fax_buffers(p, ast);
06237 
06238       p->law = p->law_default;
06239       law = p->law_default;
06240       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06241       if (res < 0) {
06242          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n",
06243             p->channel, strerror(errno));
06244       }
06245 
06246       sig_ss7_hangup(p->sig_pvt, ast);
06247 
06248       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06249       dahdi_disable_ec(p);
06250 
06251       x = 0;
06252       ast_channel_setoption(ast, AST_OPTION_TDD, &x, sizeof(char), 0);
06253       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06254 
06255       update_conf(p);
06256       reset_conf(p);
06257 
06258       /* Restore data mode */
06259       x = 0;
06260       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06261 
06262       if (num_restart_pending == 0) {
06263          restart_monitor();
06264       }
06265       goto hangup_out;
06266    }
06267 #endif   /* defined(HAVE_SS7) */
06268 
06269    idx = dahdi_get_index(ast, p, 1);
06270 
06271    dahdi_confmute(p, 0);
06272    p->muting = 0;
06273    restore_gains(p);
06274    if (p->origcid_num) {
06275       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
06276       ast_free(p->origcid_num);
06277       p->origcid_num = NULL;
06278    }
06279    if (p->origcid_name) {
06280       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
06281       ast_free(p->origcid_name);
06282       p->origcid_name = NULL;
06283    }
06284    if (p->dsp)
06285       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
06286 
06287    ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
06288       p->channel, idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
06289    p->ignoredtmf = 0;
06290 
06291    if (idx > -1) {
06292       /* Real channel, do some fixup */
06293       p->subs[idx].owner = NULL;
06294       p->subs[idx].needanswer = 0;
06295       p->subs[idx].needflash = 0;
06296       p->subs[idx].needringing = 0;
06297       p->subs[idx].needbusy = 0;
06298       p->subs[idx].needcongestion = 0;
06299       p->subs[idx].linear = 0;
06300       p->polarity = POLARITY_IDLE;
06301       dahdi_setlinear(p->subs[idx].dfd, 0);
06302       if (idx == SUB_REAL) {
06303          if ((p->subs[SUB_CALLWAIT].dfd > -1) && (p->subs[SUB_THREEWAY].dfd > -1)) {
06304             ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
06305             if (p->subs[SUB_CALLWAIT].inthreeway) {
06306                /* We had flipped over to answer a callwait and now it's gone */
06307                ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
06308                /* Move to the call-wait, but un-own us until they flip back. */
06309                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06310                unalloc_sub(p, SUB_CALLWAIT);
06311                p->owner = NULL;
06312             } else {
06313                /* The three way hung up, but we still have a call wait */
06314                ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
06315                swap_subs(p, SUB_THREEWAY, SUB_REAL);
06316                unalloc_sub(p, SUB_THREEWAY);
06317                if (p->subs[SUB_REAL].inthreeway) {
06318                   /* This was part of a three way call.  Immediately make way for
06319                      another call */
06320                   ast_debug(1, "Call was complete, setting owner to former third call\n");
06321                   p->owner = p->subs[SUB_REAL].owner;
06322                } else {
06323                   /* This call hasn't been completed yet...  Set owner to NULL */
06324                   ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06325                   p->owner = NULL;
06326                }
06327                p->subs[SUB_REAL].inthreeway = 0;
06328             }
06329          } else if (p->subs[SUB_CALLWAIT].dfd > -1) {
06330             /* Move to the call-wait and switch back to them. */
06331             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06332             unalloc_sub(p, SUB_CALLWAIT);
06333             p->owner = p->subs[SUB_REAL].owner;
06334             if (p->owner->_state != AST_STATE_UP)
06335                p->subs[SUB_REAL].needanswer = 1;
06336             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
06337                ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
06338          } else if (p->subs[SUB_THREEWAY].dfd > -1) {
06339             swap_subs(p, SUB_THREEWAY, SUB_REAL);
06340             unalloc_sub(p, SUB_THREEWAY);
06341             if (p->subs[SUB_REAL].inthreeway) {
06342                /* This was part of a three way call.  Immediately make way for
06343                   another call */
06344                ast_debug(1, "Call was complete, setting owner to former third call\n");
06345                p->owner = p->subs[SUB_REAL].owner;
06346             } else {
06347                /* This call hasn't been completed yet...  Set owner to NULL */
06348                ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06349                p->owner = NULL;
06350             }
06351             p->subs[SUB_REAL].inthreeway = 0;
06352          }
06353       } else if (idx == SUB_CALLWAIT) {
06354          /* Ditch the holding callwait call, and immediately make it availabe */
06355          if (p->subs[SUB_CALLWAIT].inthreeway) {
06356             /* This is actually part of a three way, placed on hold.  Place the third part
06357                on music on hold now */
06358             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
06359                ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
06360                   S_OR(p->mohsuggest, NULL),
06361                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06362             }
06363             p->subs[SUB_THREEWAY].inthreeway = 0;
06364             /* Make it the call wait now */
06365             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
06366             unalloc_sub(p, SUB_THREEWAY);
06367          } else
06368             unalloc_sub(p, SUB_CALLWAIT);
06369       } else if (idx == SUB_THREEWAY) {
06370          if (p->subs[SUB_CALLWAIT].inthreeway) {
06371             /* The other party of the three way call is currently in a call-wait state.
06372                Start music on hold for them, and take the main guy out of the third call */
06373             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
06374                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
06375                   S_OR(p->mohsuggest, NULL),
06376                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06377             }
06378             p->subs[SUB_CALLWAIT].inthreeway = 0;
06379          }
06380          p->subs[SUB_REAL].inthreeway = 0;
06381          /* If this was part of a three way call index, let us make
06382             another three way call */
06383          unalloc_sub(p, SUB_THREEWAY);
06384       } else {
06385          /* This wasn't any sort of call, but how are we an index? */
06386          ast_log(LOG_WARNING, "Index found but not any type of call?\n");
06387       }
06388    }
06389 
06390    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
06391       p->owner = NULL;
06392       p->ringt = 0;
06393       p->distinctivering = 0;
06394       p->confirmanswer = 0;
06395       p->outgoing = 0;
06396       p->digital = 0;
06397       p->faxhandled = 0;
06398       p->pulsedial = 0;
06399       if (p->dsp) {
06400          ast_dsp_free(p->dsp);
06401          p->dsp = NULL;
06402       }
06403 
06404       revert_fax_buffers(p, ast);
06405 
06406       p->law = p->law_default;
06407       law = p->law_default;
06408       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06409       if (res < 0)
06410          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
06411       /* Perform low level hangup if no owner left */
06412 #ifdef HAVE_OPENR2
06413       if (p->mfcr2 && p->mfcr2call && openr2_chan_get_direction(p->r2chan) != OR2_DIR_STOPPED) {
06414          ast_log(LOG_DEBUG, "disconnecting MFC/R2 call on chan %d\n", p->channel);
06415          /* If it's an incoming call, check the mfcr2_forced_release setting */
06416          if (openr2_chan_get_direction(p->r2chan) == OR2_DIR_BACKWARD && p->mfcr2_forced_release) {
06417             dahdi_r2_disconnect_call(p, OR2_CAUSE_FORCED_RELEASE);
06418          } else {
06419             const char *r2causestr = pbx_builtin_getvar_helper(ast, "MFCR2_CAUSE");
06420             int r2cause_user = r2causestr ? atoi(r2causestr) : 0;
06421             openr2_call_disconnect_cause_t r2cause = r2cause_user ? dahdi_ast_cause_to_r2_cause(r2cause_user)
06422                                                              : dahdi_ast_cause_to_r2_cause(ast->hangupcause);
06423             dahdi_r2_disconnect_call(p, r2cause);
06424          }
06425       } else if (p->mfcr2call) {
06426          ast_log(LOG_DEBUG, "Clearing call request on channel %d\n", p->channel);
06427          /* since ast_request() was called but not ast_call() we have not yet dialed
06428          and the openr2 stack will not call on_call_end callback, we need to unset
06429          the mfcr2call flag and bump the monitor count so the monitor thread can take
06430          care of this channel events from now on */
06431          p->mfcr2call = 0;
06432       }
06433 #endif
06434       switch (p->sig) {
06435       case SIG_SS7:
06436       case SIG_MFCR2:
06437       case SIG_PRI_LIB_HANDLE_CASES:
06438       case 0:
06439          break;
06440       default:
06441          res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
06442          break;
06443       }
06444       if (res < 0) {
06445          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
06446       }
06447       switch (p->sig) {
06448       case SIG_FXOGS:
06449       case SIG_FXOLS:
06450       case SIG_FXOKS:
06451          memset(&par, 0, sizeof(par));
06452          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
06453          if (!res) {
06454             struct analog_pvt *analog_p = p->sig_pvt;
06455 #if 0
06456             ast_debug(1, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
06457 #endif
06458             /* If they're off hook, try playing congestion */
06459             if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
06460                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
06461             else
06462                tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06463             analog_p->fxsoffhookstate = par.rxisoffhook;
06464          }
06465          break;
06466       case SIG_FXSGS:
06467       case SIG_FXSLS:
06468       case SIG_FXSKS:
06469          /* Make sure we're not made available for at least two seconds assuming
06470          we were actually used for an inbound or outbound call. */
06471          if (ast->_state != AST_STATE_RESERVED) {
06472             time(&p->guardtime);
06473             p->guardtime += 2;
06474          }
06475          break;
06476       default:
06477          tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06478          break;
06479       }
06480       if (p->sig)
06481          dahdi_disable_ec(p);
06482       x = 0;
06483       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
06484       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
06485       p->didtdd = 0;
06486       p->callwaitcas = 0;
06487       p->callwaiting = p->permcallwaiting;
06488       p->hidecallerid = p->permhidecallerid;
06489       p->waitingfordt.tv_sec = 0;
06490       p->dialing = 0;
06491       p->rdnis[0] = '\0';
06492       update_conf(p);
06493       reset_conf(p);
06494       /* Restore data mode */
06495       switch (p->sig) {
06496       case SIG_PRI_LIB_HANDLE_CASES:
06497       case SIG_SS7:
06498          x = 0;
06499          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
06500          break;
06501       default:
06502          break;
06503       }
06504       if (num_restart_pending == 0)
06505          restart_monitor();
06506    }
06507 
06508    p->callwaitingrepeat = 0;
06509    p->cidcwexpire = 0;
06510    p->cid_suppress_expire = 0;
06511    p->oprmode = 0;
06512 hangup_out:
06513    ast->tech_pvt = NULL;
06514    ast_free(p->cidspill);
06515    p->cidspill = NULL;
06516 
06517    ast_mutex_unlock(&p->lock);
06518    ast_verb(3, "Hungup '%s'\n", ast->name);
06519 
06520    ast_mutex_lock(&iflock);
06521    if (p->restartpending) {
06522       num_restart_pending--;
06523    }
06524 
06525    if (p->destroy) {
06526       destroy_channel(p, 0);
06527    }
06528    ast_mutex_unlock(&iflock);
06529 
06530    ast_module_unref(ast_module_info->self);
06531    return 0;
06532 }
06533 
06534 static int dahdi_answer(struct ast_channel *ast)
06535 {
06536    struct dahdi_pvt *p = ast->tech_pvt;
06537    int res = 0;
06538    int idx;
06539    ast_setstate(ast, AST_STATE_UP);/*! \todo XXX this is redundantly set by the analog and PRI submodules! */
06540    ast_mutex_lock(&p->lock);
06541    idx = dahdi_get_index(ast, p, 0);
06542    if (idx < 0)
06543       idx = SUB_REAL;
06544    /* nothing to do if a radio channel */
06545    if ((p->radio || (p->oprmode < 0))) {
06546       ast_mutex_unlock(&p->lock);
06547       return 0;
06548    }
06549 
06550    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06551       res = analog_answer(p->sig_pvt, ast);
06552       ast_mutex_unlock(&p->lock);
06553       return res;
06554    }
06555 
06556    switch (p->sig) {
06557 #if defined(HAVE_PRI)
06558    case SIG_PRI_LIB_HANDLE_CASES:
06559       res = sig_pri_answer(p->sig_pvt, ast);
06560       break;
06561 #endif   /* defined(HAVE_PRI) */
06562 #if defined(HAVE_SS7)
06563    case SIG_SS7:
06564       res = sig_ss7_answer(p->sig_pvt, ast);
06565       break;
06566 #endif   /* defined(HAVE_SS7) */
06567 #ifdef HAVE_OPENR2
06568    case SIG_MFCR2:
06569       if (!p->mfcr2_call_accepted) {
06570          /* The call was not accepted on offer nor the user, so it must be accepted now before answering,
06571             openr2_chan_answer_call will be called when the callback on_call_accepted is executed */
06572          p->mfcr2_answer_pending = 1;
06573          if (p->mfcr2_charge_calls) {
06574             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge before answering on chan %d\n", p->channel);
06575             openr2_chan_accept_call(p->r2chan, OR2_CALL_WITH_CHARGE);
06576          } else {
06577             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge before answering on chan %d\n", p->channel);
06578             openr2_chan_accept_call(p->r2chan, OR2_CALL_NO_CHARGE);
06579          }
06580       } else {
06581          ast_log(LOG_DEBUG, "Answering MFC/R2 call on chan %d\n", p->channel);
06582          dahdi_r2_answer(p);
06583       }
06584       break;
06585 #endif
06586    case 0:
06587       ast_mutex_unlock(&p->lock);
06588       return 0;
06589    default:
06590       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
06591       res = -1;
06592       break;
06593    }
06594    ast_mutex_unlock(&p->lock);
06595    return res;
06596 }
06597 
06598 static void disable_dtmf_detect(struct dahdi_pvt *p)
06599 {
06600    int val = 0;
06601 
06602    p->ignoredtmf = 1;
06603 
06604    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06605 
06606    if (!p->hardwaredtmf && p->dsp) {
06607       p->dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
06608       ast_dsp_set_features(p->dsp, p->dsp_features);
06609    }
06610 }
06611 
06612 static void enable_dtmf_detect(struct dahdi_pvt *p)
06613 {
06614    int val = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
06615 
06616    if (p->channel == CHAN_PSEUDO)
06617       return;
06618 
06619    p->ignoredtmf = 0;
06620 
06621    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06622 
06623    if (!p->hardwaredtmf && p->dsp) {
06624       p->dsp_features |= DSP_FEATURE_DIGIT_DETECT;
06625       ast_dsp_set_features(p->dsp, p->dsp_features);
06626    }
06627 }
06628 
06629 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
06630 {
06631    char *cp;
06632    struct dahdi_pvt *p = chan->tech_pvt;
06633 
06634    /* all supported options require data */
06635    if (!p || !data || (*datalen < 1)) {
06636       errno = EINVAL;
06637       return -1;
06638    }
06639 
06640    switch (option) {
06641    case AST_OPTION_DIGIT_DETECT:
06642       cp = (char *) data;
06643       *cp = p->ignoredtmf ? 0 : 1;
06644       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06645       break;
06646    case AST_OPTION_FAX_DETECT:
06647       cp = (char *) data;
06648       *cp = (p->dsp_features & DSP_FEATURE_FAX_DETECT) ? 0 : 1;
06649       ast_debug(1, "Reporting fax tone detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06650       break;
06651    case AST_OPTION_CC_AGENT_TYPE:
06652 #if defined(HAVE_PRI)
06653 #if defined(HAVE_PRI_CCSS)
06654       if (dahdi_sig_pri_lib_handles(p->sig)) {
06655          ast_copy_string((char *) data, dahdi_pri_cc_type, *datalen);
06656          break;
06657       }
06658 #endif   /* defined(HAVE_PRI_CCSS) */
06659 #endif   /* defined(HAVE_PRI) */
06660       return -1;
06661    default:
06662       return -1;
06663    }
06664 
06665    errno = 0;
06666 
06667    return 0;
06668 }
06669 
06670 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen)
06671 {
06672    char *cp;
06673    signed char *scp;
06674    int x;
06675    int idx;
06676    struct dahdi_pvt *p = chan->tech_pvt, *pp;
06677    struct oprmode *oprmode;
06678 
06679 
06680    /* all supported options require data */
06681    if (!p || !data || (datalen < 1)) {
06682       errno = EINVAL;
06683       return -1;
06684    }
06685 
06686    switch (option) {
06687    case AST_OPTION_TXGAIN:
06688       scp = (signed char *) data;
06689       idx = dahdi_get_index(chan, p, 0);
06690       if (idx < 0) {
06691          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
06692          return -1;
06693       }
06694       ast_debug(1, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
06695       return set_actual_txgain(p->subs[idx].dfd, p->txgain + (float) *scp, p->txdrc, p->law);
06696    case AST_OPTION_RXGAIN:
06697       scp = (signed char *) data;
06698       idx = dahdi_get_index(chan, p, 0);
06699       if (idx < 0) {
06700          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
06701          return -1;
06702       }
06703       ast_debug(1, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
06704       return set_actual_rxgain(p->subs[idx].dfd, p->rxgain + (float) *scp, p->rxdrc, p->law);
06705    case AST_OPTION_TONE_VERIFY:
06706       if (!p->dsp)
06707          break;
06708       cp = (char *) data;
06709       switch (*cp) {
06710       case 1:
06711          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
06712          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
06713          break;
06714       case 2:
06715          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
06716          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
06717          break;
06718       default:
06719          ast_debug(1, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
06720          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
06721          break;
06722       }
06723       break;
06724    case AST_OPTION_TDD:
06725       /* turn on or off TDD */
06726       cp = (char *) data;
06727       p->mate = 0;
06728       if (!*cp) { /* turn it off */
06729          ast_debug(1, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
06730          if (p->tdd)
06731             tdd_free(p->tdd);
06732          p->tdd = 0;
06733          break;
06734       }
06735       ast_debug(1, "Set option TDD MODE, value: %s(%d) on %s\n",
06736          (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
06737       dahdi_disable_ec(p);
06738       /* otherwise, turn it on */
06739       if (!p->didtdd) { /* if havent done it yet */
06740          unsigned char mybuf[41000];/*! \todo XXX This is an abuse of the stack!! */
06741          unsigned char *buf;
06742          int size, res, fd, len;
06743          struct pollfd fds[1];
06744 
06745          buf = mybuf;
06746          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
06747          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
06748          len = 40000;
06749          idx = dahdi_get_index(chan, p, 0);
06750          if (idx < 0) {
06751             ast_log(LOG_WARNING, "No index in TDD?\n");
06752             return -1;
06753          }
06754          fd = p->subs[idx].dfd;
06755          while (len) {
06756             if (ast_check_hangup(chan))
06757                return -1;
06758             size = len;
06759             if (size > READ_SIZE)
06760                size = READ_SIZE;
06761             fds[0].fd = fd;
06762             fds[0].events = POLLPRI | POLLOUT;
06763             fds[0].revents = 0;
06764             res = poll(fds, 1, -1);
06765             if (!res) {
06766                ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
06767                continue;
06768             }
06769             /* if got exception */
06770             if (fds[0].revents & POLLPRI)
06771                return -1;
06772             if (!(fds[0].revents & POLLOUT)) {
06773                ast_debug(1, "write fd not ready on channel %d\n", p->channel);
06774                continue;
06775             }
06776             res = write(fd, buf, size);
06777             if (res != size) {
06778                if (res == -1) return -1;
06779                ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
06780                break;
06781             }
06782             len -= size;
06783             buf += size;
06784          }
06785          p->didtdd = 1; /* set to have done it now */
06786       }
06787       if (*cp == 2) { /* Mate mode */
06788          if (p->tdd)
06789             tdd_free(p->tdd);
06790          p->tdd = 0;
06791          p->mate = 1;
06792          break;
06793       }
06794       if (!p->tdd) { /* if we don't have one yet */
06795          p->tdd = tdd_new(); /* allocate one */
06796       }
06797       break;
06798    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
06799       if (!p->dsp)
06800          break;
06801       cp = (char *) data;
06802       ast_debug(1, "Set option RELAX DTMF, value: %s(%d) on %s\n",
06803          *cp ? "ON" : "OFF", (int) *cp, chan->name);
06804       ast_dsp_set_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
06805       break;
06806    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
06807 #if defined(HAVE_PRI)
06808       if (dahdi_sig_pri_lib_handles(p->sig)
06809          && ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
06810          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
06811          break;
06812       }
06813 #endif   /* defined(HAVE_PRI) */
06814 
06815       cp = (char *) data;
06816       if (!*cp) {
06817          ast_debug(1, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
06818          x = 0;
06819          dahdi_disable_ec(p);
06820       } else {
06821          ast_debug(1, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
06822          x = 1;
06823       }
06824       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x) == -1)
06825          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", p->channel, x, strerror(errno));
06826       break;
06827    case AST_OPTION_OPRMODE:  /* Operator services mode */
06828       oprmode = (struct oprmode *) data;
06829       /* We don't support operator mode across technologies */
06830       if (strcasecmp(chan->tech->type, oprmode->peer->tech->type)) {
06831          ast_log(LOG_NOTICE, "Operator mode not supported on %s to %s calls.\n",
06832                chan->tech->type, oprmode->peer->tech->type);
06833          errno = EINVAL;
06834          return -1;
06835       }
06836       pp = oprmode->peer->tech_pvt;
06837       p->oprmode = pp->oprmode = 0;
06838       /* setup peers */
06839       p->oprpeer = pp;
06840       pp->oprpeer = p;
06841       /* setup modes, if any */
06842       if (oprmode->mode)
06843       {
06844          pp->oprmode = oprmode->mode;
06845          p->oprmode = -oprmode->mode;
06846       }
06847       ast_debug(1, "Set Operator Services mode, value: %d on %s/%s\n",
06848          oprmode->mode, chan->name,oprmode->peer->name);
06849       break;
06850    case AST_OPTION_ECHOCAN:
06851       cp = (char *) data;
06852       if (*cp) {
06853          ast_debug(1, "Enabling echo cancellation on %s\n", chan->name);
06854          dahdi_enable_ec(p);
06855       } else {
06856          ast_debug(1, "Disabling echo cancellation on %s\n", chan->name);
06857          dahdi_disable_ec(p);
06858       }
06859       break;
06860    case AST_OPTION_DIGIT_DETECT:
06861       cp = (char *) data;
06862       ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
06863       if (*cp) {
06864          enable_dtmf_detect(p);
06865       } else {
06866          disable_dtmf_detect(p);
06867       }
06868       break;
06869    case AST_OPTION_FAX_DETECT:
06870       cp = (char *) data;
06871       if (p->dsp) {
06872          ast_debug(1, "%sabling fax tone detection on %s\n", *cp ? "En" : "Dis", chan->name);
06873          if (*cp) {
06874             p->dsp_features |= DSP_FEATURE_FAX_DETECT;
06875          } else {
06876             p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
06877          }
06878          ast_dsp_set_features(p->dsp, p->dsp_features);
06879       }
06880       break;
06881    default:
06882       return -1;
06883    }
06884    errno = 0;
06885 
06886    return 0;
06887 }
06888 
06889 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
06890 {
06891    struct dahdi_pvt *p = chan->tech_pvt;
06892    int res = 0;
06893 
06894    if (!p) {
06895       /* No private structure! */
06896       *buf = '\0';
06897       return -1;
06898    }
06899 
06900    if (!strcasecmp(data, "rxgain")) {
06901       ast_mutex_lock(&p->lock);
06902       snprintf(buf, len, "%f", p->rxgain);
06903       ast_mutex_unlock(&p->lock);
06904    } else if (!strcasecmp(data, "txgain")) {
06905       ast_mutex_lock(&p->lock);
06906       snprintf(buf, len, "%f", p->txgain);
06907       ast_mutex_unlock(&p->lock);
06908    } else if (!strcasecmp(data, "dahdi_channel")) {
06909       ast_mutex_lock(&p->lock);
06910       snprintf(buf, len, "%d", p->channel);
06911       ast_mutex_unlock(&p->lock);
06912    } else if (!strcasecmp(data, "dahdi_span")) {
06913       ast_mutex_lock(&p->lock);
06914       snprintf(buf, len, "%d", p->span);
06915       ast_mutex_unlock(&p->lock);
06916    } else if (!strcasecmp(data, "dahdi_type")) {
06917       ast_mutex_lock(&p->lock);
06918       switch (p->sig) {
06919 #if defined(HAVE_OPENR2)
06920       case SIG_MFCR2:
06921          ast_copy_string(buf, "mfc/r2", len);
06922          break;
06923 #endif   /* defined(HAVE_OPENR2) */
06924 #if defined(HAVE_PRI)
06925       case SIG_PRI_LIB_HANDLE_CASES:
06926          ast_copy_string(buf, "pri", len);
06927          break;
06928 #endif   /* defined(HAVE_PRI) */
06929       case 0:
06930          ast_copy_string(buf, "pseudo", len);
06931          break;
06932 #if defined(HAVE_SS7)
06933       case SIG_SS7:
06934          ast_copy_string(buf, "ss7", len);
06935          break;
06936 #endif   /* defined(HAVE_SS7) */
06937       default:
06938          /* The only thing left is analog ports. */
06939          ast_copy_string(buf, "analog", len);
06940          break;
06941       }
06942       ast_mutex_unlock(&p->lock);
06943 #if defined(HAVE_PRI)
06944 #if defined(HAVE_PRI_REVERSE_CHARGE)
06945    } else if (!strcasecmp(data, "reversecharge")) {
06946       ast_mutex_lock(&p->lock);
06947       switch (p->sig) {
06948       case SIG_PRI_LIB_HANDLE_CASES:
06949          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->reverse_charging_indication);
06950          break;
06951       default:
06952          *buf = '\0';
06953          res = -1;
06954          break;
06955       }
06956       ast_mutex_unlock(&p->lock);
06957 #endif
06958 #if defined(HAVE_PRI_SETUP_KEYPAD)
06959    } else if (!strcasecmp(data, "keypad_digits")) {
06960       ast_mutex_lock(&p->lock);
06961       switch (p->sig) {
06962       case SIG_PRI_LIB_HANDLE_CASES:
06963          ast_copy_string(buf, ((struct sig_pri_chan *) p->sig_pvt)->keypad_digits,
06964             len);
06965          break;
06966       default:
06967          *buf = '\0';
06968          res = -1;
06969          break;
06970       }
06971       ast_mutex_unlock(&p->lock);
06972 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
06973    } else if (!strcasecmp(data, "no_media_path")) {
06974       ast_mutex_lock(&p->lock);
06975       switch (p->sig) {
06976       case SIG_PRI_LIB_HANDLE_CASES:
06977          /*
06978           * TRUE if the call is on hold or is call waiting because
06979           * there is no media path available.
06980           */
06981          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel);
06982          break;
06983       default:
06984          *buf = '\0';
06985          res = -1;
06986          break;
06987       }
06988       ast_mutex_unlock(&p->lock);
06989 #endif   /* defined(HAVE_PRI) */
06990    } else {
06991       *buf = '\0';
06992       res = -1;
06993    }
06994 
06995    return res;
06996 }
06997 
06998 
06999 static int parse_buffers_policy(const char *parse, int *num_buffers, int *policy)
07000 {
07001    int res;
07002    char policy_str[21] = "";
07003 
07004    if ((res = sscanf(parse, "%30d,%20s", num_buffers, policy_str)) != 2) {
07005       ast_log(LOG_WARNING, "Parsing buffer string '%s' failed.\n", parse);
07006       return 1;
07007    }
07008    if (*num_buffers < 0) {
07009       ast_log(LOG_WARNING, "Invalid buffer count given '%d'.\n", *num_buffers);
07010       return -1;
07011    }
07012    if (!strcasecmp(policy_str, "full")) {
07013       *policy = DAHDI_POLICY_WHEN_FULL;
07014    } else if (!strcasecmp(policy_str, "immediate")) {
07015       *policy = DAHDI_POLICY_IMMEDIATE;
07016 #if defined(HAVE_DAHDI_HALF_FULL)
07017    } else if (!strcasecmp(policy_str, "half")) {
07018       *policy = DAHDI_POLICY_HALF_FULL;
07019 #endif
07020    } else {
07021       ast_log(LOG_WARNING, "Invalid policy name given '%s'.\n", policy_str);
07022       return -1;
07023    }
07024 
07025    return 0;
07026 }
07027 
07028 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value)
07029 {
07030    struct dahdi_pvt *p = chan->tech_pvt;
07031    int res = 0;
07032 
07033    if (!p) {
07034       /* No private structure! */
07035       return -1;
07036    }
07037 
07038    if (!strcasecmp(data, "buffers")) {
07039       int num_bufs, policy;
07040 
07041       if (!(parse_buffers_policy(value, &num_bufs, &policy))) {
07042          struct dahdi_bufferinfo bi = {
07043             .txbufpolicy = policy,
07044             .rxbufpolicy = policy,
07045             .bufsize = p->bufsize,
07046             .numbufs = num_bufs,
07047          };
07048          int bpres;
07049 
07050          if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07051             ast_log(LOG_WARNING, "Channel '%d' unable to override buffer policy: %s\n", p->channel, strerror(errno));
07052          } else {
07053             p->bufferoverrideinuse = 1;
07054          }
07055       } else {
07056          res = -1;
07057       }
07058    } else if (!strcasecmp(data, "echocan_mode")) {
07059       if (!strcasecmp(value, "on")) {
07060          ast_mutex_lock(&p->lock);
07061          dahdi_enable_ec(p);
07062          ast_mutex_unlock(&p->lock);
07063       } else if (!strcasecmp(value, "off")) {
07064          ast_mutex_lock(&p->lock);
07065          dahdi_disable_ec(p);
07066          ast_mutex_unlock(&p->lock);
07067 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07068       } else if (!strcasecmp(value, "fax")) {
07069          int blah = 1;
07070 
07071          ast_mutex_lock(&p->lock);
07072          if (!p->echocanon) {
07073             dahdi_enable_ec(p);
07074          }
07075          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
07076             ast_log(LOG_WARNING, "Unable to place echocan into fax mode on channel %d: %s\n", p->channel, strerror(errno));
07077          }
07078          ast_mutex_unlock(&p->lock);
07079       } else if (!strcasecmp(value, "voice")) {
07080          int blah = 0;
07081 
07082          ast_mutex_lock(&p->lock);
07083          if (!p->echocanon) {
07084             dahdi_enable_ec(p);
07085          }
07086          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
07087             ast_log(LOG_WARNING, "Unable to place echocan into voice mode on channel %d: %s\n", p->channel, strerror(errno));
07088          }
07089          ast_mutex_unlock(&p->lock);
07090 #endif
07091       } else {
07092          ast_log(LOG_WARNING, "Unsupported value '%s' provided for '%s' item.\n", value, data);
07093          res = -1;
07094       }
07095    } else {
07096       res = -1;
07097    }
07098 
07099    return res;
07100 }
07101 
07102 static void dahdi_unlink(struct dahdi_pvt *slave, struct dahdi_pvt *master, int needlock)
07103 {
07104    /* Unlink a specific slave or all slaves/masters from a given master */
07105    int x;
07106    int hasslaves;
07107    if (!master)
07108       return;
07109    if (needlock) {
07110       ast_mutex_lock(&master->lock);
07111       if (slave) {
07112          while (ast_mutex_trylock(&slave->lock)) {
07113             DEADLOCK_AVOIDANCE(&master->lock);
07114          }
07115       }
07116    }
07117    hasslaves = 0;
07118    for (x = 0; x < MAX_SLAVES; x++) {
07119       if (master->slaves[x]) {
07120          if (!slave || (master->slaves[x] == slave)) {
07121             /* Take slave out of the conference */
07122             ast_debug(1, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
07123             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
07124             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
07125             master->slaves[x]->master = NULL;
07126             master->slaves[x] = NULL;
07127          } else
07128             hasslaves = 1;
07129       }
07130       if (!hasslaves)
07131          master->inconference = 0;
07132    }
07133    if (!slave) {
07134       if (master->master) {
07135          /* Take master out of the conference */
07136          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
07137          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
07138          hasslaves = 0;
07139          for (x = 0; x < MAX_SLAVES; x++) {
07140             if (master->master->slaves[x] == master)
07141                master->master->slaves[x] = NULL;
07142             else if (master->master->slaves[x])
07143                hasslaves = 1;
07144          }
07145          if (!hasslaves)
07146             master->master->inconference = 0;
07147       }
07148       master->master = NULL;
07149    }
07150    update_conf(master);
07151    if (needlock) {
07152       if (slave)
07153          ast_mutex_unlock(&slave->lock);
07154       ast_mutex_unlock(&master->lock);
07155    }
07156 }
07157 
07158 static void dahdi_link(struct dahdi_pvt *slave, struct dahdi_pvt *master) {
07159    int x;
07160    if (!slave || !master) {
07161       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
07162       return;
07163    }
07164    for (x = 0; x < MAX_SLAVES; x++) {
07165       if (!master->slaves[x]) {
07166          master->slaves[x] = slave;
07167          break;
07168       }
07169    }
07170    if (x >= MAX_SLAVES) {
07171       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
07172       master->slaves[MAX_SLAVES - 1] = slave;
07173    }
07174    if (slave->master)
07175       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
07176    slave->master = master;
07177 
07178    ast_debug(1, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
07179 }
07180 
07181 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)
07182 {
07183    struct ast_channel *who;
07184    struct dahdi_pvt *p0, *p1, *op0, *op1;
07185    struct dahdi_pvt *master = NULL, *slave = NULL;
07186    struct ast_frame *f;
07187    int inconf = 0;
07188    int nothingok = 1;
07189    int ofd0, ofd1;
07190    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
07191    int os0 = -1, os1 = -1;
07192    int priority = 0;
07193    struct ast_channel *oc0, *oc1;
07194    enum ast_bridge_result res;
07195 #ifdef PRI_2BCT
07196    int triedtopribridge = 0;
07197    q931_call *q931c0;
07198    q931_call *q931c1;
07199 #endif
07200 
07201    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
07202       There is code below to handle it properly until DTMF is actually seen,
07203       but due to currently unresolved issues it's ignored...
07204    */
07205 
07206    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
07207       return AST_BRIDGE_FAILED_NOWARN;
07208 
07209    ast_channel_lock(c0);
07210    while (ast_channel_trylock(c1)) {
07211       CHANNEL_DEADLOCK_AVOIDANCE(c0);
07212    }
07213 
07214    p0 = c0->tech_pvt;
07215    p1 = c1->tech_pvt;
07216    /* cant do pseudo-channels here */
07217    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
07218       ast_channel_unlock(c0);
07219       ast_channel_unlock(c1);
07220       return AST_BRIDGE_FAILED_NOWARN;
07221    }
07222 
07223    oi0 = dahdi_get_index(c0, p0, 0);
07224    oi1 = dahdi_get_index(c1, p1, 0);
07225    if ((oi0 < 0) || (oi1 < 0)) {
07226       ast_channel_unlock(c0);
07227       ast_channel_unlock(c1);
07228       return AST_BRIDGE_FAILED;
07229    }
07230 
07231    op0 = p0 = c0->tech_pvt;
07232    op1 = p1 = c1->tech_pvt;
07233    ofd0 = c0->fds[0];
07234    ofd1 = c1->fds[0];
07235    oc0 = p0->owner;
07236    oc1 = p1->owner;
07237 
07238    if (ast_mutex_trylock(&p0->lock)) {
07239       /* Don't block, due to potential for deadlock */
07240       ast_channel_unlock(c0);
07241       ast_channel_unlock(c1);
07242       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
07243       return AST_BRIDGE_RETRY;
07244    }
07245    if (ast_mutex_trylock(&p1->lock)) {
07246       /* Don't block, due to potential for deadlock */
07247       ast_mutex_unlock(&p0->lock);
07248       ast_channel_unlock(c0);
07249       ast_channel_unlock(c1);
07250       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
07251       return AST_BRIDGE_RETRY;
07252    }
07253 
07254    if ((p0->callwaiting && p0->callwaitingcallerid)
07255       || (p1->callwaiting && p1->callwaitingcallerid)) {
07256       /*
07257        * Call Waiting Caller ID requires DTMF detection to know if it
07258        * can send the CID spill.
07259        *
07260        * For now, don't attempt to native bridge if either channel
07261        * needs DTMF detection.  There is code below to handle it
07262        * properly until DTMF is actually seen, but due to currently
07263        * unresolved issues it's ignored...
07264        */
07265       ast_mutex_unlock(&p0->lock);
07266       ast_mutex_unlock(&p1->lock);
07267       ast_channel_unlock(c0);
07268       ast_channel_unlock(c1);
07269       return AST_BRIDGE_FAILED_NOWARN;
07270    }
07271 
07272 #if defined(HAVE_PRI)
07273    if ((dahdi_sig_pri_lib_handles(p0->sig)
07274          && ((struct sig_pri_chan *) p0->sig_pvt)->no_b_channel)
07275       || (dahdi_sig_pri_lib_handles(p1->sig)
07276          && ((struct sig_pri_chan *) p1->sig_pvt)->no_b_channel)) {
07277       /*
07278        * PRI nobch channels (hold and call waiting) are equivalent to
07279        * pseudo channels and cannot be done here.
07280        */
07281       ast_mutex_unlock(&p0->lock);
07282       ast_mutex_unlock(&p1->lock);
07283       ast_channel_unlock(c0);
07284       ast_channel_unlock(c1);
07285       return AST_BRIDGE_FAILED_NOWARN;
07286    }
07287 #endif   /* defined(HAVE_PRI) */
07288 
07289    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07290       if (p0->owner && p1->owner) {
07291          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
07292          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
07293             master = p0;
07294             slave = p1;
07295             inconf = 1;
07296          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
07297             master = p1;
07298             slave = p0;
07299             inconf = 1;
07300          } else {
07301             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
07302             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
07303                p0->channel,
07304                oi0, (p0->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07305                p0->subs[SUB_REAL].inthreeway, p0->channel,
07306                oi0, (p1->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07307                p1->subs[SUB_REAL].inthreeway);
07308          }
07309          nothingok = 0;
07310       }
07311    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
07312       if (p1->subs[SUB_THREEWAY].inthreeway) {
07313          master = p1;
07314          slave = p0;
07315          nothingok = 0;
07316       }
07317    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
07318       if (p0->subs[SUB_THREEWAY].inthreeway) {
07319          master = p0;
07320          slave = p1;
07321          nothingok = 0;
07322       }
07323    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
07324       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise,
07325          don't put us in anything */
07326       if (p1->subs[SUB_CALLWAIT].inthreeway) {
07327          master = p1;
07328          slave = p0;
07329          nothingok = 0;
07330       }
07331    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
07332       /* Same as previous */
07333       if (p0->subs[SUB_CALLWAIT].inthreeway) {
07334          master = p0;
07335          slave = p1;
07336          nothingok = 0;
07337       }
07338    }
07339    ast_debug(1, "master: %d, slave: %d, nothingok: %d\n",
07340       master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
07341    if (master && slave) {
07342       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
07343          in an active threeway call with a channel that is ringing, we should
07344          indicate ringing. */
07345       if ((oi1 == SUB_THREEWAY) &&
07346          p1->subs[SUB_THREEWAY].inthreeway &&
07347          p1->subs[SUB_REAL].owner &&
07348          p1->subs[SUB_REAL].inthreeway &&
07349          (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07350          ast_debug(1,
07351             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
07352             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
07353          tone_zone_play_tone(p0->subs[oi0].dfd, DAHDI_TONE_RINGTONE);
07354          os1 = p1->subs[SUB_REAL].owner->_state;
07355       } else {
07356          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
07357             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
07358          tone_zone_play_tone(p0->subs[oi0].dfd, -1);
07359       }
07360       if ((oi0 == SUB_THREEWAY) &&
07361          p0->subs[SUB_THREEWAY].inthreeway &&
07362          p0->subs[SUB_REAL].owner &&
07363          p0->subs[SUB_REAL].inthreeway &&
07364          (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07365          ast_debug(1,
07366             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
07367             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
07368          tone_zone_play_tone(p1->subs[oi1].dfd, DAHDI_TONE_RINGTONE);
07369          os0 = p0->subs[SUB_REAL].owner->_state;
07370       } else {
07371          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
07372             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
07373          tone_zone_play_tone(p1->subs[oi1].dfd, -1);
07374       }
07375       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07376          if (!p0->echocanbridged || !p1->echocanbridged) {
07377             /* Disable echo cancellation if appropriate */
07378             dahdi_disable_ec(p0);
07379             dahdi_disable_ec(p1);
07380          }
07381       }
07382       dahdi_link(slave, master);
07383       master->inconference = inconf;
07384    } else if (!nothingok)
07385       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
07386 
07387    update_conf(p0);
07388    update_conf(p1);
07389    t0 = p0->subs[SUB_REAL].inthreeway;
07390    t1 = p1->subs[SUB_REAL].inthreeway;
07391 
07392    ast_mutex_unlock(&p0->lock);
07393    ast_mutex_unlock(&p1->lock);
07394 
07395    ast_channel_unlock(c0);
07396    ast_channel_unlock(c1);
07397 
07398    /* Native bridge failed */
07399    if ((!master || !slave) && !nothingok) {
07400       dahdi_enable_ec(p0);
07401       dahdi_enable_ec(p1);
07402       return AST_BRIDGE_FAILED;
07403    }
07404 
07405    ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
07406 
07407    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07408       disable_dtmf_detect(op0);
07409 
07410    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07411       disable_dtmf_detect(op1);
07412 
07413    for (;;) {
07414       struct ast_channel *c0_priority[2] = {c0, c1};
07415       struct ast_channel *c1_priority[2] = {c1, c0};
07416 
07417       /* Here's our main loop...  Start by locking things, looking for private parts,
07418          and then balking if anything is wrong */
07419 
07420       ast_channel_lock(c0);
07421       while (ast_channel_trylock(c1)) {
07422          CHANNEL_DEADLOCK_AVOIDANCE(c0);
07423       }
07424 
07425       p0 = c0->tech_pvt;
07426       p1 = c1->tech_pvt;
07427 
07428       if (op0 == p0)
07429          i0 = dahdi_get_index(c0, p0, 1);
07430       if (op1 == p1)
07431          i1 = dahdi_get_index(c1, p1, 1);
07432 
07433       ast_channel_unlock(c0);
07434       ast_channel_unlock(c1);
07435 
07436       if (!timeoutms ||
07437          (op0 != p0) ||
07438          (op1 != p1) ||
07439          (ofd0 != c0->fds[0]) ||
07440          (ofd1 != c1->fds[0]) ||
07441          (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
07442          (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
07443          (oc0 != p0->owner) ||
07444          (oc1 != p1->owner) ||
07445          (t0 != p0->subs[SUB_REAL].inthreeway) ||
07446          (t1 != p1->subs[SUB_REAL].inthreeway) ||
07447          (oi0 != i0) ||
07448          (oi1 != i1)) {
07449          ast_debug(1, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
07450             op0->channel, oi0, op1->channel, oi1);
07451          res = AST_BRIDGE_RETRY;
07452          goto return_from_bridge;
07453       }
07454 
07455 #ifdef PRI_2BCT
07456       if (!triedtopribridge) {
07457          triedtopribridge = 1;
07458          if (p0->pri && p0->pri == p1->pri && p0->pri->transfer) {
07459             ast_mutex_lock(&p0->pri->lock);
07460             switch (p0->sig) {
07461             case SIG_PRI_LIB_HANDLE_CASES:
07462                q931c0 = ((struct sig_pri_chan *) (p0->sig_pvt))->call;
07463                break;
07464             default:
07465                q931c0 = NULL;
07466                break;
07467             }
07468             switch (p1->sig) {
07469             case SIG_PRI_LIB_HANDLE_CASES:
07470                q931c1 = ((struct sig_pri_chan *) (p1->sig_pvt))->call;
07471                break;
07472             default:
07473                q931c1 = NULL;
07474                break;
07475             }
07476             if (q931c0 && q931c1) {
07477                pri_channel_bridge(q931c0, q931c1);
07478             }
07479             ast_mutex_unlock(&p0->pri->lock);
07480          }
07481       }
07482 #endif
07483 
07484       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
07485       if (!who) {
07486          ast_debug(1, "Ooh, empty read...\n");
07487          continue;
07488       }
07489       f = ast_read(who);
07490       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
07491          *fo = f;
07492          *rc = who;
07493          res = AST_BRIDGE_COMPLETE;
07494          goto return_from_bridge;
07495       }
07496       if (f->frametype == AST_FRAME_DTMF) {
07497          if ((who == c0) && p0->pulsedial) {
07498             ast_write(c1, f);
07499          } else if ((who == c1) && p1->pulsedial) {
07500             ast_write(c0, f);
07501          } else {
07502             *fo = f;
07503             *rc = who;
07504             res = AST_BRIDGE_COMPLETE;
07505             goto return_from_bridge;
07506          }
07507       }
07508       ast_frfree(f);
07509 
07510       /* Swap who gets priority */
07511       priority = !priority;
07512    }
07513 
07514 return_from_bridge:
07515    if (op0 == p0)
07516       dahdi_enable_ec(p0);
07517 
07518    if (op1 == p1)
07519       dahdi_enable_ec(p1);
07520 
07521    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07522       enable_dtmf_detect(op0);
07523 
07524    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07525       enable_dtmf_detect(op1);
07526 
07527    dahdi_unlink(slave, master, 1);
07528 
07529    return res;
07530 }
07531 
07532 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07533 {
07534    struct dahdi_pvt *p = newchan->tech_pvt;
07535    int x;
07536 
07537    ast_mutex_lock(&p->lock);
07538 
07539    ast_debug(1, "New owner for channel %d is %s\n", p->channel, newchan->name);
07540    if (p->owner == oldchan) {
07541       p->owner = newchan;
07542    }
07543    for (x = 0; x < 3; x++) {
07544       if (p->subs[x].owner == oldchan) {
07545          if (!x) {
07546             dahdi_unlink(NULL, p, 0);
07547          }
07548          p->subs[x].owner = newchan;
07549       }
07550    }
07551    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
07552       analog_fixup(oldchan, newchan, p->sig_pvt);
07553 #if defined(HAVE_PRI)
07554    } else if (dahdi_sig_pri_lib_handles(p->sig)) {
07555       sig_pri_fixup(oldchan, newchan, p->sig_pvt);
07556 #endif   /* defined(HAVE_PRI) */
07557 #if defined(HAVE_SS7)
07558    } else if (p->sig == SIG_SS7) {
07559       sig_ss7_fixup(oldchan, newchan, p->sig_pvt);
07560 #endif   /* defined(HAVE_SS7) */
07561    }
07562    update_conf(p);
07563 
07564    ast_mutex_unlock(&p->lock);
07565 
07566    if (newchan->_state == AST_STATE_RINGING) {
07567       dahdi_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
07568    }
07569    return 0;
07570 }
07571 
07572 static int dahdi_ring_phone(struct dahdi_pvt *p)
07573 {
07574    int x;
07575    int res;
07576    /* Make sure our transmit state is on hook */
07577    x = 0;
07578    x = DAHDI_ONHOOK;
07579    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07580    do {
07581       x = DAHDI_RING;
07582       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07583       if (res) {
07584          switch (errno) {
07585          case EBUSY:
07586          case EINTR:
07587             /* Wait just in case */
07588             usleep(10000);
07589             continue;
07590          case EINPROGRESS:
07591             res = 0;
07592             break;
07593          default:
07594             ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
07595             res = 0;
07596          }
07597       }
07598    } while (res);
07599    return res;
07600 }
07601 
07602 static void *analog_ss_thread(void *data);
07603 
07604 static int attempt_transfer(struct dahdi_pvt *p)
07605 {
07606    /* In order to transfer, we need at least one of the channels to
07607       actually be in a call bridge.  We can't conference two applications
07608       together (but then, why would we want to?) */
07609    if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
07610       /* The three-way person we're about to transfer to could still be in MOH, so
07611          stop if now if appropriate */
07612       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
07613          ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
07614       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
07615          ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
07616       }
07617       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
07618          tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, DAHDI_TONE_RINGTONE);
07619       }
07620        if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
07621          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07622                ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
07623          return -1;
07624       }
07625       /* Orphan the channel after releasing the lock */
07626       ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07627       unalloc_sub(p, SUB_THREEWAY);
07628    } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
07629       ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
07630       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
07631          ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
07632       }
07633       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
07634          tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
07635       }
07636       if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
07637          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07638                ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
07639          return -1;
07640       }
07641       /* Three-way is now the REAL */
07642       swap_subs(p, SUB_THREEWAY, SUB_REAL);
07643       ast_channel_unlock(p->subs[SUB_REAL].owner);
07644       unalloc_sub(p, SUB_THREEWAY);
07645       /* Tell the caller not to hangup */
07646       return 1;
07647    } else {
07648       ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
07649          p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
07650       p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07651       return -1;
07652    }
07653    return 0;
07654 }
07655 
07656 static int check_for_conference(struct dahdi_pvt *p)
07657 {
07658    struct dahdi_confinfo ci;
07659    /* Fine if we already have a master, etc */
07660    if (p->master || (p->confno > -1))
07661       return 0;
07662    memset(&ci, 0, sizeof(ci));
07663    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
07664       ast_log(LOG_WARNING, "Failed to get conference info on channel %d: %s\n", p->channel, strerror(errno));
07665       return 0;
07666    }
07667    /* If we have no master and don't have a confno, then
07668       if we're in a conference, it's probably a MeetMe room or
07669       some such, so don't let us 3-way out! */
07670    if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
07671       ast_verb(3, "Avoiding 3-way call when in an external conference\n");
07672       return 1;
07673    }
07674    return 0;
07675 }
07676 
07677 /*! Checks channel for alarms
07678  * \param p a channel to check for alarms.
07679  * \returns the alarms on the span to which the channel belongs, or alarms on
07680  *          the channel if no span alarms.
07681  */
07682 static int get_alarms(struct dahdi_pvt *p)
07683 {
07684    int res;
07685    struct dahdi_spaninfo zi;
07686    struct dahdi_params params;
07687 
07688    memset(&zi, 0, sizeof(zi));
07689    zi.spanno = p->span;
07690 
07691    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SPANSTAT, &zi)) >= 0) {
07692       if (zi.alarms != DAHDI_ALARM_NONE)
07693          return zi.alarms;
07694    } else {
07695       ast_log(LOG_WARNING, "Unable to determine alarm on channel %d: %s\n", p->channel, strerror(errno));
07696       return 0;
07697    }
07698 
07699    /* No alarms on the span. Check for channel alarms. */
07700    memset(&params, 0, sizeof(params));
07701    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &params)) >= 0)
07702       return params.chan_alarms;
07703 
07704    ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
07705 
07706    return DAHDI_ALARM_NONE;
07707 }
07708 
07709 static void dahdi_handle_dtmf(struct ast_channel *ast, int idx, struct ast_frame **dest)
07710 {
07711    struct dahdi_pvt *p = ast->tech_pvt;
07712    struct ast_frame *f = *dest;
07713 
07714    ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
07715       f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
07716       f->subclass.integer, f->subclass.integer, ast->name);
07717 
07718    if (p->confirmanswer) {
07719       if (f->frametype == AST_FRAME_DTMF_END) {
07720          ast_debug(1, "Confirm answer on %s!\n", ast->name);
07721          /* Upon receiving a DTMF digit, consider this an answer confirmation instead
07722             of a DTMF digit */
07723          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07724          p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07725          /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
07726          p->confirmanswer = 0;
07727       } else {
07728          p->subs[idx].f.frametype = AST_FRAME_NULL;
07729          p->subs[idx].f.subclass.integer = 0;
07730       }
07731       *dest = &p->subs[idx].f;
07732    } else if (p->callwaitcas) {
07733       if (f->frametype == AST_FRAME_DTMF_END) {
07734          if ((f->subclass.integer == 'A') || (f->subclass.integer == 'D')) {
07735             ast_debug(1, "Got some DTMF, but it's for the CAS\n");
07736             ast_free(p->cidspill);
07737             p->cidspill = NULL;
07738             send_cwcidspill(p);
07739          }
07740          p->callwaitcas = 0;
07741       }
07742       p->subs[idx].f.frametype = AST_FRAME_NULL;
07743       p->subs[idx].f.subclass.integer = 0;
07744       *dest = &p->subs[idx].f;
07745    } else if (f->subclass.integer == 'f') {
07746       if (f->frametype == AST_FRAME_DTMF_END) {
07747          /* Fax tone -- Handle and return NULL */
07748          if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
07749             /* If faxbuffers are configured, use them for the fax transmission */
07750             if (p->usefaxbuffers && !p->bufferoverrideinuse) {
07751                struct dahdi_bufferinfo bi = {
07752                   .txbufpolicy = p->faxbuf_policy,
07753                   .bufsize = p->bufsize,
07754                   .numbufs = p->faxbuf_no
07755                };
07756                int res;
07757 
07758                if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07759                   ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
07760                } else {
07761                   p->bufferoverrideinuse = 1;
07762                }
07763             }
07764             p->faxhandled = 1;
07765             if (p->dsp) {
07766                p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
07767                ast_dsp_set_features(p->dsp, p->dsp_features);
07768                ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
07769             }
07770             if (strcmp(ast->exten, "fax")) {
07771                const char *target_context = S_OR(ast->macrocontext, ast->context);
07772 
07773                /* We need to unlock 'ast' here because ast_exists_extension has the
07774                 * potential to start autoservice on the channel. Such action is prone
07775                 * to deadlock.
07776                 */
07777                ast_mutex_unlock(&p->lock);
07778                ast_channel_unlock(ast);
07779                if (ast_exists_extension(ast, target_context, "fax", 1,
07780                   S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07781                   ast_channel_lock(ast);
07782                   ast_mutex_lock(&p->lock);
07783                   ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
07784                   /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
07785                   pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07786                   if (ast_async_goto(ast, target_context, "fax", 1))
07787                      ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07788                } else {
07789                   ast_channel_lock(ast);
07790                   ast_mutex_lock(&p->lock);
07791                   ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
07792                }
07793             } else {
07794                ast_debug(1, "Already in a fax extension, not redirecting\n");
07795             }
07796          } else {
07797             ast_debug(1, "Fax already handled\n");
07798          }
07799          dahdi_confmute(p, 0);
07800       }
07801       p->subs[idx].f.frametype = AST_FRAME_NULL;
07802       p->subs[idx].f.subclass.integer = 0;
07803       *dest = &p->subs[idx].f;
07804    }
07805 }
07806 
07807 static void handle_alarms(struct dahdi_pvt *p, int alms)
07808 {
07809    const char *alarm_str = alarm2str(alms);
07810 
07811    if (report_alarms & REPORT_CHANNEL_ALARMS) {
07812       ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm_str);
07813       manager_event(EVENT_FLAG_SYSTEM, "Alarm",
07814                  "Alarm: %s\r\n"
07815                  "Channel: %d\r\n",
07816                  alarm_str, p->channel);
07817    }
07818 
07819    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
07820       ast_log(LOG_WARNING, "Detected alarm on span %d: %s\n", p->span, alarm_str);
07821       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarm",
07822                  "Alarm: %s\r\n"
07823                  "Span: %d\r\n",
07824                  alarm_str, p->span);
07825    }
07826 }
07827 
07828 static struct ast_frame *dahdi_handle_event(struct ast_channel *ast)
07829 {
07830    int res, x;
07831    int idx, mysig;
07832    char *c;
07833    struct dahdi_pvt *p = ast->tech_pvt;
07834    pthread_t threadid;
07835    struct ast_channel *chan;
07836    struct ast_frame *f;
07837 
07838    idx = dahdi_get_index(ast, p, 0);
07839    mysig = p->sig;
07840    if (p->outsigmod > -1)
07841       mysig = p->outsigmod;
07842    p->subs[idx].f.frametype = AST_FRAME_NULL;
07843    p->subs[idx].f.subclass.integer = 0;
07844    p->subs[idx].f.datalen = 0;
07845    p->subs[idx].f.samples = 0;
07846    p->subs[idx].f.mallocd = 0;
07847    p->subs[idx].f.offset = 0;
07848    p->subs[idx].f.src = "dahdi_handle_event";
07849    p->subs[idx].f.data.ptr = NULL;
07850    f = &p->subs[idx].f;
07851 
07852    if (idx < 0)
07853       return &p->subs[idx].f;
07854    if (p->fake_event) {
07855       res = p->fake_event;
07856       p->fake_event = 0;
07857    } else
07858       res = dahdi_get_event(p->subs[idx].dfd);
07859 
07860    ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, idx);
07861 
07862    if (res & (DAHDI_EVENT_PULSEDIGIT | DAHDI_EVENT_DTMFUP)) {
07863       p->pulsedial = (res & DAHDI_EVENT_PULSEDIGIT) ? 1 : 0;
07864       ast_debug(1, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
07865 #if defined(HAVE_PRI)
07866       if (dahdi_sig_pri_lib_handles(p->sig)
07867          && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
07868          && p->pri
07869          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07870          /* absorb event */
07871       } else
07872 #endif   /* defined(HAVE_PRI) */
07873       {
07874          /* Unmute conference */
07875          dahdi_confmute(p, 0);
07876          p->subs[idx].f.frametype = AST_FRAME_DTMF_END;
07877          p->subs[idx].f.subclass.integer = res & 0xff;
07878          dahdi_handle_dtmf(ast, idx, &f);
07879       }
07880       return f;
07881    }
07882 
07883    if (res & DAHDI_EVENT_DTMFDOWN) {
07884       ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
07885 #if defined(HAVE_PRI)
07886       if (dahdi_sig_pri_lib_handles(p->sig)
07887          && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
07888          && p->pri
07889          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07890          /* absorb event */
07891       } else
07892 #endif   /* defined(HAVE_PRI) */
07893       {
07894          /* Mute conference */
07895          dahdi_confmute(p, 1);
07896          p->subs[idx].f.frametype = AST_FRAME_DTMF_BEGIN;
07897          p->subs[idx].f.subclass.integer = res & 0xff;
07898          dahdi_handle_dtmf(ast, idx, &f);
07899       }
07900       return &p->subs[idx].f;
07901    }
07902 
07903    switch (res) {
07904    case DAHDI_EVENT_EC_DISABLED:
07905       ast_verb(3, "Channel %d echo canceler disabled.\n", p->channel);
07906       p->echocanon = 0;
07907       break;
07908 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07909    case DAHDI_EVENT_TX_CED_DETECTED:
07910       ast_verb(3, "Channel %d detected a CED tone towards the network.\n", p->channel);
07911       break;
07912    case DAHDI_EVENT_RX_CED_DETECTED:
07913       ast_verb(3, "Channel %d detected a CED tone from the network.\n", p->channel);
07914       break;
07915    case DAHDI_EVENT_EC_NLP_DISABLED:
07916       ast_verb(3, "Channel %d echo canceler disabled its NLP.\n", p->channel);
07917       break;
07918    case DAHDI_EVENT_EC_NLP_ENABLED:
07919       ast_verb(3, "Channel %d echo canceler enabled its NLP.\n", p->channel);
07920       break;
07921 #endif
07922    case DAHDI_EVENT_BITSCHANGED:
07923 #ifdef HAVE_OPENR2
07924       if (p->sig != SIG_MFCR2) {
07925          ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07926       } else {
07927          ast_log(LOG_DEBUG, "bits changed in chan %d\n", p->channel);
07928          openr2_chan_handle_cas(p->r2chan);
07929       }
07930 #else
07931       ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07932 #endif
07933    case DAHDI_EVENT_PULSE_START:
07934       /* Stop tone if there's a pulse start and the PBX isn't started */
07935       if (!ast->pbx)
07936          tone_zone_play_tone(p->subs[idx].dfd, -1);
07937       break;
07938    case DAHDI_EVENT_DIALCOMPLETE:
07939       /* DAHDI has completed dialing all digits sent using DAHDI_DIAL. */
07940 #if defined(HAVE_PRI)
07941       if (dahdi_sig_pri_lib_handles(p->sig)) {
07942          if (p->inalarm) {
07943             break;
07944          }
07945          if (ioctl(p->subs[idx].dfd, DAHDI_DIALING, &x) == -1) {
07946             ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n", ast->name,
07947                strerror(errno));
07948             return NULL;
07949          }
07950          if (x) {
07951             /* Still dialing in DAHDI driver */
07952             break;
07953          }
07954          /*
07955           * The ast channel is locked and the private may be locked more
07956           * than once.
07957           */
07958          sig_pri_dial_complete(p->sig_pvt, ast);
07959          break;
07960       }
07961 #endif   /* defined(HAVE_PRI) */
07962 #ifdef HAVE_OPENR2
07963       if ((p->sig & SIG_MFCR2) && p->r2chan && ast->_state != AST_STATE_UP) {
07964          /* we don't need to do anything for this event for R2 signaling
07965             if the call is being setup */
07966          break;
07967       }
07968 #endif
07969       if (p->inalarm) break;
07970       if ((p->radio || (p->oprmode < 0))) break;
07971       if (ioctl(p->subs[idx].dfd,DAHDI_DIALING,&x) == -1) {
07972          ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n",ast->name, strerror(errno));
07973          return NULL;
07974       }
07975       if (!x) { /* if not still dialing in driver */
07976          dahdi_enable_ec(p);
07977          if (p->echobreak) {
07978             dahdi_train_ec(p);
07979             ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
07980             p->dop.op = DAHDI_DIAL_OP_REPLACE;
07981             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
07982             p->echobreak = 0;
07983          } else {
07984             p->dialing = 0;
07985             if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
07986                /* if thru with dialing after offhook */
07987                if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
07988                   ast_setstate(ast, AST_STATE_UP);
07989                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07990                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07991                   break;
07992                } else { /* if to state wait for offhook to dial rest */
07993                   /* we now wait for off hook */
07994                   ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
07995                }
07996             }
07997             if (ast->_state == AST_STATE_DIALING) {
07998                if ((p->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
07999                   ast_debug(1, "Done dialing, but waiting for progress detection before doing more...\n");
08000                } else if (p->confirmanswer || (!p->dialednone
08001                   && ((mysig == SIG_EM) || (mysig == SIG_EM_E1)
08002                      || (mysig == SIG_EMWINK) || (mysig == SIG_FEATD)
08003                      || (mysig == SIG_FEATDMF_TA) || (mysig == SIG_FEATDMF)
08004                      || (mysig == SIG_E911) || (mysig == SIG_FGC_CAMA)
08005                      || (mysig == SIG_FGC_CAMAMF) || (mysig == SIG_FEATB)
08006                      || (mysig == SIG_SF) || (mysig == SIG_SFWINK)
08007                      || (mysig == SIG_SF_FEATD) || (mysig == SIG_SF_FEATDMF)
08008                      || (mysig == SIG_SF_FEATB)))) {
08009                   ast_setstate(ast, AST_STATE_RINGING);
08010                } else if (!p->answeronpolarityswitch) {
08011                   ast_setstate(ast, AST_STATE_UP);
08012                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08013                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08014                   /* If aops=0 and hops=1, this is necessary */
08015                   p->polarity = POLARITY_REV;
08016                } else {
08017                   /* Start clean, so we can catch the change to REV polarity when party answers */
08018                   p->polarity = POLARITY_IDLE;
08019                }
08020             }
08021          }
08022       }
08023       break;
08024    case DAHDI_EVENT_ALARM:
08025       switch (p->sig) {
08026 #if defined(HAVE_PRI)
08027       case SIG_PRI_LIB_HANDLE_CASES:
08028          sig_pri_chan_alarm_notify(p->sig_pvt, 0);
08029          break;
08030 #endif   /* defined(HAVE_PRI) */
08031 #if defined(HAVE_SS7)
08032       case SIG_SS7:
08033          sig_ss7_set_alarm(p->sig_pvt, 1);
08034          break;
08035 #endif   /* defined(HAVE_SS7) */
08036       default:
08037          p->inalarm = 1;
08038          break;
08039       }
08040       res = get_alarms(p);
08041       handle_alarms(p, res);
08042 #ifdef HAVE_PRI
08043       if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
08044          /* fall through intentionally */
08045       } else {
08046          break;
08047       }
08048 #endif
08049 #if defined(HAVE_SS7)
08050       if (p->sig == SIG_SS7)
08051          break;
08052 #endif   /* defined(HAVE_SS7) */
08053 #ifdef HAVE_OPENR2
08054       if (p->sig == SIG_MFCR2)
08055          break;
08056 #endif
08057    case DAHDI_EVENT_ONHOOK:
08058       if (p->radio) {
08059          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08060          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08061          break;
08062       }
08063       if (p->oprmode < 0)
08064       {
08065          if (p->oprmode != -1) break;
08066          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
08067          {
08068             /* Make sure it starts ringing */
08069             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08070             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RING);
08071             save_conference(p->oprpeer);
08072             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08073          }
08074          break;
08075       }
08076       switch (p->sig) {
08077       case SIG_FXOLS:
08078       case SIG_FXOGS:
08079       case SIG_FXOKS:
08080          /* Check for some special conditions regarding call waiting */
08081          if (idx == SUB_REAL) {
08082             /* The normal line was hung up */
08083             if (p->subs[SUB_CALLWAIT].owner) {
08084                /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
08085                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
08086                ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
08087                unalloc_sub(p, SUB_CALLWAIT);
08088 #if 0
08089                p->subs[idx].needanswer = 0;
08090                p->subs[idx].needringing = 0;
08091 #endif
08092                p->callwaitingrepeat = 0;
08093                p->cidcwexpire = 0;
08094                p->cid_suppress_expire = 0;
08095                p->owner = NULL;
08096                /* Don't start streaming audio yet if the incoming call isn't up yet */
08097                if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
08098                   p->dialing = 1;
08099                dahdi_ring_phone(p);
08100             } else if (p->subs[SUB_THREEWAY].owner) {
08101                unsigned int mssinceflash;
08102                /* Here we have to retain the lock on both the main channel, the 3-way channel, and
08103                   the private structure -- not especially easy or clean */
08104                while (p->subs[SUB_THREEWAY].owner && ast_channel_trylock(p->subs[SUB_THREEWAY].owner)) {
08105                   /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
08106                   DLA_UNLOCK(&p->lock);
08107                   CHANNEL_DEADLOCK_AVOIDANCE(ast);
08108                   /* We can grab ast and p in that order, without worry.  We should make sure
08109                      nothing seriously bad has happened though like some sort of bizarre double
08110                      masquerade! */
08111                   DLA_LOCK(&p->lock);
08112                   if (p->owner != ast) {
08113                      ast_log(LOG_WARNING, "This isn't good...\n");
08114                      return NULL;
08115                   }
08116                }
08117                if (!p->subs[SUB_THREEWAY].owner) {
08118                   ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
08119                   return NULL;
08120                }
08121                mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
08122                ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
08123                if (mssinceflash < MIN_MS_SINCE_FLASH) {
08124                   /* It hasn't been long enough since the last flashook.  This is probably a bounce on
08125                      hanging up.  Hangup both channels now */
08126                   if (p->subs[SUB_THREEWAY].owner)
08127                      ast_queue_hangup_with_cause(p->subs[SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
08128                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08129                   ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
08130                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08131                } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
08132                   if (p->transfer) {
08133                      /* In any case this isn't a threeway call anymore */
08134                      p->subs[SUB_REAL].inthreeway = 0;
08135                      p->subs[SUB_THREEWAY].inthreeway = 0;
08136                      /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
08137                      if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
08138                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08139                         /* Swap subs and dis-own channel */
08140                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
08141                         p->owner = NULL;
08142                         /* Ring the phone */
08143                         dahdi_ring_phone(p);
08144                      } else {
08145                         if ((res = attempt_transfer(p)) < 0) {
08146                            p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08147                            if (p->subs[SUB_THREEWAY].owner)
08148                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08149                         } else if (res) {
08150                            /* Don't actually hang up at this point */
08151                            if (p->subs[SUB_THREEWAY].owner)
08152                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08153                            break;
08154                         }
08155                      }
08156                   } else {
08157                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08158                      if (p->subs[SUB_THREEWAY].owner)
08159                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08160                   }
08161                } else {
08162                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08163                   /* Swap subs and dis-own channel */
08164                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08165                   p->owner = NULL;
08166                   /* Ring the phone */
08167                   dahdi_ring_phone(p);
08168                }
08169             }
08170          } else {
08171             ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", idx);
08172          }
08173          /* Fall through */
08174       default:
08175          dahdi_disable_ec(p);
08176          return NULL;
08177       }
08178       break;
08179    case DAHDI_EVENT_RINGOFFHOOK:
08180       if (p->inalarm) break;
08181       if (p->oprmode < 0)
08182       {
08183          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
08184          {
08185             /* Make sure it stops ringing */
08186             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08187             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, -1);
08188             restore_conference(p->oprpeer);
08189          }
08190          break;
08191       }
08192       if (p->radio)
08193       {
08194          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08195          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08196          break;
08197       }
08198       /* for E911, its supposed to wait for offhook then dial
08199          the second half of the dial string */
08200       if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
08201          c = strchr(p->dialdest, '/');
08202          if (c)
08203             c++;
08204          else
08205             c = p->dialdest;
08206          if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
08207          else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
08208          if (strlen(p->dop.dialstr) > 4) {
08209             memset(p->echorest, 'w', sizeof(p->echorest) - 1);
08210             strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
08211             p->echorest[sizeof(p->echorest) - 1] = '\0';
08212             p->echobreak = 1;
08213             p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
08214          } else
08215             p->echobreak = 0;
08216          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
08217             int saveerr = errno;
08218 
08219             x = DAHDI_ONHOOK;
08220             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
08221             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
08222             return NULL;
08223             }
08224          p->dialing = 1;
08225          return &p->subs[idx].f;
08226       }
08227       switch (p->sig) {
08228       case SIG_FXOLS:
08229       case SIG_FXOGS:
08230       case SIG_FXOKS:
08231          switch (ast->_state) {
08232          case AST_STATE_RINGING:
08233             dahdi_enable_ec(p);
08234             dahdi_train_ec(p);
08235             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08236             p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08237             /* Make sure it stops ringing */
08238             p->subs[SUB_REAL].needringing = 0;
08239             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
08240             ast_debug(1, "channel %d answered\n", p->channel);
08241 
08242             /* Cancel any running CallerID spill */
08243             ast_free(p->cidspill);
08244             p->cidspill = NULL;
08245             restore_conference(p);
08246 
08247             p->dialing = 0;
08248             p->callwaitcas = 0;
08249             if (p->confirmanswer) {
08250                /* Ignore answer if "confirm answer" is enabled */
08251                p->subs[idx].f.frametype = AST_FRAME_NULL;
08252                p->subs[idx].f.subclass.integer = 0;
08253             } else if (!ast_strlen_zero(p->dop.dialstr)) {
08254                /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
08255                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08256                if (res < 0) {
08257                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08258                   p->dop.dialstr[0] = '\0';
08259                   return NULL;
08260                } else {
08261                   ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
08262                   p->subs[idx].f.frametype = AST_FRAME_NULL;
08263                   p->subs[idx].f.subclass.integer = 0;
08264                   p->dialing = 1;
08265                }
08266                p->dop.dialstr[0] = '\0';
08267                ast_setstate(ast, AST_STATE_DIALING);
08268             } else
08269                ast_setstate(ast, AST_STATE_UP);
08270             return &p->subs[idx].f;
08271          case AST_STATE_DOWN:
08272             ast_setstate(ast, AST_STATE_RING);
08273             ast->rings = 1;
08274             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08275             p->subs[idx].f.subclass.integer = AST_CONTROL_OFFHOOK;
08276             ast_debug(1, "channel %d picked up\n", p->channel);
08277             return &p->subs[idx].f;
08278          case AST_STATE_UP:
08279             /* Make sure it stops ringing */
08280             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
08281             /* Okay -- probably call waiting*/
08282             if (ast_bridged_channel(p->owner))
08283                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08284             p->subs[idx].needunhold = 1;
08285             break;
08286          case AST_STATE_RESERVED:
08287             /* Start up dialtone */
08288             if (has_voicemail(p))
08289                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
08290             else
08291                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
08292             break;
08293          default:
08294             ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
08295          }
08296          break;
08297       case SIG_FXSLS:
08298       case SIG_FXSGS:
08299       case SIG_FXSKS:
08300          if (ast->_state == AST_STATE_RING) {
08301             p->ringt = p->ringt_base;
08302          }
08303 
08304          /* If we get a ring then we cannot be in
08305           * reversed polarity. So we reset to idle */
08306          ast_debug(1, "Setting IDLE polarity due "
08307             "to ring. Old polarity was %d\n",
08308             p->polarity);
08309          p->polarity = POLARITY_IDLE;
08310 
08311          /* Fall through */
08312       case SIG_EM:
08313       case SIG_EM_E1:
08314       case SIG_EMWINK:
08315       case SIG_FEATD:
08316       case SIG_FEATDMF:
08317       case SIG_FEATDMF_TA:
08318       case SIG_E911:
08319       case SIG_FGC_CAMA:
08320       case SIG_FGC_CAMAMF:
08321       case SIG_FEATB:
08322       case SIG_SF:
08323       case SIG_SFWINK:
08324       case SIG_SF_FEATD:
08325       case SIG_SF_FEATDMF:
08326       case SIG_SF_FEATB:
08327          if (ast->_state == AST_STATE_PRERING)
08328             ast_setstate(ast, AST_STATE_RING);
08329          if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
08330             ast_debug(1, "Ring detected\n");
08331             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08332             p->subs[idx].f.subclass.integer = AST_CONTROL_RING;
08333          } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
08334             ast_debug(1, "Line answered\n");
08335             if (p->confirmanswer) {
08336                p->subs[idx].f.frametype = AST_FRAME_NULL;
08337                p->subs[idx].f.subclass.integer = 0;
08338             } else {
08339                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08340                p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08341                ast_setstate(ast, AST_STATE_UP);
08342             }
08343          } else if (ast->_state != AST_STATE_RING)
08344             ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
08345          break;
08346       default:
08347          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08348       }
08349       break;
08350    case DAHDI_EVENT_RINGBEGIN:
08351       switch (p->sig) {
08352       case SIG_FXSLS:
08353       case SIG_FXSGS:
08354       case SIG_FXSKS:
08355          if (ast->_state == AST_STATE_RING) {
08356             p->ringt = p->ringt_base;
08357          }
08358          break;
08359       }
08360       break;
08361    case DAHDI_EVENT_RINGERON:
08362       break;
08363    case DAHDI_EVENT_NOALARM:
08364       switch (p->sig) {
08365 #if defined(HAVE_PRI)
08366       case SIG_PRI_LIB_HANDLE_CASES:
08367          sig_pri_chan_alarm_notify(p->sig_pvt, 1);
08368          break;
08369 #endif   /* defined(HAVE_PRI) */
08370 #if defined(HAVE_SS7)
08371       case SIG_SS7:
08372          sig_ss7_set_alarm(p->sig_pvt, 0);
08373          break;
08374 #endif   /* defined(HAVE_SS7) */
08375       default:
08376          p->inalarm = 0;
08377          break;
08378       }
08379       handle_clear_alarms(p);
08380       break;
08381    case DAHDI_EVENT_WINKFLASH:
08382       if (p->inalarm) break;
08383       if (p->radio) break;
08384       if (p->oprmode < 0) break;
08385       if (p->oprmode > 1)
08386       {
08387          struct dahdi_params par;
08388 
08389          memset(&par, 0, sizeof(par));
08390          if (ioctl(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par) != -1)
08391          {
08392             if (!par.rxisoffhook)
08393             {
08394                /* Make sure it stops ringing */
08395                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08396                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RING);
08397                save_conference(p);
08398                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08399             }
08400          }
08401          break;
08402       }
08403       /* Remember last time we got a flash-hook */
08404       p->flashtime = ast_tvnow();
08405       switch (mysig) {
08406       case SIG_FXOLS:
08407       case SIG_FXOGS:
08408       case SIG_FXOKS:
08409          ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
08410             idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
08411 
08412          /* Cancel any running CallerID spill */
08413          ast_free(p->cidspill);
08414          p->cidspill = NULL;
08415          restore_conference(p);
08416          p->callwaitcas = 0;
08417 
08418          if (idx != SUB_REAL) {
08419             ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", idx, p->channel);
08420             goto winkflashdone;
08421          }
08422 
08423          if (p->subs[SUB_CALLWAIT].owner) {
08424             /* Swap to call-wait */
08425             swap_subs(p, SUB_REAL, SUB_CALLWAIT);
08426             tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
08427             p->owner = p->subs[SUB_REAL].owner;
08428             ast_debug(1, "Making %s the new owner\n", p->owner->name);
08429             if (p->owner->_state == AST_STATE_RINGING) {
08430                ast_setstate(p->owner, AST_STATE_UP);
08431                p->subs[SUB_REAL].needanswer = 1;
08432             }
08433             p->callwaitingrepeat = 0;
08434             p->cidcwexpire = 0;
08435             p->cid_suppress_expire = 0;
08436             /* Start music on hold if appropriate */
08437             if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
08438                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
08439                   S_OR(p->mohsuggest, NULL),
08440                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08441             }
08442             p->subs[SUB_CALLWAIT].needhold = 1;
08443             if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
08444                ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
08445                   S_OR(p->mohsuggest, NULL),
08446                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08447             }
08448             p->subs[SUB_REAL].needunhold = 1;
08449          } else if (!p->subs[SUB_THREEWAY].owner) {
08450             if (!p->threewaycalling) {
08451                /* Just send a flash if no 3-way calling */
08452                p->subs[SUB_REAL].needflash = 1;
08453                goto winkflashdone;
08454             } else if (!check_for_conference(p)) {
08455                char cid_num[256];
08456                char cid_name[256];
08457 
08458                cid_num[0] = 0;
08459                cid_name[0] = 0;
08460                if (p->dahditrcallerid && p->owner) {
08461                   if (p->owner->caller.id.number.valid
08462                      && p->owner->caller.id.number.str) {
08463                      ast_copy_string(cid_num, p->owner->caller.id.number.str,
08464                         sizeof(cid_num));
08465                   }
08466                   if (p->owner->caller.id.name.valid
08467                      && p->owner->caller.id.name.str) {
08468                      ast_copy_string(cid_name, p->owner->caller.id.name.str,
08469                         sizeof(cid_name));
08470                   }
08471                }
08472                /* XXX This section needs much more error checking!!! XXX */
08473                /* Start a 3-way call if feasible */
08474                if (!((ast->pbx) ||
08475                   (ast->_state == AST_STATE_UP) ||
08476                   (ast->_state == AST_STATE_RING))) {
08477                   ast_debug(1, "Flash when call not up or ringing\n");
08478                   goto winkflashdone;
08479                }
08480                if (alloc_sub(p, SUB_THREEWAY)) {
08481                   ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
08482                   goto winkflashdone;
08483                }
08484                /* Make new channel */
08485                chan = dahdi_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, NULL);
08486                if (p->dahditrcallerid) {
08487                   if (!p->origcid_num)
08488                      p->origcid_num = ast_strdup(p->cid_num);
08489                   if (!p->origcid_name)
08490                      p->origcid_name = ast_strdup(p->cid_name);
08491                   ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
08492                   ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
08493                }
08494                /* Swap things around between the three-way and real call */
08495                swap_subs(p, SUB_THREEWAY, SUB_REAL);
08496                /* Disable echo canceller for better dialing */
08497                dahdi_disable_ec(p);
08498                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALRECALL);
08499                if (res)
08500                   ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
08501                p->owner = chan;
08502                if (!chan) {
08503                   ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
08504                } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
08505                   ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
08506                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
08507                   dahdi_enable_ec(p);
08508                   ast_hangup(chan);
08509                } else {
08510                   ast_verb(3, "Started three way call on channel %d\n", p->channel);
08511 
08512                   /* Start music on hold if appropriate */
08513                   if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
08514                      ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
08515                         S_OR(p->mohsuggest, NULL),
08516                         !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08517                   }
08518                   p->subs[SUB_THREEWAY].needhold = 1;
08519                }
08520             }
08521          } else {
08522             /* Already have a 3 way call */
08523             if (p->subs[SUB_THREEWAY].inthreeway) {
08524                /* Call is already up, drop the last person */
08525                ast_debug(1, "Got flash with three way call up, dropping last call on %d\n", p->channel);
08526                /* If the primary call isn't answered yet, use it */
08527                if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
08528                   /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
08529                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08530                   p->owner = p->subs[SUB_REAL].owner;
08531                }
08532                /* Drop the last call and stop the conference */
08533                ast_verb(3, "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
08534                p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08535                p->subs[SUB_REAL].inthreeway = 0;
08536                p->subs[SUB_THREEWAY].inthreeway = 0;
08537             } else {
08538                /* Lets see what we're up to */
08539                if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
08540                   (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
08541                   int otherindex = SUB_THREEWAY;
08542 
08543                   ast_verb(3, "Building conference call with %s and %s\n",
08544                      p->subs[SUB_THREEWAY].owner->name,
08545                      p->subs[SUB_REAL].owner->name);
08546                   /* Put them in the threeway, and flip */
08547                   p->subs[SUB_THREEWAY].inthreeway = 1;
08548                   p->subs[SUB_REAL].inthreeway = 1;
08549                   if (ast->_state == AST_STATE_UP) {
08550                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
08551                      otherindex = SUB_REAL;
08552                   }
08553                   if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
08554                      ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
08555                   p->subs[otherindex].needunhold = 1;
08556                   p->owner = p->subs[SUB_REAL].owner;
08557                } else {
08558                   ast_verb(3, "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
08559                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08560                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08561                   p->owner = p->subs[SUB_REAL].owner;
08562                   if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
08563                      ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
08564                   p->subs[SUB_REAL].needunhold = 1;
08565                   dahdi_enable_ec(p);
08566                }
08567             }
08568          }
08569 winkflashdone:
08570          update_conf(p);
08571          break;
08572       case SIG_EM:
08573       case SIG_EM_E1:
08574       case SIG_FEATD:
08575       case SIG_SF:
08576       case SIG_SFWINK:
08577       case SIG_SF_FEATD:
08578       case SIG_FXSLS:
08579       case SIG_FXSGS:
08580          if (p->dialing)
08581             ast_debug(1, "Ignoring wink on channel %d\n", p->channel);
08582          else
08583             ast_debug(1, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
08584          break;
08585       case SIG_FEATDMF_TA:
08586          switch (p->whichwink) {
08587          case 0:
08588             ast_debug(1, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->caller.ani2,
08589                S_COR(p->owner->caller.ani.number.valid,
08590                   p->owner->caller.ani.number.str, ""));
08591             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#",
08592                p->owner->caller.ani2,
08593                S_COR(p->owner->caller.ani.number.valid,
08594                   p->owner->caller.ani.number.str, ""));
08595             break;
08596          case 1:
08597             ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
08598             break;
08599          case 2:
08600             ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
08601             return NULL;
08602          }
08603          p->whichwink++;
08604          /* Fall through */
08605       case SIG_FEATDMF:
08606       case SIG_E911:
08607       case SIG_FGC_CAMAMF:
08608       case SIG_FGC_CAMA:
08609       case SIG_FEATB:
08610       case SIG_SF_FEATDMF:
08611       case SIG_SF_FEATB:
08612       case SIG_EMWINK:
08613          /* FGD MF and EMWINK *Must* wait for wink */
08614          if (!ast_strlen_zero(p->dop.dialstr)) {
08615             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08616             if (res < 0) {
08617                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08618                p->dop.dialstr[0] = '\0';
08619                return NULL;
08620             } else
08621                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08622          }
08623          p->dop.dialstr[0] = '\0';
08624          break;
08625       default:
08626          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08627       }
08628       break;
08629    case DAHDI_EVENT_HOOKCOMPLETE:
08630       if (p->inalarm) break;
08631       if ((p->radio || (p->oprmode < 0))) break;
08632       if (p->waitingfordt.tv_sec) break;
08633       switch (mysig) {
08634       case SIG_FXSLS:  /* only interesting for FXS */
08635       case SIG_FXSGS:
08636       case SIG_FXSKS:
08637       case SIG_EM:
08638       case SIG_EM_E1:
08639       case SIG_EMWINK:
08640       case SIG_FEATD:
08641       case SIG_SF:
08642       case SIG_SFWINK:
08643       case SIG_SF_FEATD:
08644          if (!ast_strlen_zero(p->dop.dialstr)) {
08645             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08646             if (res < 0) {
08647                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08648                p->dop.dialstr[0] = '\0';
08649                return NULL;
08650             } else
08651                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08652          }
08653          p->dop.dialstr[0] = '\0';
08654          p->dop.op = DAHDI_DIAL_OP_REPLACE;
08655          break;
08656       case SIG_FEATDMF:
08657       case SIG_FEATDMF_TA:
08658       case SIG_E911:
08659       case SIG_FGC_CAMA:
08660       case SIG_FGC_CAMAMF:
08661       case SIG_FEATB:
08662       case SIG_SF_FEATDMF:
08663       case SIG_SF_FEATB:
08664          ast_debug(1, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
08665          break;
08666       default:
08667          break;
08668       }
08669       break;
08670    case DAHDI_EVENT_POLARITY:
08671       /*
08672        * If we get a Polarity Switch event, check to see
08673        * if we should change the polarity state and
08674        * mark the channel as UP or if this is an indication
08675        * of remote end disconnect.
08676        */
08677       if (p->polarity == POLARITY_IDLE) {
08678          p->polarity = POLARITY_REV;
08679          if (p->answeronpolarityswitch &&
08680             ((ast->_state == AST_STATE_DIALING) ||
08681             (ast->_state == AST_STATE_RINGING))) {
08682             ast_debug(1, "Answering on polarity switch!\n");
08683             ast_setstate(p->owner, AST_STATE_UP);
08684             if (p->hanguponpolarityswitch) {
08685                p->polaritydelaytv = ast_tvnow();
08686             }
08687          } else
08688             ast_debug(1, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
08689       }
08690       /* Removed else statement from here as it was preventing hangups from ever happening*/
08691       /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
08692       if (p->hanguponpolarityswitch &&
08693          (p->polarityonanswerdelay > 0) &&
08694          (p->polarity == POLARITY_REV) &&
08695          ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
08696          /* Added log_debug information below to provide a better indication of what is going on */
08697          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) );
08698 
08699          if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
08700             ast_debug(1, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
08701             ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
08702             p->polarity = POLARITY_IDLE;
08703          } else
08704             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);
08705 
08706       } else {
08707          p->polarity = POLARITY_IDLE;
08708          ast_debug(1, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
08709       }
08710       /* Added more log_debug information below to provide a better indication of what is going on */
08711       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) );
08712       break;
08713    default:
08714       ast_debug(1, "Dunno what to do with event %d on channel %d\n", res, p->channel);
08715    }
08716    return &p->subs[idx].f;
08717 }
08718 
08719 static struct ast_frame *__dahdi_exception(struct ast_channel *ast)
08720 {
08721    int res;
08722    int idx;
08723    struct ast_frame *f;
08724    int usedindex = -1;
08725    struct dahdi_pvt *p = ast->tech_pvt;
08726 
08727    idx = dahdi_get_index(ast, p, 1);
08728 
08729    p->subs[idx].f.frametype = AST_FRAME_NULL;
08730    p->subs[idx].f.datalen = 0;
08731    p->subs[idx].f.samples = 0;
08732    p->subs[idx].f.mallocd = 0;
08733    p->subs[idx].f.offset = 0;
08734    p->subs[idx].f.subclass.integer = 0;
08735    p->subs[idx].f.delivery = ast_tv(0,0);
08736    p->subs[idx].f.src = "dahdi_exception";
08737    p->subs[idx].f.data.ptr = NULL;
08738 
08739 
08740    if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
08741       /* If nobody owns us, absorb the event appropriately, otherwise
08742          we loop indefinitely.  This occurs when, during call waiting, the
08743          other end hangs up our channel so that it no longer exists, but we
08744          have neither FLASH'd nor ONHOOK'd to signify our desire to
08745          change to the other channel. */
08746       if (p->fake_event) {
08747          res = p->fake_event;
08748          p->fake_event = 0;
08749       } else
08750          res = dahdi_get_event(p->subs[SUB_REAL].dfd);
08751       /* Switch to real if there is one and this isn't something really silly... */
08752       if ((res != DAHDI_EVENT_RINGEROFF) && (res != DAHDI_EVENT_RINGERON) &&
08753          (res != DAHDI_EVENT_HOOKCOMPLETE)) {
08754          ast_debug(1, "Restoring owner of channel %d on event %d\n", p->channel, res);
08755          p->owner = p->subs[SUB_REAL].owner;
08756          if (p->owner && ast_bridged_channel(p->owner))
08757             ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08758          p->subs[SUB_REAL].needunhold = 1;
08759       }
08760       switch (res) {
08761       case DAHDI_EVENT_ONHOOK:
08762          dahdi_disable_ec(p);
08763          if (p->owner) {
08764             ast_verb(3, "Channel %s still has call, ringing phone\n", p->owner->name);
08765             dahdi_ring_phone(p);
08766             p->callwaitingrepeat = 0;
08767             p->cidcwexpire = 0;
08768             p->cid_suppress_expire = 0;
08769          } else
08770             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08771          update_conf(p);
08772          break;
08773       case DAHDI_EVENT_RINGOFFHOOK:
08774          dahdi_enable_ec(p);
08775          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08776          if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
08777             p->subs[SUB_REAL].needanswer = 1;
08778             p->dialing = 0;
08779          }
08780          break;
08781       case DAHDI_EVENT_HOOKCOMPLETE:
08782       case DAHDI_EVENT_RINGERON:
08783       case DAHDI_EVENT_RINGEROFF:
08784          /* Do nothing */
08785          break;
08786       case DAHDI_EVENT_WINKFLASH:
08787          p->flashtime = ast_tvnow();
08788          if (p->owner) {
08789             ast_verb(3, "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
08790             if (p->owner->_state != AST_STATE_UP) {
08791                /* Answer if necessary */
08792                usedindex = dahdi_get_index(p->owner, p, 0);
08793                if (usedindex > -1) {
08794                   p->subs[usedindex].needanswer = 1;
08795                }
08796                ast_setstate(p->owner, AST_STATE_UP);
08797             }
08798             p->callwaitingrepeat = 0;
08799             p->cidcwexpire = 0;
08800             p->cid_suppress_expire = 0;
08801             if (ast_bridged_channel(p->owner))
08802                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08803             p->subs[SUB_REAL].needunhold = 1;
08804          } else
08805             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08806          update_conf(p);
08807          break;
08808       default:
08809          ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
08810       }
08811       f = &p->subs[idx].f;
08812       return f;
08813    }
08814    if (!(p->radio || (p->oprmode < 0)))
08815       ast_debug(1, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
08816    /* If it's not us, return NULL immediately */
08817    if (ast != p->owner) {
08818       ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
08819       f = &p->subs[idx].f;
08820       return f;
08821    }
08822    f = dahdi_handle_event(ast);
08823 
08824    /* tell the cdr this zap device hung up */
08825    if (f == NULL) {
08826       ast_set_hangupsource(ast, ast->name, 0);
08827    }
08828 
08829    return f;
08830 }
08831 
08832 static struct ast_frame *dahdi_exception(struct ast_channel *ast)
08833 {
08834    struct dahdi_pvt *p = ast->tech_pvt;
08835    struct ast_frame *f;
08836    ast_mutex_lock(&p->lock);
08837    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08838       struct analog_pvt *analog_p = p->sig_pvt;
08839       f = analog_exception(analog_p, ast);
08840    } else {
08841       f = __dahdi_exception(ast);
08842    }
08843    ast_mutex_unlock(&p->lock);
08844    return f;
08845 }
08846 
08847 static struct ast_frame *dahdi_read(struct ast_channel *ast)
08848 {
08849    struct dahdi_pvt *p;
08850    int res;
08851    int idx;
08852    void *readbuf;
08853    struct ast_frame *f;
08854 
08855    /*
08856     * For analog channels, we must do deadlock avoidance because
08857     * analog ports can have more than one Asterisk channel using
08858     * the same private structure.
08859     */
08860    p = ast->tech_pvt;
08861    while (ast_mutex_trylock(&p->lock)) {
08862       CHANNEL_DEADLOCK_AVOIDANCE(ast);
08863 
08864       /*
08865        * For PRI channels, we must refresh the private pointer because
08866        * the call could move to another B channel while the Asterisk
08867        * channel is unlocked.
08868        */
08869       p = ast->tech_pvt;
08870    }
08871 
08872    idx = dahdi_get_index(ast, p, 0);
08873 
08874    /* Hang up if we don't really exist */
08875    if (idx < 0)   {
08876       ast_log(LOG_WARNING, "We don't exist?\n");
08877       ast_mutex_unlock(&p->lock);
08878       return NULL;
08879    }
08880 
08881    if ((p->radio || (p->oprmode < 0)) && p->inalarm) {
08882       ast_mutex_unlock(&p->lock);
08883       return NULL;
08884    }
08885 
08886    p->subs[idx].f.frametype = AST_FRAME_NULL;
08887    p->subs[idx].f.datalen = 0;
08888    p->subs[idx].f.samples = 0;
08889    p->subs[idx].f.mallocd = 0;
08890    p->subs[idx].f.offset = 0;
08891    p->subs[idx].f.subclass.integer = 0;
08892    p->subs[idx].f.delivery = ast_tv(0,0);
08893    p->subs[idx].f.src = "dahdi_read";
08894    p->subs[idx].f.data.ptr = NULL;
08895 
08896    /* make sure it sends initial key state as first frame */
08897    if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
08898    {
08899       struct dahdi_params ps;
08900 
08901       memset(&ps, 0, sizeof(ps));
08902       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
08903          ast_mutex_unlock(&p->lock);
08904          return NULL;
08905       }
08906       p->firstradio = 1;
08907       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08908       if (ps.rxisoffhook)
08909       {
08910          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08911       }
08912       else
08913       {
08914          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08915       }
08916       ast_mutex_unlock(&p->lock);
08917       return &p->subs[idx].f;
08918    }
08919    if (p->ringt > 0) {
08920       if (!(--p->ringt)) {
08921          ast_mutex_unlock(&p->lock);
08922          return NULL;
08923       }
08924    }
08925 
08926 #ifdef HAVE_OPENR2
08927    if (p->mfcr2) {
08928       openr2_chan_process_event(p->r2chan);
08929       if (OR2_DIR_FORWARD == openr2_chan_get_direction(p->r2chan)) {
08930          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_PROGRESS }, };
08931          /* if the call is already accepted and we already delivered AST_CONTROL_RINGING
08932           * now enqueue a progress frame to bridge the media up */
08933          if (p->mfcr2_call_accepted &&
08934              !p->mfcr2_progress && 
08935              ast->_state == AST_STATE_RINGING) {
08936             ast_log(LOG_DEBUG, "Enqueuing progress frame after R2 accept in chan %d\n", p->channel);
08937             ast_queue_frame(p->owner, &f);
08938             p->mfcr2_progress = 1;
08939          }
08940       }
08941    }
08942 #endif
08943 
08944    if (p->subs[idx].needringing) {
08945       /* Send ringing frame if requested */
08946       p->subs[idx].needringing = 0;
08947       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08948       p->subs[idx].f.subclass.integer = AST_CONTROL_RINGING;
08949       ast_setstate(ast, AST_STATE_RINGING);
08950       ast_mutex_unlock(&p->lock);
08951       return &p->subs[idx].f;
08952    }
08953 
08954    if (p->subs[idx].needbusy) {
08955       /* Send busy frame if requested */
08956       p->subs[idx].needbusy = 0;
08957       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08958       p->subs[idx].f.subclass.integer = AST_CONTROL_BUSY;
08959       ast_mutex_unlock(&p->lock);
08960       return &p->subs[idx].f;
08961    }
08962 
08963    if (p->subs[idx].needcongestion) {
08964       /* Send congestion frame if requested */
08965       p->subs[idx].needcongestion = 0;
08966       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08967       p->subs[idx].f.subclass.integer = AST_CONTROL_CONGESTION;
08968       ast_mutex_unlock(&p->lock);
08969       return &p->subs[idx].f;
08970    }
08971 
08972    if (p->subs[idx].needanswer) {
08973       /* Send answer frame if requested */
08974       p->subs[idx].needanswer = 0;
08975       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08976       p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08977       ast_mutex_unlock(&p->lock);
08978       return &p->subs[idx].f;
08979    }
08980 #ifdef HAVE_OPENR2
08981    if (p->mfcr2 && openr2_chan_get_read_enabled(p->r2chan)) {
08982       /* openr2 took care of reading and handling any event
08983         (needanswer, needbusy etc), if we continue we will read()
08984         twice, lets just return a null frame. This should only
08985         happen when openr2 is dialing out */
08986       ast_mutex_unlock(&p->lock);
08987       return &ast_null_frame;
08988    }
08989 #endif
08990 
08991    if (p->subs[idx].needflash) {
08992       /* Send answer frame if requested */
08993       p->subs[idx].needflash = 0;
08994       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08995       p->subs[idx].f.subclass.integer = AST_CONTROL_FLASH;
08996       ast_mutex_unlock(&p->lock);
08997       return &p->subs[idx].f;
08998    }
08999 
09000    if (p->subs[idx].needhold) {
09001       /* Send answer frame if requested */
09002       p->subs[idx].needhold = 0;
09003       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09004       p->subs[idx].f.subclass.integer = AST_CONTROL_HOLD;
09005       ast_mutex_unlock(&p->lock);
09006       ast_debug(1, "Sending hold on '%s'\n", ast->name);
09007       return &p->subs[idx].f;
09008    }
09009 
09010    if (p->subs[idx].needunhold) {
09011       /* Send answer frame if requested */
09012       p->subs[idx].needunhold = 0;
09013       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09014       p->subs[idx].f.subclass.integer = AST_CONTROL_UNHOLD;
09015       ast_mutex_unlock(&p->lock);
09016       ast_debug(1, "Sending unhold on '%s'\n", ast->name);
09017       return &p->subs[idx].f;
09018    }
09019 
09020    /*
09021     * If we have a fake_event, fake an exception to handle it only
09022     * if this channel owns the private.
09023     */
09024    if (p->fake_event && p->owner == ast) {
09025       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09026          struct analog_pvt *analog_p = p->sig_pvt;
09027 
09028          f = analog_exception(analog_p, ast);
09029       } else {
09030          f = __dahdi_exception(ast);
09031       }
09032       ast_mutex_unlock(&p->lock);
09033       return f;
09034    }
09035 
09036    if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
09037       if (!p->subs[idx].linear) {
09038          p->subs[idx].linear = 1;
09039          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09040          if (res)
09041             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, idx);
09042       }
09043    } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
09044       (ast->rawreadformat == AST_FORMAT_ALAW)) {
09045       if (p->subs[idx].linear) {
09046          p->subs[idx].linear = 0;
09047          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09048          if (res)
09049             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, idx);
09050       }
09051    } else {
09052       ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
09053       ast_mutex_unlock(&p->lock);
09054       return NULL;
09055    }
09056    readbuf = ((unsigned char *)p->subs[idx].buffer) + AST_FRIENDLY_OFFSET;
09057    CHECK_BLOCKING(ast);
09058    res = read(p->subs[idx].dfd, readbuf, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
09059    ast_clear_flag(ast, AST_FLAG_BLOCKING);
09060    /* Check for hangup */
09061    if (res < 0) {
09062       f = NULL;
09063       if (res == -1) {
09064          if (errno == EAGAIN) {
09065             /* Return "NULL" frame if there is nobody there */
09066             ast_mutex_unlock(&p->lock);
09067             return &p->subs[idx].f;
09068          } else if (errno == ELAST) {
09069             if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09070                struct analog_pvt *analog_p = p->sig_pvt;
09071                f = analog_exception(analog_p, ast);
09072             } else {
09073                f = __dahdi_exception(ast);
09074             }
09075          } else
09076             ast_log(LOG_WARNING, "dahdi_rec: %s\n", strerror(errno));
09077       }
09078       ast_mutex_unlock(&p->lock);
09079       return f;
09080    }
09081    if (res != (p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE)) {
09082       ast_debug(1, "Short read (%d/%d), must be an event...\n", res, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
09083       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09084          struct analog_pvt *analog_p = p->sig_pvt;
09085          f = analog_exception(analog_p, ast);
09086       } else {
09087          f = __dahdi_exception(ast);
09088       }
09089       ast_mutex_unlock(&p->lock);
09090       return f;
09091    }
09092    if (p->tdd) { /* if in TDD mode, see if we receive that */
09093       int c;
09094 
09095       c = tdd_feed(p->tdd,readbuf,READ_SIZE);
09096       if (c < 0) {
09097          ast_debug(1,"tdd_feed failed\n");
09098          ast_mutex_unlock(&p->lock);
09099          return NULL;
09100       }
09101       if (c) { /* if a char to return */
09102          p->subs[idx].f.subclass.integer = 0;
09103          p->subs[idx].f.frametype = AST_FRAME_TEXT;
09104          p->subs[idx].f.mallocd = 0;
09105          p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
09106          p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET;
09107          p->subs[idx].f.datalen = 1;
09108          *((char *) p->subs[idx].f.data.ptr) = c;
09109          ast_mutex_unlock(&p->lock);
09110          return &p->subs[idx].f;
09111       }
09112    }
09113    if (idx == SUB_REAL) {
09114       /* Ensure the CW timers decrement only on a single subchannel */
09115       if (p->cidcwexpire) {
09116          if (!--p->cidcwexpire) {
09117             /* Expired CID/CW */
09118             ast_verb(3, "CPE does not support Call Waiting Caller*ID.\n");
09119             restore_conference(p);
09120          }
09121       }
09122       if (p->cid_suppress_expire) {
09123          --p->cid_suppress_expire;
09124       }
09125       if (p->callwaitingrepeat) {
09126          if (!--p->callwaitingrepeat) {
09127             /* Expired, Repeat callwaiting tone */
09128             ++p->callwaitrings;
09129             dahdi_callwait(ast);
09130          }
09131       }
09132    }
09133    if (p->subs[idx].linear) {
09134       p->subs[idx].f.datalen = READ_SIZE * 2;
09135    } else
09136       p->subs[idx].f.datalen = READ_SIZE;
09137 
09138    /* Handle CallerID Transmission */
09139    if ((p->owner == ast) && p->cidspill) {
09140       send_callerid(p);
09141    }
09142 
09143    p->subs[idx].f.frametype = AST_FRAME_VOICE;
09144    p->subs[idx].f.subclass.codec = ast->rawreadformat;
09145    p->subs[idx].f.samples = READ_SIZE;
09146    p->subs[idx].f.mallocd = 0;
09147    p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
09148    p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[idx].buffer[0]);
09149 #if 0
09150    ast_debug(1, "Read %d of voice on %s\n", p->subs[idx].f.datalen, ast->name);
09151 #endif
09152    if (p->dialing ||  p->radio || /* Transmitting something */
09153       (idx && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
09154       ((idx == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
09155       ) {
09156       /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
09157          don't send anything */
09158       p->subs[idx].f.frametype = AST_FRAME_NULL;
09159       p->subs[idx].f.subclass.integer = 0;
09160       p->subs[idx].f.samples = 0;
09161       p->subs[idx].f.mallocd = 0;
09162       p->subs[idx].f.offset = 0;
09163       p->subs[idx].f.data.ptr = NULL;
09164       p->subs[idx].f.datalen= 0;
09165    }
09166    if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress || p->waitingfordt.tv_sec) && !idx) {
09167       /* Perform busy detection etc on the dahdi line */
09168       int mute;
09169 
09170       f = ast_dsp_process(ast, p->dsp, &p->subs[idx].f);
09171 
09172       /* Check if DSP code thinks we should be muting this frame and mute the conference if so */
09173       mute = ast_dsp_was_muted(p->dsp);
09174       if (p->muting != mute) {
09175          p->muting = mute;
09176          dahdi_confmute(p, mute);
09177       }
09178 
09179       if (f) {
09180          if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_BUSY)) {
09181             if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
09182                /* Treat this as a "hangup" instead of a "busy" on the assumption that
09183                   a busy */
09184                f = NULL;
09185             }
09186          } else if (f->frametype == AST_FRAME_DTMF_BEGIN
09187             || f->frametype == AST_FRAME_DTMF_END) {
09188 #ifdef HAVE_PRI
09189             if (dahdi_sig_pri_lib_handles(p->sig)
09190                && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
09191                && p->pri
09192                && ((!p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING))
09193                   || (p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)))) {
09194                /* Don't accept in-band DTMF when in overlap dial mode */
09195                ast_debug(1, "Absorbing inband %s DTMF digit: 0x%02X '%c' on %s\n",
09196                   f->frametype == AST_FRAME_DTMF_BEGIN ? "begin" : "end",
09197                   f->subclass.integer, f->subclass.integer, ast->name);
09198 
09199                f->frametype = AST_FRAME_NULL;
09200                f->subclass.integer = 0;
09201             }
09202 #endif
09203             /* DSP clears us of being pulse */
09204             p->pulsedial = 0;
09205          } else if (p->waitingfordt.tv_sec) {
09206             if (ast_tvdiff_ms(ast_tvnow(), p->waitingfordt) >= p->waitfordialtone ) {
09207                p->waitingfordt.tv_sec = 0;
09208                ast_log(LOG_WARNING, "Never saw dialtone on channel %d\n", p->channel);
09209                f=NULL;
09210             } else if (f->frametype == AST_FRAME_VOICE) {
09211                f->frametype = AST_FRAME_NULL;
09212                f->subclass.integer = 0;
09213                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) {
09214                   p->waitingfordt.tv_sec = 0;
09215                   p->dsp_features &= ~DSP_FEATURE_WAITDIALTONE;
09216                   ast_dsp_set_features(p->dsp, p->dsp_features);
09217                   ast_log(LOG_DEBUG, "Got 10 samples of dialtone!\n");
09218                   if (!ast_strlen_zero(p->dop.dialstr)) { /* Dial deferred digits */
09219                      res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
09220                      if (res < 0) {
09221                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
09222                         p->dop.dialstr[0] = '\0';
09223                         ast_mutex_unlock(&p->lock);
09224                         return NULL;
09225                      } else {
09226                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
09227                         p->dialing = 1;
09228                         p->dop.dialstr[0] = '\0';
09229                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
09230                         ast_setstate(ast, AST_STATE_DIALING);
09231                      }
09232                   }
09233                }
09234             }
09235          }
09236       }
09237    } else
09238       f = &p->subs[idx].f;
09239 
09240    if (f) {
09241       switch (f->frametype) {
09242       case AST_FRAME_DTMF_BEGIN:
09243       case AST_FRAME_DTMF_END:
09244          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09245             analog_handle_dtmf(p->sig_pvt, ast, idx, &f);
09246          } else {
09247             dahdi_handle_dtmf(ast, idx, &f);
09248          }
09249          break;
09250       case AST_FRAME_VOICE:
09251          if (p->cidspill || p->cid_suppress_expire) {
09252             /* We are/were sending a caller id spill.  Suppress any echo. */
09253             p->subs[idx].f.frametype = AST_FRAME_NULL;
09254             p->subs[idx].f.subclass.integer = 0;
09255             p->subs[idx].f.samples = 0;
09256             p->subs[idx].f.mallocd = 0;
09257             p->subs[idx].f.offset = 0;
09258             p->subs[idx].f.data.ptr = NULL;
09259             p->subs[idx].f.datalen= 0;
09260          }
09261          break;
09262       default:
09263          break;
09264       }
09265    }
09266 
09267    ast_mutex_unlock(&p->lock);
09268    return f;
09269 }
09270 
09271 static int my_dahdi_write(struct dahdi_pvt *p, unsigned char *buf, int len, int idx, int linear)
09272 {
09273    int sent=0;
09274    int size;
09275    int res;
09276    int fd;
09277    fd = p->subs[idx].dfd;
09278    while (len) {
09279       size = len;
09280       if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
09281          size = (linear ? READ_SIZE * 2 : READ_SIZE);
09282       res = write(fd, buf, size);
09283       if (res != size) {
09284          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
09285          return sent;
09286       }
09287       len -= size;
09288       buf += size;
09289    }
09290    return sent;
09291 }
09292 
09293 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame)
09294 {
09295    struct dahdi_pvt *p = ast->tech_pvt;
09296    int res;
09297    int idx;
09298    idx = dahdi_get_index(ast, p, 0);
09299    if (idx < 0) {
09300       ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
09301       return -1;
09302    }
09303 
09304    /* Write a frame of (presumably voice) data */
09305    if (frame->frametype != AST_FRAME_VOICE) {
09306       if (frame->frametype != AST_FRAME_IMAGE)
09307          ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
09308       return 0;
09309    }
09310    if ((frame->subclass.codec != AST_FORMAT_SLINEAR) &&
09311       (frame->subclass.codec != AST_FORMAT_ULAW) &&
09312       (frame->subclass.codec != AST_FORMAT_ALAW)) {
09313       ast_log(LOG_WARNING, "Cannot handle frames in %s format\n", ast_getformatname(frame->subclass.codec));
09314       return -1;
09315    }
09316    if (p->dialing) {
09317       ast_debug(1, "Dropping frame since I'm still dialing on %s...\n",ast->name);
09318       return 0;
09319    }
09320    if (!p->owner) {
09321       ast_debug(1, "Dropping frame since there is no active owner on %s...\n",ast->name);
09322       return 0;
09323    }
09324    if (p->cidspill) {
09325       ast_debug(1, "Dropping frame since I've still got a callerid spill on %s...\n",
09326          ast->name);
09327       return 0;
09328    }
09329    /* Return if it's not valid data */
09330    if (!frame->data.ptr || !frame->datalen)
09331       return 0;
09332 
09333    if (frame->subclass.codec == AST_FORMAT_SLINEAR) {
09334       if (!p->subs[idx].linear) {
09335          p->subs[idx].linear = 1;
09336          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09337          if (res)
09338             ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
09339       }
09340       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 1);
09341    } else {
09342       /* x-law already */
09343       if (p->subs[idx].linear) {
09344          p->subs[idx].linear = 0;
09345          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09346          if (res)
09347             ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
09348       }
09349       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 0);
09350    }
09351    if (res < 0) {
09352       ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
09353       return -1;
09354    }
09355    return 0;
09356 }
09357 
09358 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
09359 {
09360    struct dahdi_pvt *p = chan->tech_pvt;
09361    int res=-1;
09362    int idx;
09363    int func = DAHDI_FLASH;
09364 
09365    ast_mutex_lock(&p->lock);
09366    ast_debug(1, "Requested indication %d on channel %s\n", condition, chan->name);
09367    switch (p->sig) {
09368 #if defined(HAVE_PRI)
09369    case SIG_PRI_LIB_HANDLE_CASES:
09370       res = sig_pri_indicate(p->sig_pvt, chan, condition, data, datalen);
09371       ast_mutex_unlock(&p->lock);
09372       return res;
09373 #endif   /* defined(HAVE_PRI) */
09374 #if defined(HAVE_SS7)
09375    case SIG_SS7:
09376       res = sig_ss7_indicate(p->sig_pvt, chan, condition, data, datalen);
09377       ast_mutex_unlock(&p->lock);
09378       return res;
09379 #endif   /* defined(HAVE_SS7) */
09380    default:
09381       break;
09382    }
09383 #ifdef HAVE_OPENR2
09384    if (p->mfcr2 && !p->mfcr2_call_accepted) {
09385       ast_mutex_unlock(&p->lock);
09386       /* if this is an R2 call and the call is not yet accepted, we don't want the
09387          tone indications to mess up with the MF tones */
09388       return 0;
09389    }
09390 #endif
09391    idx = dahdi_get_index(chan, p, 0);
09392    if (idx == SUB_REAL) {
09393       switch (condition) {
09394       case AST_CONTROL_BUSY:
09395          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_BUSY);
09396          break;
09397       case AST_CONTROL_RINGING:
09398          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_RINGTONE);
09399 
09400          if (chan->_state != AST_STATE_UP) {
09401             if ((chan->_state != AST_STATE_RING) ||
09402                ((p->sig != SIG_FXSKS) &&
09403              (p->sig != SIG_FXSLS) &&
09404              (p->sig != SIG_FXSGS)))
09405             ast_setstate(chan, AST_STATE_RINGING);
09406          }
09407          break;
09408       case AST_CONTROL_INCOMPLETE:
09409          ast_debug(1, "Received AST_CONTROL_INCOMPLETE on %s\n", chan->name);
09410          /* act as a progress or proceeding, allowing the caller to enter additional numbers */
09411          res = 0;
09412          break;
09413       case AST_CONTROL_PROCEEDING:
09414          ast_debug(1, "Received AST_CONTROL_PROCEEDING on %s\n", chan->name);
09415          /* don't continue in ast_indicate */
09416          res = 0;
09417          break;
09418       case AST_CONTROL_PROGRESS:
09419          ast_debug(1, "Received AST_CONTROL_PROGRESS on %s\n", chan->name);
09420          /* don't continue in ast_indicate */
09421          res = 0;
09422          break;
09423       case AST_CONTROL_CONGESTION:
09424          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
09425          switch (chan->hangupcause) {
09426          case AST_CAUSE_USER_BUSY:
09427          case AST_CAUSE_NORMAL_CLEARING:
09428          case 0:/* Cause has not been set. */
09429             /* Supply a more appropriate cause. */
09430             chan->hangupcause = AST_CAUSE_CONGESTION;
09431             break;
09432          default:
09433             break;
09434          }
09435          break;
09436       case AST_CONTROL_HOLD:
09437          ast_moh_start(chan, data, p->mohinterpret);
09438          break;
09439       case AST_CONTROL_UNHOLD:
09440          ast_moh_stop(chan);
09441          break;
09442       case AST_CONTROL_RADIO_KEY:
09443          if (p->radio)
09444             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
09445          res = 0;
09446          break;
09447       case AST_CONTROL_RADIO_UNKEY:
09448          if (p->radio)
09449             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_RINGOFF);
09450          res = 0;
09451          break;
09452       case AST_CONTROL_FLASH:
09453          /* flash hookswitch */
09454          if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
09455             /* Clear out the dial buffer */
09456             p->dop.dialstr[0] = '\0';
09457             if ((ioctl(p->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
09458                ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
09459                   chan->name, strerror(errno));
09460             } else
09461                res = 0;
09462          } else
09463             res = 0;
09464          break;
09465       case AST_CONTROL_SRCUPDATE:
09466          res = 0;
09467          break;
09468       case -1:
09469          res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09470          break;
09471       }
09472    } else {
09473       res = 0;
09474    }
09475    ast_mutex_unlock(&p->lock);
09476    return res;
09477 }
09478 
09479 #if defined(HAVE_PRI)
09480 static struct ast_str *create_channel_name(struct dahdi_pvt *i, int is_outgoing, char *address)
09481 #else
09482 static struct ast_str *create_channel_name(struct dahdi_pvt *i)
09483 #endif   /* defined(HAVE_PRI) */
09484 {
09485    struct ast_str *chan_name;
09486    int x, y;
09487 
09488    /* Create the new channel name tail. */
09489    if (!(chan_name = ast_str_create(32))) {
09490       return NULL;
09491    }
09492    if (i->channel == CHAN_PSEUDO) {
09493       ast_str_set(&chan_name, 0, "pseudo-%ld", ast_random());
09494 #if defined(HAVE_PRI)
09495    } else if (i->pri) {
09496       ast_mutex_lock(&i->pri->lock);
09497       y = ++i->pri->new_chan_seq;
09498       if (is_outgoing) {
09499          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, address, y);
09500          address[0] = '\0';
09501       } else if (ast_strlen_zero(i->cid_subaddr)) {
09502          /* Put in caller-id number only since there is no subaddress. */
09503          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, i->cid_num, y);
09504       } else {
09505          /* Put in caller-id number and subaddress. */
09506          ast_str_set(&chan_name, 0, "i%d/%s:%s-%x", i->pri->span, i->cid_num,
09507             i->cid_subaddr, y);
09508       }
09509       ast_mutex_unlock(&i->pri->lock);
09510 #endif   /* defined(HAVE_PRI) */
09511    } else {
09512       y = 1;
09513       do {
09514          ast_str_set(&chan_name, 0, "%d-%d", i->channel, y);
09515          for (x = 0; x < 3; ++x) {
09516             if (i->subs[x].owner && !strcasecmp(ast_str_buffer(chan_name),
09517                i->subs[x].owner->name + 6)) {
09518                break;
09519             }
09520          }
09521          ++y;
09522       } while (x < 3);
09523    }
09524    return chan_name;
09525 }
09526 
09527 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid)
09528 {
09529    struct ast_channel *tmp;
09530    format_t deflaw;
09531    int x;
09532    int features;
09533    struct ast_str *chan_name;
09534    struct ast_variable *v;
09535    char *dashptr;
09536    char device_name[AST_CHANNEL_NAME];
09537 
09538    if (i->subs[idx].owner) {
09539       ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[idx]);
09540       return NULL;
09541    }
09542 
09543 #if defined(HAVE_PRI)
09544    /*
09545     * The dnid has been stuffed with the called-number[:subaddress]
09546     * by dahdi_request() for outgoing calls.
09547     */
09548    chan_name = create_channel_name(i, i->outgoing, i->dnid);
09549 #else
09550    chan_name = create_channel_name(i);
09551 #endif   /* defined(HAVE_PRI) */
09552    if (!chan_name) {
09553       return NULL;
09554    }
09555 
09556    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));
09557    ast_free(chan_name);
09558    if (!tmp)
09559       return NULL;
09560    tmp->tech = &dahdi_tech;
09561 #if defined(HAVE_PRI)
09562    if (i->pri) {
09563       ast_cc_copy_config_params(i->cc_params, i->pri->cc_params);
09564    }
09565 #endif   /* defined(HAVE_PRI) */
09566    ast_channel_cc_params_init(tmp, i->cc_params);
09567    if (law) {
09568       i->law = law;
09569       if (law == DAHDI_LAW_ALAW) {
09570          deflaw = AST_FORMAT_ALAW;
09571       } else {
09572          deflaw = AST_FORMAT_ULAW;
09573       }
09574    } else {
09575       switch (i->sig) {
09576       case SIG_PRI_LIB_HANDLE_CASES:
09577          /* Make sure companding law is known. */
09578          i->law = (i->law_default == DAHDI_LAW_ALAW)
09579             ? DAHDI_LAW_ALAW : DAHDI_LAW_MULAW;
09580          break;
09581       default:
09582          i->law = i->law_default;
09583          break;
09584       }
09585       if (i->law_default == DAHDI_LAW_ALAW) {
09586          deflaw = AST_FORMAT_ALAW;
09587       } else {
09588          deflaw = AST_FORMAT_ULAW;
09589       }
09590    }
09591    ast_channel_set_fd(tmp, 0, i->subs[idx].dfd);
09592    tmp->nativeformats = deflaw;
09593    /* Start out assuming ulaw since it's smaller :) */
09594    tmp->rawreadformat = deflaw;
09595    tmp->readformat = deflaw;
09596    tmp->rawwriteformat = deflaw;
09597    tmp->writeformat = deflaw;
09598    i->subs[idx].linear = 0;
09599    dahdi_setlinear(i->subs[idx].dfd, i->subs[idx].linear);
09600    features = 0;
09601    if (idx == SUB_REAL) {
09602       if (i->busydetect && CANBUSYDETECT(i))
09603          features |= DSP_FEATURE_BUSY_DETECT;
09604       if ((i->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(i))
09605          features |= DSP_FEATURE_CALL_PROGRESS;
09606       if ((i->waitfordialtone) && CANPROGRESSDETECT(i))
09607          features |= DSP_FEATURE_WAITDIALTONE;
09608       if ((!i->outgoing && (i->callprogress & CALLPROGRESS_FAX_INCOMING)) ||
09609          (i->outgoing && (i->callprogress & CALLPROGRESS_FAX_OUTGOING))) {
09610          features |= DSP_FEATURE_FAX_DETECT;
09611       }
09612       x = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
09613       if (ioctl(i->subs[idx].dfd, DAHDI_TONEDETECT, &x)) {
09614          i->hardwaredtmf = 0;
09615          features |= DSP_FEATURE_DIGIT_DETECT;
09616       } else if (NEED_MFDETECT(i)) {
09617          i->hardwaredtmf = 1;
09618          features |= DSP_FEATURE_DIGIT_DETECT;
09619       }
09620    }
09621    if (features) {
09622       if (i->dsp) {
09623          ast_debug(1, "Already have a dsp on %s?\n", tmp->name);
09624       } else {
09625          if (i->channel != CHAN_PSEUDO)
09626             i->dsp = ast_dsp_new();
09627          else
09628             i->dsp = NULL;
09629          if (i->dsp) {
09630             i->dsp_features = features;
09631 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09632             /* We cannot do progress detection until receive PROGRESS message */
09633             if (i->outgoing && (dahdi_sig_pri_lib_handles(i->sig) || (i->sig == SIG_SS7))) {
09634                /* Remember requested DSP features, don't treat
09635                   talking as ANSWER */
09636                i->dsp_features = features & ~DSP_PROGRESS_TALK;
09637                features = 0;
09638             }
09639 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09640             ast_dsp_set_features(i->dsp, features);
09641             ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
09642             if (!ast_strlen_zero(progzone))
09643                ast_dsp_set_call_progress_zone(i->dsp, progzone);
09644             if (i->busydetect && CANBUSYDETECT(i)) {
09645                ast_dsp_set_busy_count(i->dsp, i->busycount);
09646                ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
09647             }
09648          }
09649       }
09650    }
09651 
09652    if (state == AST_STATE_RING)
09653       tmp->rings = 1;
09654    tmp->tech_pvt = i;
09655    if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
09656       /* Only FXO signalled stuff can be picked up */
09657       tmp->callgroup = i->callgroup;
09658       tmp->pickupgroup = i->pickupgroup;
09659    }
09660    if (!ast_strlen_zero(i->parkinglot))
09661       ast_string_field_set(tmp, parkinglot, i->parkinglot);
09662    if (!ast_strlen_zero(i->language))
09663       ast_string_field_set(tmp, language, i->language);
09664    if (!i->owner)
09665       i->owner = tmp;
09666    if (!ast_strlen_zero(i->accountcode))
09667       ast_string_field_set(tmp, accountcode, i->accountcode);
09668    if (i->amaflags)
09669       tmp->amaflags = i->amaflags;
09670    i->subs[idx].owner = tmp;
09671    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
09672    if (!analog_lib_handles(i->sig, i->radio, i->oprmode)) {
09673       ast_string_field_set(tmp, call_forward, i->call_forward);
09674    }
09675    /* If we've been told "no ADSI" then enforce it */
09676    if (!i->adsi)
09677       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
09678    if (!ast_strlen_zero(i->exten))
09679       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
09680    if (!ast_strlen_zero(i->rdnis)) {
09681       tmp->redirecting.from.number.valid = 1;
09682       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
09683    }
09684    if (!ast_strlen_zero(i->dnid)) {
09685       tmp->dialed.number.str = ast_strdup(i->dnid);
09686    }
09687 
09688    /* Don't use ast_set_callerid() here because it will
09689     * generate a needless NewCallerID event */
09690 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09691    if (!ast_strlen_zero(i->cid_ani)) {
09692       tmp->caller.ani.number.valid = 1;
09693       tmp->caller.ani.number.str = ast_strdup(i->cid_ani);
09694    } else if (!ast_strlen_zero(i->cid_num)) {
09695       tmp->caller.ani.number.valid = 1;
09696       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09697    }
09698 #else
09699    if (!ast_strlen_zero(i->cid_num)) {
09700       tmp->caller.ani.number.valid = 1;
09701       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09702    }
09703 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09704    tmp->caller.id.name.presentation = i->callingpres;
09705    tmp->caller.id.number.presentation = i->callingpres;
09706    tmp->caller.id.number.plan = i->cid_ton;
09707    tmp->caller.ani2 = i->cid_ani2;
09708    tmp->caller.id.tag = ast_strdup(i->cid_tag);
09709    /* clear the fake event in case we posted one before we had ast_channel */
09710    i->fake_event = 0;
09711    /* Assure there is no confmute on this channel */
09712    dahdi_confmute(i, 0);
09713    i->muting = 0;
09714    /* Configure the new channel jb */
09715    ast_jb_configure(tmp, &global_jbconf);
09716 
09717    /* Set initial device state */
09718    ast_copy_string(device_name, tmp->name, sizeof(device_name));
09719    dashptr = strrchr(device_name, '-');
09720    if (dashptr) {
09721       *dashptr = '\0';
09722    }
09723    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, device_name);
09724 
09725    for (v = i->vars ; v ; v = v->next)
09726       pbx_builtin_setvar_helper(tmp, v->name, v->value);
09727 
09728    ast_module_ref(ast_module_info->self);
09729 
09730    dahdi_ami_channel_event(i, tmp);
09731    if (startpbx) {
09732 #ifdef HAVE_OPENR2
09733       if (i->mfcr2call) {
09734          pbx_builtin_setvar_helper(tmp, "MFCR2_CATEGORY", openr2_proto_get_category_string(i->mfcr2_recvd_category));
09735       }
09736 #endif
09737       if (ast_pbx_start(tmp)) {
09738          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
09739          ast_hangup(tmp);
09740          return NULL;
09741       }
09742    }
09743    return tmp;
09744 }
09745 
09746 
09747 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
09748 {
09749    char c;
09750 
09751    *str = 0; /* start with empty output buffer */
09752    for (;;)
09753    {
09754       /* Wait for the first digit (up to specified ms). */
09755       c = ast_waitfordigit(chan, ms);
09756       /* if timeout, hangup or error, return as such */
09757       if (c < 1)
09758          return c;
09759       *str++ = c;
09760       *str = 0;
09761       if (strchr(term, c))
09762          return 1;
09763    }
09764 }
09765 
09766 static int dahdi_wink(struct dahdi_pvt *p, int idx)
09767 {
09768    int j;
09769    dahdi_set_hook(p->subs[idx].dfd, DAHDI_WINK);
09770    for (;;)
09771    {
09772       /* set bits of interest */
09773       j = DAHDI_IOMUX_SIGEVENT;
09774       /* wait for some happening */
09775       if (ioctl(p->subs[idx].dfd,DAHDI_IOMUX,&j) == -1) return(-1);
09776       /* exit loop if we have it */
09777       if (j & DAHDI_IOMUX_SIGEVENT) break;
09778    }
09779    /* get the event info */
09780    if (ioctl(p->subs[idx].dfd,DAHDI_GETEVENT,&j) == -1) return(-1);
09781    return 0;
09782 }
09783 
09784 /*! \brief enable or disable the chan_dahdi Do-Not-Disturb mode for a DAHDI channel
09785  * \param dahdichan "Physical" DAHDI channel (e.g: DAHDI/5)
09786  * \param flag on 1 to enable, 0 to disable, -1 return dnd value
09787  *
09788  * chan_dahdi has a DND (Do Not Disturb) mode for each dahdichan (physical
09789  * DAHDI channel). Use this to enable or disable it.
09790  *
09791  * \bug the use of the word "channel" for those dahdichans is really confusing.
09792  */
09793 static int dahdi_dnd(struct dahdi_pvt *dahdichan, int flag)
09794 {
09795    if (analog_lib_handles(dahdichan->sig, dahdichan->radio, dahdichan->oprmode)) {
09796       return analog_dnd(dahdichan->sig_pvt, flag);
09797    }
09798 
09799    if (flag == -1) {
09800       return dahdichan->dnd;
09801    }
09802 
09803    /* Do not disturb */
09804    dahdichan->dnd = flag;
09805    ast_verb(3, "%s DND on channel %d\n",
09806          flag? "Enabled" : "Disabled",
09807          dahdichan->channel);
09808    manager_event(EVENT_FLAG_SYSTEM, "DNDState",
09809          "Channel: DAHDI/%d\r\n"
09810          "Status: %s\r\n", dahdichan->channel,
09811          flag? "enabled" : "disabled");
09812 
09813    return 0;
09814 }
09815 
09816 static int canmatch_featurecode(const char *exten)
09817 {
09818    int extlen = strlen(exten);
09819    const char *pickup_ext;
09820    if (!extlen) {
09821       return 1;
09822    }
09823    pickup_ext = ast_pickup_ext();
09824    if (extlen < strlen(pickup_ext) && !strncmp(pickup_ext, exten, extlen)) {
09825       return 1;
09826    }
09827    /* hardcoded features are *60, *67, *69, *70, *72, *73, *78, *79, *82, *0 */
09828    if (exten[0] == '*' && extlen < 3) {
09829       if (extlen == 1) {
09830          return 1;
09831       }
09832       /* "*0" should be processed before it gets here */
09833       switch (exten[1]) {
09834       case '6':
09835       case '7':
09836       case '8':
09837          return 1;
09838       }
09839    }
09840    return 0;
09841 }
09842 
09843 static void *analog_ss_thread(void *data)
09844 {
09845    struct ast_channel *chan = data;
09846    struct dahdi_pvt *p = chan->tech_pvt;
09847    char exten[AST_MAX_EXTENSION] = "";
09848    char exten2[AST_MAX_EXTENSION] = "";
09849    unsigned char buf[256];
09850    char dtmfcid[300];
09851    char dtmfbuf[300];
09852    struct callerid_state *cs = NULL;
09853    char *name = NULL, *number = NULL;
09854    int distMatches;
09855    int curRingData[3];
09856    int receivedRingT;
09857    int counter1;
09858    int counter;
09859    int samples = 0;
09860    struct ast_smdi_md_message *smdi_msg = NULL;
09861    int flags = 0;
09862    int i;
09863    int timeout;
09864    int getforward = 0;
09865    char *s1, *s2;
09866    int len = 0;
09867    int res;
09868    int idx;
09869 
09870    ast_mutex_lock(&ss_thread_lock);
09871    ss_thread_count++;
09872    ast_mutex_unlock(&ss_thread_lock);
09873    /* in the bizarre case where the channel has become a zombie before we
09874       even get started here, abort safely
09875    */
09876    if (!p) {
09877       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
09878       ast_hangup(chan);
09879       goto quit;
09880    }
09881    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
09882    idx = dahdi_get_index(chan, p, 1);
09883    if (idx < 0) {
09884       ast_log(LOG_WARNING, "Huh?\n");
09885       ast_hangup(chan);
09886       goto quit;
09887    }
09888    if (p->dsp)
09889       ast_dsp_digitreset(p->dsp);
09890    switch (p->sig) {
09891    case SIG_FEATD:
09892    case SIG_FEATDMF:
09893    case SIG_FEATDMF_TA:
09894    case SIG_E911:
09895    case SIG_FGC_CAMAMF:
09896    case SIG_FEATB:
09897    case SIG_EMWINK:
09898    case SIG_SF_FEATD:
09899    case SIG_SF_FEATDMF:
09900    case SIG_SF_FEATB:
09901    case SIG_SFWINK:
09902       if (dahdi_wink(p, idx))
09903          goto quit;
09904       /* Fall through */
09905    case SIG_EM:
09906    case SIG_EM_E1:
09907    case SIG_SF:
09908    case SIG_FGC_CAMA:
09909       res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09910       if (p->dsp)
09911          ast_dsp_digitreset(p->dsp);
09912       /* set digit mode appropriately */
09913       if (p->dsp) {
09914          if (NEED_MFDETECT(p))
09915             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
09916          else
09917             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
09918       }
09919       memset(dtmfbuf, 0, sizeof(dtmfbuf));
09920       /* Wait for the first digit only if immediate=no */
09921       if (!p->immediate)
09922          /* Wait for the first digit (up to 5 seconds). */
09923          res = ast_waitfordigit(chan, 5000);
09924       else
09925          res = 0;
09926       if (res > 0) {
09927          /* save first char */
09928          dtmfbuf[0] = res;
09929          switch (p->sig) {
09930          case SIG_FEATD:
09931          case SIG_SF_FEATD:
09932             res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
09933             if (res > 0)
09934                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
09935             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09936             break;
09937          case SIG_FEATDMF_TA:
09938             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09939             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09940             if (dahdi_wink(p, idx)) goto quit;
09941             dtmfbuf[0] = 0;
09942             /* Wait for the first digit (up to 5 seconds). */
09943             res = ast_waitfordigit(chan, 5000);
09944             if (res <= 0) break;
09945             dtmfbuf[0] = res;
09946             /* fall through intentionally */
09947          case SIG_FEATDMF:
09948          case SIG_E911:
09949          case SIG_FGC_CAMAMF:
09950          case SIG_SF_FEATDMF:
09951             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09952             /* if international caca, do it again to get real ANO */
09953             if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
09954             {
09955                if (dahdi_wink(p, idx)) goto quit;
09956                dtmfbuf[0] = 0;
09957                /* Wait for the first digit (up to 5 seconds). */
09958                res = ast_waitfordigit(chan, 5000);
09959                if (res <= 0) break;
09960                dtmfbuf[0] = res;
09961                res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09962             }
09963             if (res > 0) {
09964                /* if E911, take off hook */
09965                if (p->sig == SIG_E911)
09966                   dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
09967                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
09968             }
09969             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09970             break;
09971          case SIG_FEATB:
09972          case SIG_SF_FEATB:
09973             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09974             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09975             break;
09976          case SIG_EMWINK:
09977             /* if we received a '*', we are actually receiving Feature Group D
09978                dial syntax, so use that mode; otherwise, fall through to normal
09979                mode
09980             */
09981             if (res == '*') {
09982                res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
09983                if (res > 0)
09984                   res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
09985                if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09986                break;
09987             }
09988          default:
09989             /* If we got the first digit, get the rest */
09990             len = 1;
09991             dtmfbuf[len] = '\0';
09992             while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
09993                if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
09994                   timeout = matchdigittimeout;
09995                } else {
09996                   timeout = gendigittimeout;
09997                }
09998                res = ast_waitfordigit(chan, timeout);
09999                if (res < 0) {
10000                   ast_debug(1, "waitfordigit returned < 0...\n");
10001                   ast_hangup(chan);
10002                   goto quit;
10003                } else if (res) {
10004                   dtmfbuf[len++] = res;
10005                   dtmfbuf[len] = '\0';
10006                } else {
10007                   break;
10008                }
10009             }
10010             break;
10011          }
10012       }
10013       if (res == -1) {
10014          ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
10015          ast_hangup(chan);
10016          goto quit;
10017       } else if (res < 0) {
10018          ast_debug(1, "Got hung up before digits finished\n");
10019          ast_hangup(chan);
10020          goto quit;
10021       }
10022 
10023       if (p->sig == SIG_FGC_CAMA) {
10024          char anibuf[100];
10025 
10026          if (ast_safe_sleep(chan,1000) == -1) {
10027             ast_hangup(chan);
10028             goto quit;
10029          }
10030          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10031          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
10032          res = my_getsigstr(chan, anibuf, "#", 10000);
10033          if ((res > 0) && (strlen(anibuf) > 2)) {
10034             if (anibuf[strlen(anibuf) - 1] == '#')
10035                anibuf[strlen(anibuf) - 1] = 0;
10036             ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
10037          }
10038          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10039       }
10040 
10041       ast_copy_string(exten, dtmfbuf, sizeof(exten));
10042       if (ast_strlen_zero(exten))
10043          ast_copy_string(exten, "s", sizeof(exten));
10044       if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
10045          /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
10046          if (exten[0] == '*') {
10047             char *stringp=NULL;
10048             ast_copy_string(exten2, exten, sizeof(exten2));
10049             /* Parse out extension and callerid */
10050             stringp=exten2 +1;
10051             s1 = strsep(&stringp, "*");
10052             s2 = strsep(&stringp, "*");
10053             if (s2) {
10054                if (!ast_strlen_zero(p->cid_num))
10055                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10056                else
10057                   ast_set_callerid(chan, s1, NULL, s1);
10058                ast_copy_string(exten, s2, sizeof(exten));
10059             } else
10060                ast_copy_string(exten, s1, sizeof(exten));
10061          } else if (p->sig == SIG_FEATD)
10062             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10063       }
10064       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
10065          if (exten[0] == '*') {
10066             char *stringp=NULL;
10067             ast_copy_string(exten2, exten, sizeof(exten2));
10068             /* Parse out extension and callerid */
10069             stringp=exten2 +1;
10070             s1 = strsep(&stringp, "#");
10071             s2 = strsep(&stringp, "#");
10072             if (s2) {
10073                if (!ast_strlen_zero(p->cid_num))
10074                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10075                else
10076                   if (*(s1 + 2))
10077                      ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
10078                ast_copy_string(exten, s2 + 1, sizeof(exten));
10079             } else
10080                ast_copy_string(exten, s1 + 2, sizeof(exten));
10081          } else
10082             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10083       }
10084       if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
10085          if (exten[0] == '*') {
10086             char *stringp=NULL;
10087             ast_copy_string(exten2, exten, sizeof(exten2));
10088             /* Parse out extension and callerid */
10089             stringp=exten2 +1;
10090             s1 = strsep(&stringp, "#");
10091             s2 = strsep(&stringp, "#");
10092             if (s2 && (*(s2 + 1) == '0')) {
10093                if (*(s2 + 2))
10094                   ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
10095             }
10096             if (s1)  ast_copy_string(exten, s1, sizeof(exten));
10097             else ast_copy_string(exten, "911", sizeof(exten));
10098          } else
10099             ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10100       }
10101       if (p->sig == SIG_FEATB) {
10102          if (exten[0] == '*') {
10103             char *stringp=NULL;
10104             ast_copy_string(exten2, exten, sizeof(exten2));
10105             /* Parse out extension and callerid */
10106             stringp=exten2 +1;
10107             s1 = strsep(&stringp, "#");
10108             ast_copy_string(exten, exten2 + 1, sizeof(exten));
10109          } else
10110             ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10111       }
10112       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
10113          dahdi_wink(p, idx);
10114          /* some switches require a minimum guard time between
10115             the last FGD wink and something that answers
10116             immediately. This ensures it */
10117          if (ast_safe_sleep(chan, 100)) {
10118             ast_hangup(chan);
10119             goto quit;
10120          }
10121       }
10122       dahdi_enable_ec(p);
10123       if (NEED_MFDETECT(p)) {
10124          if (p->dsp) {
10125             if (!p->hardwaredtmf)
10126                ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10127             else {
10128                ast_dsp_free(p->dsp);
10129                p->dsp = NULL;
10130             }
10131          }
10132       }
10133 
10134       if (ast_exists_extension(chan, chan->context, exten, 1,
10135          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
10136          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
10137          if (p->dsp) ast_dsp_digitreset(p->dsp);
10138          res = ast_pbx_run(chan);
10139          if (res) {
10140             ast_log(LOG_WARNING, "PBX exited non-zero\n");
10141             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10142          }
10143          goto quit;
10144       } else {
10145          ast_verb(2, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
10146          sleep(2);
10147          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_INFO);
10148          if (res < 0)
10149             ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
10150          else
10151             sleep(1);
10152          res = ast_streamfile(chan, "ss-noservice", chan->language);
10153          if (res >= 0)
10154             ast_waitstream(chan, "");
10155          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10156          ast_hangup(chan);
10157          goto quit;
10158       }
10159       break;
10160    case SIG_FXOLS:
10161    case SIG_FXOGS:
10162    case SIG_FXOKS:
10163       /* Read the first digit */
10164       timeout = firstdigittimeout;
10165       /* If starting a threeway call, never timeout on the first digit so someone
10166          can use flash-hook as a "hold" feature */
10167       if (p->subs[SUB_THREEWAY].owner)
10168          timeout = 999999;
10169       while (len < AST_MAX_EXTENSION-1) {
10170          /* Read digit unless it's supposed to be immediate, in which case the
10171             only answer is 's' */
10172          if (p->immediate)
10173             res = 's';
10174          else
10175             res = ast_waitfordigit(chan, timeout);
10176          timeout = 0;
10177          if (res < 0) {
10178             ast_debug(1, "waitfordigit returned < 0...\n");
10179             res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10180             ast_hangup(chan);
10181             goto quit;
10182          } else if (res) {
10183             ast_debug(1,"waitfordigit returned '%c' (%d), timeout = %d\n", res, res, timeout);
10184             exten[len++]=res;
10185             exten[len] = '\0';
10186          }
10187          if (!ast_ignore_pattern(chan->context, exten))
10188             tone_zone_play_tone(p->subs[idx].dfd, -1);
10189          else
10190             tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
10191          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && !ast_parking_ext_valid(exten, chan, chan->context)) {
10192             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
10193                if (getforward) {
10194                   /* Record this as the forwarding extension */
10195                   ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
10196                   ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
10197                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10198                   if (res)
10199                      break;
10200                   usleep(500000);
10201                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10202                   sleep(1);
10203                   memset(exten, 0, sizeof(exten));
10204                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
10205                   len = 0;
10206                   getforward = 0;
10207                } else {
10208                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10209                   ast_copy_string(chan->exten, exten, sizeof(chan->exten));
10210                   if (!ast_strlen_zero(p->cid_num)) {
10211                      if (!p->hidecallerid)
10212                         ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10213                      else
10214                         ast_set_callerid(chan, NULL, NULL, p->cid_num);
10215                   }
10216                   if (!ast_strlen_zero(p->cid_name)) {
10217                      if (!p->hidecallerid)
10218                         ast_set_callerid(chan, NULL, p->cid_name, NULL);
10219                   }
10220                   ast_setstate(chan, AST_STATE_RING);
10221                   dahdi_enable_ec(p);
10222                   res = ast_pbx_run(chan);
10223                   if (res) {
10224                      ast_log(LOG_WARNING, "PBX exited non-zero\n");
10225                      res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10226                   }
10227                   goto quit;
10228                }
10229             } else {
10230                /* It's a match, but they just typed a digit, and there is an ambiguous match,
10231                   so just set the timeout to matchdigittimeout and wait some more */
10232                timeout = matchdigittimeout;
10233             }
10234          } else if (res == 0) {
10235             ast_debug(1, "not enough digits (and no ambiguous match)...\n");
10236             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10237             dahdi_wait_event(p->subs[idx].dfd);
10238             ast_hangup(chan);
10239             goto quit;
10240          } else if (p->callwaiting && !strcmp(exten, "*70")) {
10241             ast_verb(3, "Disabling call waiting on %s\n", chan->name);
10242             /* Disable call waiting if enabled */
10243             p->callwaiting = 0;
10244             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10245             if (res) {
10246                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10247                   chan->name, strerror(errno));
10248             }
10249             len = 0;
10250             ioctl(p->subs[idx].dfd,DAHDI_CONFDIAG,&len);
10251             memset(exten, 0, sizeof(exten));
10252             timeout = firstdigittimeout;
10253 
10254          } else if (!strcmp(exten,ast_pickup_ext())) {
10255             /* Scan all channels and see if there are any
10256              * ringing channels that have call groups
10257              * that equal this channels pickup group
10258              */
10259             if (idx == SUB_REAL) {
10260                /* Switch us from Third call to Call Wait */
10261                if (p->subs[SUB_THREEWAY].owner) {
10262                   /* If you make a threeway call and the *8# a call, it should actually
10263                      look like a callwait */
10264                   alloc_sub(p, SUB_CALLWAIT);
10265                   swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
10266                   unalloc_sub(p, SUB_THREEWAY);
10267                }
10268                dahdi_enable_ec(p);
10269                if (ast_pickup_call(chan)) {
10270                   ast_debug(1, "No call pickup possible...\n");
10271                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10272                   dahdi_wait_event(p->subs[idx].dfd);
10273                }
10274                ast_hangup(chan);
10275                goto quit;
10276             } else {
10277                ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
10278                ast_hangup(chan);
10279                goto quit;
10280             }
10281 
10282          } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
10283             ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
10284             /* Disable Caller*ID if enabled */
10285             p->hidecallerid = 1;
10286             ast_party_number_free(&chan->caller.id.number);
10287             ast_party_number_init(&chan->caller.id.number);
10288             ast_party_name_free(&chan->caller.id.name);
10289             ast_party_name_init(&chan->caller.id.name);
10290             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10291             if (res) {
10292                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10293                   chan->name, strerror(errno));
10294             }
10295             len = 0;
10296             memset(exten, 0, sizeof(exten));
10297             timeout = firstdigittimeout;
10298          } else if (p->callreturn && !strcmp(exten, "*69")) {
10299             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10300             break;
10301          } else if (!strcmp(exten, "*78")) {
10302             dahdi_dnd(p, 1);
10303             /* Do not disturb */
10304             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10305             getforward = 0;
10306             memset(exten, 0, sizeof(exten));
10307             len = 0;
10308          } else if (!strcmp(exten, "*79")) {
10309             dahdi_dnd(p, 0);
10310             /* Do not disturb */
10311             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10312             getforward = 0;
10313             memset(exten, 0, sizeof(exten));
10314             len = 0;
10315          } else if (p->cancallforward && !strcmp(exten, "*72")) {
10316             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10317             getforward = 1;
10318             memset(exten, 0, sizeof(exten));
10319             len = 0;
10320          } else if (p->cancallforward && !strcmp(exten, "*73")) {
10321             ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
10322             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10323             memset(p->call_forward, 0, sizeof(p->call_forward));
10324             getforward = 0;
10325             memset(exten, 0, sizeof(exten));
10326             len = 0;
10327          } else if ((p->transfer || p->canpark) && ast_parking_ext_valid(exten, chan, chan->context) &&
10328                   p->subs[SUB_THREEWAY].owner &&
10329                   ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
10330             /* This is a three way call, the main call being a real channel,
10331                and we're parking the first call. */
10332             ast_masq_park_call_exten(ast_bridged_channel(p->subs[SUB_THREEWAY].owner),
10333                chan, exten, chan->context, 0, NULL);
10334             ast_verb(3, "Parking call to '%s'\n", chan->name);
10335             break;
10336          } else if (p->hidecallerid && !strcmp(exten, "*82")) {
10337             ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
10338             /* Enable Caller*ID if enabled */
10339             p->hidecallerid = 0;
10340             ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
10341             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10342             if (res) {
10343                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10344                   chan->name, strerror(errno));
10345             }
10346             len = 0;
10347             memset(exten, 0, sizeof(exten));
10348             timeout = firstdigittimeout;
10349          } else if (!strcmp(exten, "*0")) {
10350             struct ast_channel *nbridge =
10351                p->subs[SUB_THREEWAY].owner;
10352             struct dahdi_pvt *pbridge = NULL;
10353             /* set up the private struct of the bridged one, if any */
10354             if (nbridge && ast_bridged_channel(nbridge))
10355                pbridge = ast_bridged_channel(nbridge)->tech_pvt;
10356             if (nbridge && pbridge &&
10357                (nbridge->tech == &dahdi_tech) &&
10358                (ast_bridged_channel(nbridge)->tech == &dahdi_tech) &&
10359                ISTRUNK(pbridge)) {
10360                int func = DAHDI_FLASH;
10361                /* Clear out the dial buffer */
10362                p->dop.dialstr[0] = '\0';
10363                /* flash hookswitch */
10364                if ((ioctl(pbridge->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
10365                   ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
10366                      nbridge->name, strerror(errno));
10367                }
10368                swap_subs(p, SUB_REAL, SUB_THREEWAY);
10369                unalloc_sub(p, SUB_THREEWAY);
10370                p->owner = p->subs[SUB_REAL].owner;
10371                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
10372                   ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
10373                ast_hangup(chan);
10374                goto quit;
10375             } else {
10376                tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10377                dahdi_wait_event(p->subs[idx].dfd);
10378                tone_zone_play_tone(p->subs[idx].dfd, -1);
10379                swap_subs(p, SUB_REAL, SUB_THREEWAY);
10380                unalloc_sub(p, SUB_THREEWAY);
10381                p->owner = p->subs[SUB_REAL].owner;
10382                ast_hangup(chan);
10383                goto quit;
10384             }
10385          } else if (!ast_canmatch_extension(chan, chan->context, exten, 1,
10386             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
10387             && !canmatch_featurecode(exten)) {
10388             ast_debug(1, "Can't match %s from '%s' in context %s\n", exten,
10389                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<Unknown Caller>"),
10390                chan->context);
10391             break;
10392          }
10393          if (!timeout)
10394             timeout = gendigittimeout;
10395          if (len && !ast_ignore_pattern(chan->context, exten))
10396             tone_zone_play_tone(p->subs[idx].dfd, -1);
10397       }
10398       break;
10399    case SIG_FXSLS:
10400    case SIG_FXSGS:
10401    case SIG_FXSKS:
10402       /* check for SMDI messages */
10403       if (p->use_smdi && p->smdi_iface) {
10404          smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
10405 
10406          if (smdi_msg != NULL) {
10407             ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
10408 
10409             if (smdi_msg->type == 'B')
10410                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
10411             else if (smdi_msg->type == 'N')
10412                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
10413 
10414             ast_debug(1, "Received SMDI message on %s\n", chan->name);
10415          } else {
10416             ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
10417          }
10418       }
10419 
10420       if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
10421          number = smdi_msg->calling_st;
10422 
10423       /* If we want caller id, we're in a prering state due to a polarity reversal
10424        * and we're set to use a polarity reversal to trigger the start of caller id,
10425        * grab the caller id and wait for ringing to start... */
10426       } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING &&
10427                    (p->cid_start == CID_START_POLARITY || p->cid_start == CID_START_POLARITY_IN || p->cid_start == CID_START_DTMF_NOALERT))) {
10428          /* If set to use DTMF CID signalling, listen for DTMF */
10429          if (p->cid_signalling == CID_SIG_DTMF) {
10430             int k = 0;
10431             cs = NULL;
10432             ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
10433             dahdi_setlinear(p->subs[idx].dfd, 0);
10434             /*
10435              * We are the only party interested in the Rx stream since
10436              * we have not answered yet.  We don't need or even want DTMF
10437              * emulation.  The DTMF digits can come so fast that emulation
10438              * can drop some of them.
10439              */
10440             ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
10441             res = 4000;/* This is a typical OFF time between rings. */
10442             for (;;) {
10443                struct ast_frame *f;
10444                res = ast_waitfor(chan, res);
10445                if (res <= 0) {
10446                   /*
10447                    * We do not need to restore the dahdi_setlinear()
10448                    * or AST_FLAG_END_DTMF_ONLY flag settings since we
10449                    * are hanging up the channel.
10450                    */
10451                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10452                      "Exiting simple switch\n");
10453                   ast_hangup(chan);
10454                   goto quit;
10455                }
10456                f = ast_read(chan);
10457                if (!f)
10458                   break;
10459                if (f->frametype == AST_FRAME_DTMF) {
10460                   if (k < ARRAY_LEN(dtmfbuf) - 1) {
10461                      dtmfbuf[k++] = f->subclass.integer;
10462                   }
10463                   ast_debug(1, "CID got digit '%c'\n", f->subclass.integer);
10464                   res = 4000;/* This is a typical OFF time between rings. */
10465                }
10466                ast_frfree(f);
10467                if (chan->_state == AST_STATE_RING ||
10468                   chan->_state == AST_STATE_RINGING)
10469                   break; /* Got ring */
10470             }
10471             ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
10472             dtmfbuf[k] = '\0';
10473             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10474             /* Got cid and ring. */
10475             ast_debug(1, "CID got string '%s'\n", dtmfbuf);
10476             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10477             ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
10478             /* If first byte is NULL, we have no cid */
10479             if (!ast_strlen_zero(dtmfcid))
10480                number = dtmfcid;
10481             else
10482                number = NULL;
10483          /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10484          } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
10485             cs = callerid_new(p->cid_signalling);
10486             if (cs) {
10487                samples = 0;
10488 #if 1
10489                bump_gains(p);
10490 #endif
10491                /* Take out of linear mode for Caller*ID processing */
10492                dahdi_setlinear(p->subs[idx].dfd, 0);
10493 
10494                /* First we wait and listen for the Caller*ID */
10495                for (;;) {
10496                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10497                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10498                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10499                      callerid_free(cs);
10500                      ast_hangup(chan);
10501                      goto quit;
10502                   }
10503                   if (i & DAHDI_IOMUX_SIGEVENT) {
10504                      res = dahdi_get_event(p->subs[idx].dfd);
10505                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10506                      if (res == DAHDI_EVENT_NOALARM) {
10507                         p->inalarm = 0;
10508                      }
10509 
10510                      if (p->cid_signalling == CID_SIG_V23_JP) {
10511                         if (res == DAHDI_EVENT_RINGBEGIN) {
10512                            res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10513                            usleep(1);
10514                         }
10515                      } else {
10516                         res = 0;
10517                         break;
10518                      }
10519                   } else if (i & DAHDI_IOMUX_READ) {
10520                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10521                      if (res < 0) {
10522                         if (errno != ELAST) {
10523                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10524                            callerid_free(cs);
10525                            ast_hangup(chan);
10526                            goto quit;
10527                         }
10528                         break;
10529                      }
10530                      samples += res;
10531 
10532                      if (p->cid_signalling == CID_SIG_V23_JP) {
10533                         res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
10534                      } else {
10535                         res = callerid_feed(cs, buf, res, AST_LAW(p));
10536                      }
10537                      if (res < 0) {
10538                         /*
10539                          * The previous diagnostic message output likely
10540                          * explains why it failed.
10541                          */
10542                         ast_log(LOG_WARNING,
10543                            "Failed to decode CallerID on channel '%s'\n",
10544                            chan->name);
10545                         break;
10546                      } else if (res)
10547                         break;
10548                      else if (samples > (8000 * 10))
10549                         break;
10550                   }
10551                }
10552                if (res == 1) {
10553                   callerid_get(cs, &name, &number, &flags);
10554                   ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10555                }
10556 
10557                if (p->cid_signalling == CID_SIG_V23_JP) {
10558                   res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
10559                   usleep(1);
10560                }
10561 
10562                /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
10563                res = 4000;/* This is a typical OFF time between rings. */
10564                for (;;) {
10565                   struct ast_frame *f;
10566                   res = ast_waitfor(chan, res);
10567                   if (res <= 0) {
10568                      ast_log(LOG_WARNING, "CID timed out waiting for ring. "
10569                         "Exiting simple switch\n");
10570                      ast_hangup(chan);
10571                      goto quit;
10572                   }
10573                   if (!(f = ast_read(chan))) {
10574                      ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
10575                      ast_hangup(chan);
10576                      goto quit;
10577                   }
10578                   ast_frfree(f);
10579                   if (chan->_state == AST_STATE_RING ||
10580                      chan->_state == AST_STATE_RINGING)
10581                      break; /* Got ring */
10582                }
10583 
10584                /* We must have a ring by now, so, if configured, lets try to listen for
10585                 * distinctive ringing */
10586                if (p->usedistinctiveringdetection) {
10587                   len = 0;
10588                   distMatches = 0;
10589                   /* Clear the current ring data array so we don't have old data in it. */
10590                   for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10591                      curRingData[receivedRingT] = 0;
10592                   receivedRingT = 0;
10593                   counter = 0;
10594                   counter1 = 0;
10595                   /* Check to see if context is what it should be, if not set to be. */
10596                   if (strcmp(p->context,p->defcontext) != 0) {
10597                      ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10598                      ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10599                   }
10600 
10601                   for (;;) {
10602                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10603                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10604                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10605                         callerid_free(cs);
10606                         ast_hangup(chan);
10607                         goto quit;
10608                      }
10609                      if (i & DAHDI_IOMUX_SIGEVENT) {
10610                         res = dahdi_get_event(p->subs[idx].dfd);
10611                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10612                         if (res == DAHDI_EVENT_NOALARM) {
10613                            p->inalarm = 0;
10614                         }
10615                         res = 0;
10616                         /* Let us detect distinctive ring */
10617 
10618                         curRingData[receivedRingT] = p->ringt;
10619 
10620                         if (p->ringt < p->ringt_base/2)
10621                            break;
10622                         /* Increment the ringT counter so we can match it against
10623                            values in chan_dahdi.conf for distinctive ring */
10624                         if (++receivedRingT == ARRAY_LEN(curRingData))
10625                            break;
10626                      } else if (i & DAHDI_IOMUX_READ) {
10627                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10628                         if (res < 0) {
10629                            if (errno != ELAST) {
10630                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10631                               callerid_free(cs);
10632                               ast_hangup(chan);
10633                               goto quit;
10634                            }
10635                            break;
10636                         }
10637                         if (p->ringt > 0) {
10638                            if (!(--p->ringt)) {
10639                               res = -1;
10640                               break;
10641                            }
10642                         }
10643                      }
10644                   }
10645                      /* this only shows up if you have n of the dring patterns filled in */
10646                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10647                   for (counter = 0; counter < 3; counter++) {
10648                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10649                      channel */
10650                      distMatches = 0;
10651                      for (counter1 = 0; counter1 < 3; counter1++) {
10652                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10653                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10654                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10655                            curRingData[counter1]);
10656                            distMatches++;
10657                         } else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10658                               curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10659                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10660                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10661                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10662                            distMatches++;
10663                         }
10664                      }
10665 
10666                      if (distMatches == 3) {
10667                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10668                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10669                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10670                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10671                         break;
10672                      }
10673                   }
10674                }
10675                /* Restore linear mode (if appropriate) for Caller*ID processing */
10676                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10677 #if 1
10678                restore_gains(p);
10679 #endif
10680             } else
10681                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10682          } else {
10683             ast_log(LOG_WARNING, "Channel %s in prering "
10684                "state, but I have nothing to do. "
10685                "Terminating simple switch, should be "
10686                "restarted by the actual ring.\n",
10687                chan->name);
10688             ast_hangup(chan);
10689             goto quit;
10690          }
10691       } else if (p->use_callerid && p->cid_start == CID_START_RING) {
10692          if (p->cid_signalling == CID_SIG_DTMF) {
10693             int k = 0;
10694             cs = NULL;
10695             dahdi_setlinear(p->subs[idx].dfd, 0);
10696             res = 2000;
10697             for (;;) {
10698                struct ast_frame *f;
10699                res = ast_waitfor(chan, res);
10700                if (res <= 0) {
10701                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10702                      "Exiting simple switch\n");
10703                   ast_hangup(chan);
10704                   goto quit;
10705                }
10706                f = ast_read(chan);
10707                if (!f) {
10708                   /* Hangup received waiting for DTMFCID. Exiting simple switch. */
10709                   ast_hangup(chan);
10710                   goto quit;
10711                }
10712                if (f->frametype == AST_FRAME_DTMF) {
10713                   dtmfbuf[k++] = f->subclass.integer;
10714                   ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass.integer);
10715                   res = 2000;
10716                }
10717                ast_frfree(f);
10718 
10719                if (p->ringt_base == p->ringt)
10720                   break;
10721             }
10722             dtmfbuf[k] = '\0';
10723             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10724             /* Got cid and ring. */
10725             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10726             ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
10727                dtmfcid, flags);
10728             /* If first byte is NULL, we have no cid */
10729             if (!ast_strlen_zero(dtmfcid))
10730                number = dtmfcid;
10731             else
10732                number = NULL;
10733             /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10734          } else {
10735             /* FSK Bell202 callerID */
10736             cs = callerid_new(p->cid_signalling);
10737             if (cs) {
10738 #if 1
10739                bump_gains(p);
10740 #endif
10741                samples = 0;
10742                len = 0;
10743                distMatches = 0;
10744                /* Clear the current ring data array so we don't have old data in it. */
10745                for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10746                   curRingData[receivedRingT] = 0;
10747                receivedRingT = 0;
10748                counter = 0;
10749                counter1 = 0;
10750                /* Check to see if context is what it should be, if not set to be. */
10751                if (strcmp(p->context,p->defcontext) != 0) {
10752                   ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10753                   ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10754                }
10755 
10756                /* Take out of linear mode for Caller*ID processing */
10757                dahdi_setlinear(p->subs[idx].dfd, 0);
10758                for (;;) {
10759                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10760                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10761                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10762                      callerid_free(cs);
10763                      ast_hangup(chan);
10764                      goto quit;
10765                   }
10766                   if (i & DAHDI_IOMUX_SIGEVENT) {
10767                      res = dahdi_get_event(p->subs[idx].dfd);
10768                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10769                      if (res == DAHDI_EVENT_NOALARM) {
10770                         p->inalarm = 0;
10771                      }
10772                      /* If we get a PR event, they hung up while processing calerid */
10773                      if ( res == DAHDI_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
10774                         ast_log(LOG_DEBUG, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
10775                         p->polarity = POLARITY_IDLE;
10776                         callerid_free(cs);
10777                         ast_hangup(chan);
10778                         goto quit;
10779                      }
10780                      res = 0;
10781                      /* Let us detect callerid when the telco uses distinctive ring */
10782 
10783                      curRingData[receivedRingT] = p->ringt;
10784 
10785                      if (p->ringt < p->ringt_base/2)
10786                         break;
10787                      /* Increment the ringT counter so we can match it against
10788                         values in chan_dahdi.conf for distinctive ring */
10789                      if (++receivedRingT == ARRAY_LEN(curRingData))
10790                         break;
10791                   } else if (i & DAHDI_IOMUX_READ) {
10792                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10793                      if (res < 0) {
10794                         if (errno != ELAST) {
10795                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10796                            callerid_free(cs);
10797                            ast_hangup(chan);
10798                            goto quit;
10799                         }
10800                         break;
10801                      }
10802                      if (p->ringt > 0) {
10803                         if (!(--p->ringt)) {
10804                            res = -1;
10805                            break;
10806                         }
10807                      }
10808                      samples += res;
10809                      res = callerid_feed(cs, buf, res, AST_LAW(p));
10810                      if (res < 0) {
10811                         /*
10812                          * The previous diagnostic message output likely
10813                          * explains why it failed.
10814                          */
10815                         ast_log(LOG_WARNING,
10816                            "Failed to decode CallerID on channel '%s'\n",
10817                            chan->name);
10818                         break;
10819                      } else if (res)
10820                         break;
10821                      else if (samples > (8000 * 10))
10822                         break;
10823                   }
10824                }
10825                if (res == 1) {
10826                   callerid_get(cs, &name, &number, &flags);
10827                   ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10828                }
10829                if (distinctiveringaftercid == 1) {
10830                   /* Clear the current ring data array so we don't have old data in it. */
10831                   for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
10832                      curRingData[receivedRingT] = 0;
10833                   }
10834                   receivedRingT = 0;
10835                   ast_verb(3, "Detecting post-CID distinctive ring\n");
10836                   for (;;) {
10837                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10838                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10839                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10840                         callerid_free(cs);
10841                         ast_hangup(chan);
10842                         goto quit;
10843                      }
10844                      if (i & DAHDI_IOMUX_SIGEVENT) {
10845                         res = dahdi_get_event(p->subs[idx].dfd);
10846                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10847                         if (res == DAHDI_EVENT_NOALARM) {
10848                            p->inalarm = 0;
10849                         }
10850                         res = 0;
10851                         /* Let us detect callerid when the telco uses distinctive ring */
10852 
10853                         curRingData[receivedRingT] = p->ringt;
10854 
10855                         if (p->ringt < p->ringt_base/2)
10856                            break;
10857                         /* Increment the ringT counter so we can match it against
10858                            values in chan_dahdi.conf for distinctive ring */
10859                         if (++receivedRingT == ARRAY_LEN(curRingData))
10860                            break;
10861                      } else if (i & DAHDI_IOMUX_READ) {
10862                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10863                         if (res < 0) {
10864                            if (errno != ELAST) {
10865                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10866                               callerid_free(cs);
10867                               ast_hangup(chan);
10868                               goto quit;
10869                            }
10870                            break;
10871                         }
10872                         if (p->ringt > 0) {
10873                            if (!(--p->ringt)) {
10874                               res = -1;
10875                               break;
10876                            }
10877                         }
10878                      }
10879                   }
10880                }
10881                if (p->usedistinctiveringdetection) {
10882                   /* this only shows up if you have n of the dring patterns filled in */
10883                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10884 
10885                   for (counter = 0; counter < 3; counter++) {
10886                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10887                      channel */
10888                      /* this only shows up if you have n of the dring patterns filled in */
10889                      ast_verb(3, "Checking %d,%d,%d\n",
10890                            p->drings.ringnum[counter].ring[0],
10891                            p->drings.ringnum[counter].ring[1],
10892                            p->drings.ringnum[counter].ring[2]);
10893                      distMatches = 0;
10894                      for (counter1 = 0; counter1 < 3; counter1++) {
10895                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10896                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10897                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10898                            curRingData[counter1]);
10899                            distMatches++;
10900                         }
10901                         else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10902                            curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10903                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10904                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10905                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10906                            distMatches++;
10907                         }
10908                      }
10909                      if (distMatches == 3) {
10910                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10911                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10912                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10913                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10914                         break;
10915                      }
10916                   }
10917                }
10918                /* Restore linear mode (if appropriate) for Caller*ID processing */
10919                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10920 #if 1
10921                restore_gains(p);
10922 #endif
10923                if (res < 0) {
10924                   ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
10925                }
10926             } else
10927                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10928          }
10929       } else
10930          cs = NULL;
10931 
10932       if (number)
10933          ast_shrink_phone_number(number);
10934       ast_set_callerid(chan, number, name, number);
10935 
10936       if (smdi_msg)
10937          ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
10938 
10939       if (cs)
10940          callerid_free(cs);
10941 
10942       my_handle_notify_message(chan, p, flags, -1);
10943 
10944       ast_setstate(chan, AST_STATE_RING);
10945       chan->rings = 1;
10946       p->ringt = p->ringt_base;
10947       res = ast_pbx_run(chan);
10948       if (res) {
10949          ast_hangup(chan);
10950          ast_log(LOG_WARNING, "PBX exited non-zero\n");
10951       }
10952       goto quit;
10953    default:
10954       ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
10955       res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10956       if (res < 0)
10957             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
10958    }
10959    res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10960    if (res < 0)
10961          ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
10962    ast_hangup(chan);
10963 quit:
10964    ast_mutex_lock(&ss_thread_lock);
10965    ss_thread_count--;
10966    ast_cond_signal(&ss_thread_complete);
10967    ast_mutex_unlock(&ss_thread_lock);
10968    return NULL;
10969 }
10970 
10971 struct mwi_thread_data {
10972    struct dahdi_pvt *pvt;
10973    unsigned char buf[READ_SIZE];
10974    size_t len;
10975 };
10976 
10977 static int calc_energy(const unsigned char *buf, int len, format_t law)
10978 {
10979    int x;
10980    int sum = 0;
10981 
10982    if (!len)
10983       return 0;
10984 
10985    for (x = 0; x < len; x++)
10986       sum += abs(law == AST_FORMAT_ULAW ? AST_MULAW(buf[x]) : AST_ALAW(buf[x]));
10987 
10988    return sum / len;
10989 }
10990 
10991 static void *mwi_thread(void *data)
10992 {
10993    struct mwi_thread_data *mtd = data;
10994    struct callerid_state *cs;
10995    pthread_t threadid;
10996    int samples = 0;
10997    char *name, *number;
10998    int flags;
10999    int i, res;
11000    unsigned int spill_done = 0;
11001    int spill_result = -1;
11002 
11003    if (!(cs = callerid_new(mtd->pvt->cid_signalling))) {
11004       mtd->pvt->mwimonitoractive = 0;
11005 
11006       return NULL;
11007    }
11008 
11009    callerid_feed(cs, mtd->buf, mtd->len, AST_LAW(mtd->pvt));
11010 
11011    bump_gains(mtd->pvt);
11012 
11013    for (;;) {
11014       i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
11015       if ((res = ioctl(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_IOMUX, &i))) {
11016          ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
11017          goto quit;
11018       }
11019 
11020       if (i & DAHDI_IOMUX_SIGEVENT) {
11021          struct ast_channel *chan;
11022 
11023          /* If we get an event, screen out events that we do not act on.
11024           * Otherwise, cancel and go to the simple switch to let it deal with it.
11025           */
11026          res = dahdi_get_event(mtd->pvt->subs[SUB_REAL].dfd);
11027 
11028          switch (res) {
11029          case DAHDI_EVENT_NEONMWI_ACTIVE:
11030          case DAHDI_EVENT_NEONMWI_INACTIVE:
11031          case DAHDI_EVENT_NONE:
11032          case DAHDI_EVENT_BITSCHANGED:
11033             break;
11034          case DAHDI_EVENT_NOALARM:
11035             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11036                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
11037 
11038                analog_p->inalarm = 0;
11039             }
11040             mtd->pvt->inalarm = 0;
11041             handle_clear_alarms(mtd->pvt);
11042             break;
11043          case DAHDI_EVENT_ALARM:
11044             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11045                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
11046 
11047                analog_p->inalarm = 1;
11048             }
11049             mtd->pvt->inalarm = 1;
11050             res = get_alarms(mtd->pvt);
11051             handle_alarms(mtd->pvt, res);
11052             break; /* What to do on channel alarm ???? -- fall thru intentionally?? */
11053          default:
11054             ast_log(LOG_NOTICE, "Got event %d (%s)...  Passing along to analog_ss_thread\n", res, event2str(res));
11055             callerid_free(cs);
11056 
11057             restore_gains(mtd->pvt);
11058             mtd->pvt->ringt = mtd->pvt->ringt_base;
11059 
11060             if ((chan = dahdi_new(mtd->pvt, AST_STATE_RING, 0, SUB_REAL, 0, NULL))) {
11061                int result;
11062                if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11063                   result = analog_ss_thread_start(mtd->pvt->sig_pvt, chan);
11064                } else {
11065                   result = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11066                }
11067                if (result) {
11068                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", mtd->pvt->channel);
11069                   res = tone_zone_play_tone(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11070                   if (res < 0)
11071                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", mtd->pvt->channel);
11072                   ast_hangup(chan);
11073                   goto quit;
11074                }
11075                goto quit_no_clean;
11076 
11077             } else {
11078                ast_log(LOG_WARNING, "Could not create channel to handle call\n");
11079             }
11080          }
11081       } else if (i & DAHDI_IOMUX_READ) {
11082          if ((res = read(mtd->pvt->subs[SUB_REAL].dfd, mtd->buf, sizeof(mtd->buf))) < 0) {
11083             if (errno != ELAST) {
11084                ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
11085                goto quit;
11086             }
11087             break;
11088          }
11089          samples += res;
11090          if (!spill_done) {
11091             if ((spill_result = callerid_feed(cs, mtd->buf, res, AST_LAW(mtd->pvt))) < 0) {
11092                /*
11093                 * The previous diagnostic message output likely
11094                 * explains why it failed.
11095                 */
11096                ast_log(LOG_WARNING, "Failed to decode CallerID\n");
11097                break;
11098             } else if (spill_result) {
11099                spill_done = 1;
11100             }
11101          } else {
11102             /* keep reading data until the energy level drops below the threshold
11103                so we don't get another 'trigger' on the remaining carrier signal
11104             */
11105             if (calc_energy(mtd->buf, res, AST_LAW(mtd->pvt)) <= mwilevel)
11106                break;
11107          }
11108          if (samples > (8000 * 4)) /*Termination case - time to give up*/
11109             break;
11110       }
11111    }
11112 
11113    if (spill_result == 1) {
11114       callerid_get(cs, &name, &number, &flags);
11115       if (flags & CID_MSGWAITING) {
11116          ast_log(LOG_NOTICE, "mwi: Have Messages on channel %d\n", mtd->pvt->channel);
11117          notify_message(mtd->pvt->mailbox, 1);
11118       } else if (flags & CID_NOMSGWAITING) {
11119          ast_log(LOG_NOTICE, "mwi: No Messages on channel %d\n", mtd->pvt->channel);
11120          notify_message(mtd->pvt->mailbox, 0);
11121       } else {
11122          ast_log(LOG_NOTICE, "mwi: Status unknown on channel %d\n", mtd->pvt->channel);
11123       }
11124    }
11125 
11126 
11127 quit:
11128    callerid_free(cs);
11129 
11130    restore_gains(mtd->pvt);
11131 
11132 quit_no_clean:
11133    mtd->pvt->mwimonitoractive = 0;
11134 
11135    ast_free(mtd);
11136 
11137    return NULL;
11138 }
11139 
11140 /*
11141 * The following three functions (mwi_send_init, mwi_send_process_buffer,
11142 * mwi_send_process_event) work with the do_monitor thread to generate mwi spills
11143 * that are sent out via FXS port on voicemail state change.  The execution of
11144 * the mwi send is state driven and can either generate a ring pulse prior to
11145 * sending the fsk spill or simply send an fsk spill.
11146 */
11147 static int mwi_send_init(struct dahdi_pvt * pvt)
11148 {
11149    int x;
11150 
11151 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11152    /* Determine how this spill is to be sent */
11153    if (pvt->mwisend_rpas) {
11154       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
11155       pvt->mwisendactive = 1;
11156    } else if (pvt->mwisend_fsk) {
11157       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11158       pvt->mwisendactive = 1;
11159    } else {
11160       pvt->mwisendactive = 0;
11161       return 0;
11162    }
11163 #else
11164    if (mwisend_rpas) {
11165       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
11166    } else {
11167       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11168    }
11169    pvt->mwisendactive = 1;
11170 #endif
11171 
11172    if (pvt->cidspill) {
11173       ast_log(LOG_WARNING, "cidspill already exists when trying to send FSK MWI\n");
11174       ast_free(pvt->cidspill);
11175       pvt->cidspill = NULL;
11176       pvt->cidpos = 0;
11177       pvt->cidlen = 0;
11178    }
11179    pvt->cidspill = ast_calloc(1, MAX_CALLERID_SIZE);
11180    if (!pvt->cidspill) {
11181       pvt->mwisendactive = 0;
11182       return -1;
11183    }
11184    x = DAHDI_FLUSH_BOTH;
11185    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
11186    x = 3000;
11187    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_ONHOOKTRANSFER, &x);
11188 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11189    if (pvt->mwisend_fsk) {
11190 #endif
11191       pvt->cidlen = ast_callerid_vmwi_generate(pvt->cidspill, has_voicemail(pvt), CID_MWI_TYPE_MDMF_FULL,
11192                       AST_LAW(pvt), pvt->cid_name, pvt->cid_num, 0);
11193       pvt->cidpos = 0;
11194 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11195    }
11196 #endif
11197    return 0;
11198 }
11199 
11200 static int mwi_send_process_buffer(struct dahdi_pvt * pvt, int num_read)
11201 {
11202    struct timeval    now;
11203    int         res;
11204 
11205    /* sanity check to catch if this had been interrupted previously
11206    *  i.e. state says there is more to do but there is no spill allocated
11207    */
11208    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current && !pvt->cidspill) {
11209       pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11210    } else if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
11211       /* Normal processing -- Perform mwi send action */
11212       switch ( pvt->mwisend_data.mwisend_current) {
11213       case MWI_SEND_SA:
11214          /* Send the Ring Pulse Signal Alert */
11215          res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &AS_RP_cadence);
11216          if (res) {
11217             ast_log(LOG_WARNING, "Unable to set RP-AS ring cadence: %s\n", strerror(errno));
11218             goto quit;
11219          }
11220          res = dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RING);
11221          pvt->mwisend_data.mwisend_current = MWI_SEND_SA_WAIT;
11222          break;
11223       case MWI_SEND_SA_WAIT:  /* do nothing until I get RINGEROFF event */
11224          break;
11225       case MWI_SEND_PAUSE:  /* Wait between alert and spill - min of 500 mS*/
11226 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11227          if (pvt->mwisend_fsk) {
11228 #endif
11229             gettimeofday(&now, NULL);
11230             if ((int)(now.tv_sec - pvt->mwisend_data.pause.tv_sec) * 1000000 + (int)now.tv_usec - (int)pvt->mwisend_data.pause.tv_usec > 500000) {
11231                pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11232             }
11233 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11234          } else { /* support for mwisendtype=nofsk */
11235             pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
11236          }
11237 #endif
11238          break;
11239       case MWI_SEND_SPILL:
11240          /* We read some number of bytes.  Write an equal amount of data */
11241          if(0 < num_read) {
11242             if (num_read > pvt->cidlen - pvt->cidpos)
11243                num_read = pvt->cidlen - pvt->cidpos;
11244             res = write(pvt->subs[SUB_REAL].dfd, pvt->cidspill + pvt->cidpos, num_read);
11245             if (res > 0) {
11246                pvt->cidpos += res;
11247                if (pvt->cidpos >= pvt->cidlen) {
11248                   pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
11249                }
11250             } else {
11251                ast_log(LOG_WARNING, "MWI FSK Send Write failed: %s\n", strerror(errno));
11252                goto quit;
11253             }
11254          }
11255          break;
11256       case MWI_SEND_CLEANUP:
11257          /* For now, do nothing */
11258          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11259          break;
11260       default:
11261          /* Should not get here, punt*/
11262          goto quit;
11263       }
11264    }
11265 
11266    if (MWI_SEND_DONE == pvt->mwisend_data.mwisend_current) {
11267       if (pvt->cidspill) {
11268          ast_free(pvt->cidspill);
11269          pvt->cidspill = NULL;
11270          pvt->cidpos = 0;
11271          pvt->cidlen = 0;
11272       }
11273       pvt->mwisendactive = 0;
11274    }
11275    return 0;
11276 quit:
11277    if (pvt->cidspill) {
11278       ast_free(pvt->cidspill);
11279       pvt->cidspill = NULL;
11280       pvt->cidpos = 0;
11281       pvt->cidlen = 0;
11282    }
11283    pvt->mwisendactive = 0;
11284    return -1;
11285 }
11286 
11287 static int mwi_send_process_event(struct dahdi_pvt * pvt, int event)
11288 {
11289    int handled = 0;
11290 
11291    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
11292       switch (event) {
11293       case DAHDI_EVENT_RINGEROFF:
11294          if(pvt->mwisend_data.mwisend_current == MWI_SEND_SA_WAIT) {
11295             handled = 1;
11296 
11297             if (dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RINGOFF) ) {
11298                ast_log(LOG_WARNING, "Unable to finish RP-AS: %s mwi send aborted\n", strerror(errno));
11299                ast_free(pvt->cidspill);
11300                pvt->cidspill = NULL;
11301                pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11302                pvt->mwisendactive = 0;
11303             } else {
11304                pvt->mwisend_data.mwisend_current = MWI_SEND_PAUSE;
11305                gettimeofday(&pvt->mwisend_data.pause, NULL);
11306             }
11307          }
11308          break;
11309       /* Going off hook, I need to punt this spill */
11310       case DAHDI_EVENT_RINGOFFHOOK:
11311          if (pvt->cidspill) {
11312             ast_free(pvt->cidspill);
11313             pvt->cidspill = NULL;
11314             pvt->cidpos = 0;
11315             pvt->cidlen = 0;
11316          }
11317          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11318          pvt->mwisendactive = 0;
11319          break;
11320       case DAHDI_EVENT_RINGERON:
11321       case DAHDI_EVENT_HOOKCOMPLETE:
11322          break;
11323       default:
11324          break;
11325       }
11326    }
11327    return handled;
11328 }
11329 
11330 /* destroy a DAHDI channel, identified by its number */
11331 static int dahdi_destroy_channel_bynum(int channel)
11332 {
11333    struct dahdi_pvt *cur;
11334 
11335    ast_mutex_lock(&iflock);
11336    for (cur = iflist; cur; cur = cur->next) {
11337       if (cur->channel == channel) {
11338          int x = DAHDI_FLASH;
11339 
11340          /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
11341          ioctl(cur->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
11342 
11343          destroy_channel(cur, 1);
11344          ast_mutex_unlock(&iflock);
11345          ast_module_unref(ast_module_info->self);
11346          return RESULT_SUCCESS;
11347       }
11348    }
11349    ast_mutex_unlock(&iflock);
11350    return RESULT_FAILURE;
11351 }
11352 
11353 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
11354 {
11355    int res;
11356    pthread_t threadid;
11357    struct ast_channel *chan;
11358 
11359    /* Handle an event on a given channel for the monitor thread. */
11360 
11361    switch (event) {
11362    case DAHDI_EVENT_NONE:
11363    case DAHDI_EVENT_BITSCHANGED:
11364       break;
11365    case DAHDI_EVENT_WINKFLASH:
11366    case DAHDI_EVENT_RINGOFFHOOK:
11367       if (i->inalarm) break;
11368       if (i->radio) break;
11369       /* Got a ring/answer.  What kind of channel are we? */
11370       switch (i->sig) {
11371       case SIG_FXOLS:
11372       case SIG_FXOGS:
11373       case SIG_FXOKS:
11374          res = dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11375          if (res && (errno == EBUSY))
11376             break;
11377 
11378          /* Cancel VMWI spill */
11379          ast_free(i->cidspill);
11380          i->cidspill = NULL;
11381          restore_conference(i);
11382 
11383          if (i->immediate) {
11384             dahdi_enable_ec(i);
11385             /* The channel is immediately up.  Start right away */
11386             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
11387             chan = dahdi_new(i, AST_STATE_RING, 1, SUB_REAL, 0, NULL);
11388             if (!chan) {
11389                ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
11390                res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11391                if (res < 0)
11392                   ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11393             }
11394          } else {
11395             /* Check for callerid, digits, etc */
11396             chan = dahdi_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, NULL);
11397             if (chan) {
11398                if (has_voicemail(i))
11399                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
11400                else
11401                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
11402                if (res < 0)
11403                   ast_log(LOG_WARNING, "Unable to play dialtone on channel %d, do you have defaultzone and loadzone defined?\n", i->channel);
11404                if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11405                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11406                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11407                   if (res < 0)
11408                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11409                   ast_hangup(chan);
11410                }
11411             } else
11412                ast_log(LOG_WARNING, "Unable to create channel\n");
11413          }
11414          break;
11415       case SIG_FXSLS:
11416       case SIG_FXSGS:
11417       case SIG_FXSKS:
11418             i->ringt = i->ringt_base;
11419             /* Fall through */
11420       case SIG_EMWINK:
11421       case SIG_FEATD:
11422       case SIG_FEATDMF:
11423       case SIG_FEATDMF_TA:
11424       case SIG_E911:
11425       case SIG_FGC_CAMA:
11426       case SIG_FGC_CAMAMF:
11427       case SIG_FEATB:
11428       case SIG_EM:
11429       case SIG_EM_E1:
11430       case SIG_SFWINK:
11431       case SIG_SF_FEATD:
11432       case SIG_SF_FEATDMF:
11433       case SIG_SF_FEATB:
11434       case SIG_SF:
11435          /* Check for callerid, digits, etc */
11436          if (i->cid_start == CID_START_POLARITY_IN) {
11437             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11438          } else {
11439             chan = dahdi_new(i, AST_STATE_RING, 0, SUB_REAL, 0, NULL);
11440          }
11441 
11442          if (!chan) {
11443             ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11444          } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11445             ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11446             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11447             if (res < 0) {
11448                ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11449             }
11450             ast_hangup(chan);
11451          }
11452          break;
11453       default:
11454          ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11455          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11456          if (res < 0)
11457             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11458          return NULL;
11459       }
11460       break;
11461    case DAHDI_EVENT_NOALARM:
11462       switch (i->sig) {
11463 #if defined(HAVE_PRI)
11464       case SIG_PRI_LIB_HANDLE_CASES:
11465          ast_mutex_lock(&i->lock);
11466          sig_pri_chan_alarm_notify(i->sig_pvt, 1);
11467          ast_mutex_unlock(&i->lock);
11468          break;
11469 #endif   /* defined(HAVE_PRI) */
11470 #if defined(HAVE_SS7)
11471       case SIG_SS7:
11472          sig_ss7_set_alarm(i->sig_pvt, 0);
11473          break;
11474 #endif   /* defined(HAVE_SS7) */
11475       default:
11476          i->inalarm = 0;
11477          break;
11478       }
11479       handle_clear_alarms(i);
11480       break;
11481    case DAHDI_EVENT_ALARM:
11482       switch (i->sig) {
11483 #if defined(HAVE_PRI)
11484       case SIG_PRI_LIB_HANDLE_CASES:
11485          ast_mutex_lock(&i->lock);
11486          sig_pri_chan_alarm_notify(i->sig_pvt, 0);
11487          ast_mutex_unlock(&i->lock);
11488          break;
11489 #endif   /* defined(HAVE_PRI) */
11490 #if defined(HAVE_SS7)
11491       case SIG_SS7:
11492          sig_ss7_set_alarm(i->sig_pvt, 1);
11493          break;
11494 #endif   /* defined(HAVE_SS7) */
11495       default:
11496          i->inalarm = 1;
11497          break;
11498       }
11499       res = get_alarms(i);
11500       handle_alarms(i, res);
11501       /* fall thru intentionally */
11502    case DAHDI_EVENT_ONHOOK:
11503       if (i->radio)
11504          break;
11505       /* Back on hook.  Hang up. */
11506       switch (i->sig) {
11507       case SIG_FXOLS:
11508       case SIG_FXOGS:
11509       case SIG_FEATD:
11510       case SIG_FEATDMF:
11511       case SIG_FEATDMF_TA:
11512       case SIG_E911:
11513       case SIG_FGC_CAMA:
11514       case SIG_FGC_CAMAMF:
11515       case SIG_FEATB:
11516       case SIG_EM:
11517       case SIG_EM_E1:
11518       case SIG_EMWINK:
11519       case SIG_SF_FEATD:
11520       case SIG_SF_FEATDMF:
11521       case SIG_SF_FEATB:
11522       case SIG_SF:
11523       case SIG_SFWINK:
11524       case SIG_FXSLS:
11525       case SIG_FXSGS:
11526       case SIG_FXSKS:
11527       case SIG_FXOKS:
11528          dahdi_disable_ec(i);
11529          /* Diddle the battery for the zhone */
11530 #ifdef ZHONE_HACK
11531          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11532          usleep(1);
11533 #endif
11534          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11535          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
11536          break;
11537       case SIG_SS7:
11538       case SIG_PRI_LIB_HANDLE_CASES:
11539          dahdi_disable_ec(i);
11540          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11541          break;
11542       default:
11543          ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11544          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11545          return NULL;
11546       }
11547       break;
11548    case DAHDI_EVENT_POLARITY:
11549       switch (i->sig) {
11550       case SIG_FXSLS:
11551       case SIG_FXSKS:
11552       case SIG_FXSGS:
11553          /* We have already got a PR before the channel was
11554             created, but it wasn't handled. We need polarity
11555             to be REV for remote hangup detection to work.
11556             At least in Spain */
11557          if (i->hanguponpolarityswitch)
11558             i->polarity = POLARITY_REV;
11559          if (i->cid_start == CID_START_POLARITY || i->cid_start == CID_START_POLARITY_IN) {
11560             i->polarity = POLARITY_REV;
11561             ast_verb(2, "Starting post polarity "
11562                "CID detection on channel %d\n",
11563                i->channel);
11564             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11565             if (!chan) {
11566                ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11567             } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11568                ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11569             }
11570          }
11571          break;
11572       default:
11573          ast_log(LOG_WARNING, "handle_init_event detected "
11574             "polarity reversal on non-FXO (SIG_FXS) "
11575             "interface %d\n", i->channel);
11576       }
11577       break;
11578    case DAHDI_EVENT_REMOVED: /* destroy channel, will actually do so in do_monitor */
11579       ast_log(LOG_NOTICE,
11580             "Got DAHDI_EVENT_REMOVED. Destroying channel %d\n",
11581             i->channel);
11582       return i;
11583    case DAHDI_EVENT_NEONMWI_ACTIVE:
11584       if (i->mwimonitor_neon) {
11585          notify_message(i->mailbox, 1);
11586          ast_log(LOG_NOTICE, "NEON MWI set for channel %d, mailbox %s \n", i->channel, i->mailbox);
11587       }
11588       break;
11589    case DAHDI_EVENT_NEONMWI_INACTIVE:
11590       if (i->mwimonitor_neon) {
11591          notify_message(i->mailbox, 0);
11592          ast_log(LOG_NOTICE, "NEON MWI cleared for channel %d, mailbox %s\n", i->channel, i->mailbox);
11593       }
11594       break;
11595    }
11596    return NULL;
11597 }
11598 
11599 static void *do_monitor(void *data)
11600 {
11601    int count, res, res2, spoint, pollres=0;
11602    struct dahdi_pvt *i;
11603    struct dahdi_pvt *last = NULL;
11604    struct dahdi_pvt *doomed;
11605    time_t thispass = 0, lastpass = 0;
11606    int found;
11607    char buf[1024];
11608    struct pollfd *pfds=NULL;
11609    int lastalloc = -1;
11610    /* This thread monitors all the frame relay interfaces which are not yet in use
11611       (and thus do not have a separate thread) indefinitely */
11612    /* From here on out, we die whenever asked */
11613 #if 0
11614    if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
11615       ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
11616       return NULL;
11617    }
11618    ast_debug(1, "Monitor starting...\n");
11619 #endif
11620    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11621 
11622    for (;;) {
11623       /* Lock the interface list */
11624       ast_mutex_lock(&iflock);
11625       if (!pfds || (lastalloc != ifcount)) {
11626          if (pfds) {
11627             ast_free(pfds);
11628             pfds = NULL;
11629          }
11630          if (ifcount) {
11631             if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
11632                ast_mutex_unlock(&iflock);
11633                return NULL;
11634             }
11635          }
11636          lastalloc = ifcount;
11637       }
11638       /* Build the stuff we're going to poll on, that is the socket of every
11639          dahdi_pvt that does not have an associated owner channel */
11640       count = 0;
11641       for (i = iflist; i; i = i->next) {
11642          ast_mutex_lock(&i->lock);
11643          if ((i->subs[SUB_REAL].dfd > -1) && i->sig && (!i->radio) && !(i->sig & SIG_MFCR2)) {
11644             if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11645                struct analog_pvt *p = i->sig_pvt;
11646 
11647                if (!p)
11648                   ast_log(LOG_ERROR, "No sig_pvt?\n");
11649 
11650                if (!p->owner && !p->subs[SUB_REAL].owner) {
11651                   /* This needs to be watched, as it lacks an owner */
11652                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11653                   pfds[count].events = POLLPRI;
11654                   pfds[count].revents = 0;
11655                   /* Message waiting or r2 channels also get watched for reading */
11656                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk || 
11657                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11658                      pfds[count].events |= POLLIN;
11659                   }
11660                   count++;
11661                }
11662             } else {
11663                if (!i->owner && !i->subs[SUB_REAL].owner && !i->mwimonitoractive ) {
11664                   /* This needs to be watched, as it lacks an owner */
11665                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11666                   pfds[count].events = POLLPRI;
11667                   pfds[count].revents = 0;
11668                   /* If we are monitoring for VMWI or sending CID, we need to
11669                      read from the channel as well */
11670                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk ||
11671                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11672                      pfds[count].events |= POLLIN;
11673                   }
11674                   count++;
11675                }
11676             }
11677          }
11678          ast_mutex_unlock(&i->lock);
11679       }
11680       /* Okay, now that we know what to do, release the interface lock */
11681       ast_mutex_unlock(&iflock);
11682 
11683       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
11684       pthread_testcancel();
11685       /* Wait at least a second for something to happen */
11686       res = poll(pfds, count, 1000);
11687       pthread_testcancel();
11688       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11689 
11690       /* Okay, poll has finished.  Let's see what happened.  */
11691       if (res < 0) {
11692          if ((errno != EAGAIN) && (errno != EINTR))
11693             ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
11694          continue;
11695       }
11696       /* Alright, lock the interface list again, and let's look and see what has
11697          happened */
11698       ast_mutex_lock(&iflock);
11699       found = 0;
11700       spoint = 0;
11701       lastpass = thispass;
11702       thispass = time(NULL);
11703       doomed = NULL;
11704       for (i = iflist;; i = i->next) {
11705          if (doomed) {
11706             int res;
11707             res = dahdi_destroy_channel_bynum(doomed->channel);
11708             if (res != RESULT_SUCCESS) {
11709                ast_log(LOG_WARNING, "Couldn't find channel to destroy, hopefully another destroy operation just happened.\n");
11710             }
11711             doomed = NULL;
11712          }
11713          if (!i) {
11714             break;
11715          }
11716 
11717          if (thispass != lastpass) {
11718             if (!found && ((i == last) || ((i == iflist) && !last))) {
11719                last = i;
11720                if (last) {
11721                   struct analog_pvt *analog_p = last->sig_pvt;
11722                   /* Only allow MWI to be initiated on a quiescent fxs port */
11723                   if (analog_p
11724                      && !last->mwisendactive
11725                      && (last->sig & __DAHDI_SIG_FXO)
11726                      && !analog_p->fxsoffhookstate
11727                      && !last->owner
11728                      && !ast_strlen_zero(last->mailbox)
11729                      && (thispass - analog_p->onhooktime > 3)) {
11730                      res = has_voicemail(last);
11731                      if (analog_p->msgstate != res) {
11732                         /* Set driver resources for signalling VMWI */
11733                         res2 = ioctl(last->subs[SUB_REAL].dfd, DAHDI_VMWI, &res);
11734                         if (res2) {
11735                            /* TODO: This message will ALWAYS be generated on some cards; any way to restrict it to those cards where it is interesting? */
11736                            ast_debug(3, "Unable to control message waiting led on channel %d: %s\n", last->channel, strerror(errno));
11737                         }
11738                         /* If enabled for FSK spill then initiate it */
11739                         if (mwi_send_init(last)) {
11740                            ast_log(LOG_WARNING, "Unable to initiate mwi send sequence on channel %d\n", last->channel);
11741                         }
11742                         analog_p->msgstate = res;
11743                         found ++;
11744                      }
11745                   }
11746                   last = last->next;
11747                }
11748             }
11749          }
11750          if ((i->subs[SUB_REAL].dfd > -1) && i->sig) {
11751             if (i->radio && !i->owner)
11752             {
11753                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11754                if (res)
11755                {
11756                   ast_debug(1, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
11757                   /* Don't hold iflock while handling init events */
11758                   ast_mutex_unlock(&iflock);
11759                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11760                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11761                   else
11762                      doomed = handle_init_event(i, res);
11763                   ast_mutex_lock(&iflock);
11764                }
11765                continue;
11766             }
11767             pollres = ast_fdisset(pfds, i->subs[SUB_REAL].dfd, count, &spoint);
11768             if (pollres & POLLIN) {
11769                if (i->owner || i->subs[SUB_REAL].owner) {
11770 #ifdef HAVE_PRI
11771                   if (!i->pri)
11772 #endif
11773                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].dfd);
11774                   continue;
11775                }
11776                if (!i->mwimonitor_fsk && !i->mwisendactive  && i->cid_start != CID_START_DTMF_NOALERT) {
11777                   ast_log(LOG_WARNING, "Whoa....  I'm not looking for MWI or sending MWI but am reading (%d)...\n", i->subs[SUB_REAL].dfd);
11778                   continue;
11779                }
11780                res = read(i->subs[SUB_REAL].dfd, buf, sizeof(buf));
11781                if (res > 0) {
11782                   if (i->mwimonitor_fsk) {
11783                      if (calc_energy((unsigned char *) buf, res, AST_LAW(i)) > mwilevel) {
11784                         pthread_attr_t attr;
11785                         pthread_t threadid;
11786                         struct mwi_thread_data *mtd;
11787 
11788                         pthread_attr_init(&attr);
11789                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
11790 
11791                         ast_log(LOG_DEBUG, "Maybe some MWI on port %d!\n", i->channel);
11792                         if ((mtd = ast_calloc(1, sizeof(*mtd)))) {
11793                            mtd->pvt = i;
11794                            memcpy(mtd->buf, buf, res);
11795                            mtd->len = res;
11796                            if (ast_pthread_create_background(&threadid, &attr, mwi_thread, mtd)) {
11797                               ast_log(LOG_WARNING, "Unable to start mwi thread on channel %d\n", i->channel);
11798                               ast_free(mtd);
11799                            }
11800                            i->mwimonitoractive = 1;
11801                         }
11802                      }
11803                   /* If configured to check for a DTMF CID spill that comes without alert (e.g no polarity reversal) */
11804                   } else if (i->cid_start == CID_START_DTMF_NOALERT) {
11805                      int energy;
11806                      struct timeval now;
11807                      /* State machine dtmfcid_holdoff_state allows for the line to settle
11808                       * before checking agin for dtmf energy.  Presently waits for 500 mS before checking again 
11809                      */
11810                      if (1 == i->dtmfcid_holdoff_state) {
11811                         gettimeofday(&i->dtmfcid_delay, NULL);
11812                         i->dtmfcid_holdoff_state = 2;
11813                      } else if (2 == i->dtmfcid_holdoff_state) {
11814                         gettimeofday(&now, NULL);
11815                         if ((int)(now.tv_sec - i->dtmfcid_delay.tv_sec) * 1000000 + (int)now.tv_usec - (int)i->dtmfcid_delay.tv_usec > 500000) {
11816                            i->dtmfcid_holdoff_state = 0;
11817                         }
11818                      } else {
11819                         energy = calc_energy((unsigned char *) buf, res, AST_LAW(i));
11820                         if (!i->mwisendactive && energy > dtmfcid_level) {
11821                            pthread_t threadid;
11822                            struct ast_channel *chan;
11823                            ast_mutex_unlock(&iflock);
11824                            if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11825                               /* just in case this event changes or somehow destroys a channel, set doomed here too */
11826                               doomed = analog_handle_init_event(i->sig_pvt, ANALOG_EVENT_DTMFCID);  
11827                               i->dtmfcid_holdoff_state = 1;
11828                            } else {
11829                               chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11830                               if (!chan) {
11831                                  ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11832                               } else {
11833                                  res = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11834                                  if (res) {
11835                                     ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11836                                  } else {
11837                                     i->dtmfcid_holdoff_state = 1;
11838                                  }
11839                               }
11840                            }
11841                            ast_mutex_lock(&iflock);
11842                         }
11843                      }
11844                   }
11845                   if (i->mwisendactive) {
11846                      mwi_send_process_buffer(i, res);
11847                   }
11848                } else {
11849                   ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
11850                }
11851             }
11852             if (pollres & POLLPRI) {
11853                if (i->owner || i->subs[SUB_REAL].owner) {
11854 #ifdef HAVE_PRI
11855                   if (!i->pri)
11856 #endif
11857                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d)...\n", i->subs[SUB_REAL].dfd);
11858                   continue;
11859                }
11860                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11861                ast_debug(1, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
11862                /* Don't hold iflock while handling init events */
11863                ast_mutex_unlock(&iflock);
11864                if (0 == i->mwisendactive || 0 == mwi_send_process_event(i, res)) {
11865                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11866                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11867                   else
11868                      doomed = handle_init_event(i, res);
11869                }
11870                ast_mutex_lock(&iflock);
11871             }
11872          }
11873       }
11874       ast_mutex_unlock(&iflock);
11875    }
11876    /* Never reached */
11877    return NULL;
11878 
11879 }
11880 
11881 static int restart_monitor(void)
11882 {
11883    /* If we're supposed to be stopped -- stay stopped */
11884    if (monitor_thread == AST_PTHREADT_STOP)
11885       return 0;
11886    ast_mutex_lock(&monlock);
11887    if (monitor_thread == pthread_self()) {
11888       ast_mutex_unlock(&monlock);
11889       ast_log(LOG_WARNING, "Cannot kill myself\n");
11890       return -1;
11891    }
11892    if (monitor_thread != AST_PTHREADT_NULL) {
11893       /* Wake up the thread */
11894       pthread_kill(monitor_thread, SIGURG);
11895    } else {
11896       /* Start a new monitor */
11897       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
11898          ast_mutex_unlock(&monlock);
11899          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
11900          return -1;
11901       }
11902    }
11903    ast_mutex_unlock(&monlock);
11904    return 0;
11905 }
11906 
11907 #if defined(HAVE_PRI)
11908 static int pri_resolve_span(int *span, int channel, int offset, struct dahdi_spaninfo *si)
11909 {
11910    int x;
11911    int trunkgroup;
11912    /* Get appropriate trunk group if there is one */
11913    trunkgroup = pris[*span].mastertrunkgroup;
11914    if (trunkgroup) {
11915       /* Select a specific trunk group */
11916       for (x = 0; x < NUM_SPANS; x++) {
11917          if (pris[x].pri.trunkgroup == trunkgroup) {
11918             *span = x;
11919             return 0;
11920          }
11921       }
11922       ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
11923       *span = -1;
11924    } else {
11925       if (pris[*span].pri.trunkgroup) {
11926          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);
11927          *span = -1;
11928       } else if (pris[*span].mastertrunkgroup) {
11929          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
11930          *span = -1;
11931       } else {
11932          if (si->totalchans == 31) {
11933             /* E1 */
11934             pris[*span].dchannels[0] = 16 + offset;
11935          } else if (si->totalchans == 24) {
11936             /* T1 or J1 */
11937             pris[*span].dchannels[0] = 24 + offset;
11938          } else if (si->totalchans == 3) {
11939             /* BRI */
11940             pris[*span].dchannels[0] = 3 + offset;
11941          } else {
11942             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);
11943             *span = -1;
11944             return 0;
11945          }
11946          pris[*span].pri.span = *span + 1;
11947       }
11948    }
11949    return 0;
11950 }
11951 #endif   /* defined(HAVE_PRI) */
11952 
11953 #if defined(HAVE_PRI)
11954 static int pri_create_trunkgroup(int trunkgroup, int *channels)
11955 {
11956    struct dahdi_spaninfo si;
11957    struct dahdi_params p;
11958    int fd;
11959    int span;
11960    int ospan=0;
11961    int x,y;
11962    for (x = 0; x < NUM_SPANS; x++) {
11963       if (pris[x].pri.trunkgroup == trunkgroup) {
11964          ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
11965          return -1;
11966       }
11967    }
11968    for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
11969       if (!channels[y])
11970          break;
11971       memset(&si, 0, sizeof(si));
11972       memset(&p, 0, sizeof(p));
11973       fd = open("/dev/dahdi/channel", O_RDWR);
11974       if (fd < 0) {
11975          ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
11976          return -1;
11977       }
11978       x = channels[y];
11979       if (ioctl(fd, DAHDI_SPECIFY, &x)) {
11980          ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
11981          close(fd);
11982          return -1;
11983       }
11984       if (ioctl(fd, DAHDI_GET_PARAMS, &p)) {
11985          ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
11986          return -1;
11987       }
11988       if (ioctl(fd, DAHDI_SPANSTAT, &si)) {
11989          ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d): %s\n", channels[y], p.spanno, strerror(errno));
11990          close(fd);
11991          return -1;
11992       }
11993       span = p.spanno - 1;
11994       if (pris[span].pri.trunkgroup) {
11995          ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].pri.trunkgroup);
11996          close(fd);
11997          return -1;
11998       }
11999       if (pris[span].pri.pvts[0]) {
12000          ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
12001          close(fd);
12002          return -1;
12003       }
12004       if (!y) {
12005          pris[span].pri.trunkgroup = trunkgroup;
12006          ospan = span;
12007       }
12008       pris[ospan].dchannels[y] = channels[y];
12009       pris[span].pri.span = span + 1;
12010       close(fd);
12011    }
12012    return 0;
12013 }
12014 #endif   /* defined(HAVE_PRI) */
12015 
12016 #if defined(HAVE_PRI)
12017 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
12018 {
12019    if (pris[span].mastertrunkgroup) {
12020       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);
12021       return -1;
12022    }
12023    pris[span].mastertrunkgroup = trunkgroup;
12024    pris[span].prilogicalspan = logicalspan;
12025    return 0;
12026 }
12027 #endif   /* defined(HAVE_PRI) */
12028 
12029 #if defined(HAVE_SS7)
12030 static unsigned int parse_pointcode(const char *pcstring)
12031 {
12032    unsigned int code1, code2, code3;
12033    int numvals;
12034 
12035    numvals = sscanf(pcstring, "%30d-%30d-%30d", &code1, &code2, &code3);
12036    if (numvals == 1)
12037       return code1;
12038    if (numvals == 3)
12039       return (code1 << 16) | (code2 << 8) | code3;
12040 
12041    return 0;
12042 }
12043 #endif   /* defined(HAVE_SS7) */
12044 
12045 #if defined(HAVE_SS7)
12046 static struct dahdi_ss7 * ss7_resolve_linkset(int linkset)
12047 {
12048    if ((linkset < 0) || (linkset >= NUM_SPANS))
12049       return NULL;
12050    else
12051       return &linksets[linkset - 1];
12052 }
12053 #endif   /* defined(HAVE_SS7) */
12054 
12055 #ifdef HAVE_OPENR2
12056 static void dahdi_r2_destroy_links(void)
12057 {
12058    int i = 0;
12059    if (!r2links) {
12060       return;
12061    }
12062    for (; i < r2links_count; i++) {
12063       if (r2links[i]->r2master != AST_PTHREADT_NULL) {
12064          pthread_cancel(r2links[i]->r2master);
12065          pthread_join(r2links[i]->r2master, NULL);
12066          openr2_context_delete(r2links[i]->protocol_context);
12067       }
12068       ast_free(r2links[i]);
12069    }
12070    ast_free(r2links);
12071    r2links = NULL;
12072    r2links_count = 0;
12073 }
12074 
12075 #define R2_LINK_CAPACITY 10
12076 static struct dahdi_mfcr2 *dahdi_r2_get_link(void)
12077 {
12078    struct dahdi_mfcr2 *new_r2link = NULL;
12079    struct dahdi_mfcr2 **new_r2links = NULL;
12080    /* this function is called just when starting up and no monitor threads have been launched,
12081       no need to lock monitored_count member */
12082    if (!r2links_count || (r2links[r2links_count - 1]->monitored_count == R2_LINK_CAPACITY)) {
12083       new_r2link = ast_calloc(1, sizeof(**r2links));
12084       if (!new_r2link) {
12085          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
12086          return NULL;
12087       }
12088       new_r2links = ast_realloc(r2links, ((r2links_count + 1) * sizeof(*r2links)));
12089       if (!new_r2links) {
12090          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
12091          ast_free(new_r2link);
12092          return NULL;
12093       }
12094       r2links = new_r2links;
12095       new_r2link->r2master = AST_PTHREADT_NULL;
12096       r2links[r2links_count] = new_r2link;
12097       r2links_count++;
12098       ast_log(LOG_DEBUG, "Created new R2 link!\n");
12099    }
12100    return r2links[r2links_count - 1];
12101 }
12102 
12103 static int dahdi_r2_set_context(struct dahdi_mfcr2 *r2_link, const struct dahdi_chan_conf *conf)
12104 {
12105    char tmplogdir[] = "/tmp";
12106    char logdir[OR2_MAX_PATH];
12107    int threshold = 0;
12108    int snres = 0;
12109    r2_link->protocol_context = openr2_context_new(NULL, &dahdi_r2_event_iface,
12110          &dahdi_r2_transcode_iface, conf->mfcr2.variant, conf->mfcr2.max_ani,
12111          conf->mfcr2.max_dnis);
12112    if (!r2_link->protocol_context) {
12113       return -1;
12114    }
12115    openr2_context_set_log_level(r2_link->protocol_context, conf->mfcr2.loglevel);
12116    openr2_context_set_ani_first(r2_link->protocol_context, conf->mfcr2.get_ani_first);
12117 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
12118    openr2_context_set_skip_category_request(r2_link->protocol_context, conf->mfcr2.skip_category_request);
12119 #endif
12120    openr2_context_set_mf_threshold(r2_link->protocol_context, threshold);
12121    openr2_context_set_mf_back_timeout(r2_link->protocol_context, conf->mfcr2.mfback_timeout);
12122    openr2_context_set_metering_pulse_timeout(r2_link->protocol_context, conf->mfcr2.metering_pulse_timeout);
12123    openr2_context_set_double_answer(r2_link->protocol_context, conf->mfcr2.double_answer);
12124    openr2_context_set_immediate_accept(r2_link->protocol_context, conf->mfcr2.immediate_accept);
12125    if (ast_strlen_zero(conf->mfcr2.logdir)) {
12126       if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
12127          ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
12128       }
12129    } else {
12130       snres = snprintf(logdir, sizeof(logdir), "%s/%s/%s", ast_config_AST_LOG_DIR, "mfcr2", conf->mfcr2.logdir);
12131       if (snres >= sizeof(logdir)) {
12132          ast_log(LOG_ERROR, "MFC/R2 logging directory truncated, using %s\n", tmplogdir);
12133          if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
12134             ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
12135          }
12136       } else {
12137          if (openr2_context_set_log_directory(r2_link->protocol_context, logdir)) {
12138             ast_log(LOG_ERROR, "Failed setting MFC/R2 log directory %s\n", logdir);
12139          }
12140       }
12141    }
12142    if (!ast_strlen_zero(conf->mfcr2.r2proto_file)) {
12143       if (openr2_context_configure_from_advanced_file(r2_link->protocol_context, conf->mfcr2.r2proto_file)) {
12144          ast_log(LOG_ERROR, "Failed to configure r2context from advanced configuration file %s\n", conf->mfcr2.r2proto_file);
12145       }
12146    }
12147    r2_link->monitored_count = 0;
12148    return 0;
12149 }
12150 #endif
12151 
12152 /* converts a DAHDI sigtype to signalling as can be configured from
12153  * chan_dahdi.conf.
12154  * While both have basically the same values, this will later be the
12155  * place to add filters and sanity checks
12156  */
12157 static int sigtype_to_signalling(int sigtype)
12158 {
12159    return sigtype;
12160 }
12161 
12162 /*!
12163  * \internal
12164  * \brief Get file name and channel number from (subdir,number)
12165  *
12166  * \param subdir name of the subdirectory under /dev/dahdi/
12167  * \param channel name of device file under /dev/dahdi/<subdir>/
12168  * \param path buffer to put file name in
12169  * \param pathlen maximal length of path
12170  *
12171  * \retval minor number of dahdi channel.
12172  * \retval -errno on error.
12173  */
12174 static int device2chan(const char *subdir, int channel, char *path, int pathlen)
12175 {
12176    struct stat stbuf;
12177    int      num;
12178 
12179    snprintf(path, pathlen, "/dev/dahdi/%s/%d", subdir, channel);
12180    if (stat(path, &stbuf) < 0) {
12181       ast_log(LOG_ERROR, "stat(%s) failed: %s\n", path, strerror(errno));
12182       return -errno;
12183    }
12184    if (!S_ISCHR(stbuf.st_mode)) {
12185       ast_log(LOG_ERROR, "%s: Not a character device file\n", path);
12186       return -EINVAL;
12187    }
12188    num = minor(stbuf.st_rdev);
12189    ast_log(LOG_DEBUG, "%s -> %d\n", path, num);
12190    return num;
12191 
12192 }
12193 
12194 /*!
12195  * \internal
12196  * \brief Initialize/create a channel interface.
12197  *
12198  * \param channel Channel interface number to initialize/create.
12199  * \param conf Configuration parameters to initialize interface with.
12200  * \param reloading What we are doing now:
12201  * 0 - initial module load,
12202  * 1 - module reload,
12203  * 2 - module restart
12204  *
12205  * \retval Interface-pointer initialized/created
12206  * \retval NULL if error
12207  */
12208 static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf, int reloading)
12209 {
12210    /* Make a dahdi_pvt structure for this interface */
12211    struct dahdi_pvt *tmp;/*!< Current channel structure initializing */
12212    char fn[80];
12213    struct dahdi_bufferinfo bi;
12214 
12215    int res;
12216 #if defined(HAVE_PRI)
12217    int span = 0;
12218 #endif   /* defined(HAVE_PRI) */
12219    int here = 0;/*!< TRUE if the channel interface already exists. */
12220    int x;
12221    struct analog_pvt *analog_p = NULL;
12222    struct dahdi_params p;
12223 #if defined(HAVE_PRI)
12224    struct dahdi_spaninfo si;
12225    struct sig_pri_chan *pri_chan = NULL;
12226 #endif   /* defined(HAVE_PRI) */
12227 #if defined(HAVE_SS7)
12228    struct sig_ss7_chan *ss7_chan = NULL;
12229 #endif   /* defined(HAVE_SS7) */
12230 
12231    /* Search channel interface list to see if it already exists. */
12232    for (tmp = iflist; tmp; tmp = tmp->next) {
12233       if (!tmp->destroy) {
12234          if (tmp->channel == channel) {
12235             /* The channel interface already exists. */
12236             here = 1;
12237             break;
12238          }
12239          if (tmp->channel > channel) {
12240             /* No way it can be in the sorted list. */
12241             tmp = NULL;
12242             break;
12243          }
12244       }
12245    }
12246 
12247    if (!here && reloading != 1) {
12248       tmp = ast_calloc(1, sizeof(*tmp));
12249       if (!tmp) {
12250          return NULL;
12251       }
12252       tmp->cc_params = ast_cc_config_params_init();
12253       if (!tmp->cc_params) {
12254          ast_free(tmp);
12255          return NULL;
12256       }
12257       ast_mutex_init(&tmp->lock);
12258       ifcount++;
12259       for (x = 0; x < 3; x++)
12260          tmp->subs[x].dfd = -1;
12261       tmp->channel = channel;
12262       tmp->priindication_oob = conf->chan.priindication_oob;
12263    }
12264 
12265    if (tmp) {
12266       int chan_sig = conf->chan.sig;
12267 
12268       /* If there are variables in tmp before it is updated to match the new config, clear them */
12269       if (reloading && tmp->vars) {
12270          ast_variables_destroy(tmp->vars);
12271          tmp->vars = NULL;
12272       }
12273 
12274 
12275       if (!here) {
12276          /* Can only get here if this is a new channel interface being created. */
12277          if ((channel != CHAN_PSEUDO)) {
12278             int count = 0;
12279 
12280             snprintf(fn, sizeof(fn), "%d", channel);
12281             /* Open non-blocking */
12282             tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
12283             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 */
12284                usleep(1);
12285                tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
12286                count++;
12287             }
12288             /* Allocate a DAHDI structure */
12289             if (tmp->subs[SUB_REAL].dfd < 0) {
12290                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);
12291                destroy_dahdi_pvt(tmp);
12292                return NULL;
12293             }
12294             memset(&p, 0, sizeof(p));
12295             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12296             if (res < 0) {
12297                ast_log(LOG_ERROR, "Unable to get parameters: %s\n", strerror(errno));
12298                destroy_dahdi_pvt(tmp);
12299                return NULL;
12300             }
12301             if (conf->is_sig_auto)
12302                chan_sig = sigtype_to_signalling(p.sigtype);
12303             if (p.sigtype != (chan_sig & 0x3ffff)) {
12304                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));
12305                destroy_dahdi_pvt(tmp);
12306                return NULL;
12307             }
12308             tmp->law_default = p.curlaw;
12309             tmp->law = p.curlaw;
12310             tmp->span = p.spanno;
12311 #if defined(HAVE_PRI)
12312             span = p.spanno - 1;
12313 #endif   /* defined(HAVE_PRI) */
12314          } else {
12315             chan_sig = 0;
12316          }
12317          tmp->sig = chan_sig;
12318          tmp->outsigmod = conf->chan.outsigmod;
12319 
12320          if (analog_lib_handles(chan_sig, tmp->radio, tmp->oprmode)) {
12321             analog_p = analog_new(dahdisig_to_analogsig(chan_sig), &dahdi_analog_callbacks, tmp);
12322             if (!analog_p) {
12323                destroy_dahdi_pvt(tmp);
12324                return NULL;
12325             }
12326             tmp->sig_pvt = analog_p;
12327          }
12328 #if defined(HAVE_SS7)
12329          if (chan_sig == SIG_SS7) {
12330             struct dahdi_ss7 *ss7;
12331             int clear = 0;
12332 
12333             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &clear)) {
12334                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
12335                destroy_dahdi_pvt(tmp);
12336                return NULL;
12337             }
12338 
12339             ss7 = ss7_resolve_linkset(cur_linkset);
12340             if (!ss7) {
12341                ast_log(LOG_ERROR, "Unable to find linkset %d\n", cur_linkset);
12342                destroy_dahdi_pvt(tmp);
12343                return NULL;
12344             }
12345             ss7->ss7.span = cur_linkset;
12346             if (cur_cicbeginswith < 0) {
12347                ast_log(LOG_ERROR, "Need to set cicbeginswith for the channels!\n");
12348                destroy_dahdi_pvt(tmp);
12349                return NULL;
12350             }
12351             ss7_chan = sig_ss7_chan_new(tmp, &dahdi_ss7_callbacks, &ss7->ss7);
12352             if (!ss7_chan) {
12353                destroy_dahdi_pvt(tmp);
12354                return NULL;
12355             }
12356             tmp->sig_pvt = ss7_chan;
12357             tmp->ss7 = &ss7->ss7;
12358 
12359             ss7_chan->channel = tmp->channel;
12360             ss7_chan->cic = cur_cicbeginswith++;
12361 
12362             /* DB: Add CIC's DPC information */
12363             ss7_chan->dpc = cur_defaultdpc;
12364 
12365             ss7->ss7.pvts[ss7->ss7.numchans++] = ss7_chan;
12366 
12367             ast_copy_string(ss7->ss7.internationalprefix, conf->ss7.ss7.internationalprefix, sizeof(ss7->ss7.internationalprefix));
12368             ast_copy_string(ss7->ss7.nationalprefix, conf->ss7.ss7.nationalprefix, sizeof(ss7->ss7.nationalprefix));
12369             ast_copy_string(ss7->ss7.subscriberprefix, conf->ss7.ss7.subscriberprefix, sizeof(ss7->ss7.subscriberprefix));
12370             ast_copy_string(ss7->ss7.unknownprefix, conf->ss7.ss7.unknownprefix, sizeof(ss7->ss7.unknownprefix));
12371 
12372             ss7->ss7.called_nai = conf->ss7.ss7.called_nai;
12373             ss7->ss7.calling_nai = conf->ss7.ss7.calling_nai;
12374          }
12375 #endif   /* defined(HAVE_SS7) */
12376 #ifdef HAVE_OPENR2
12377          if (chan_sig == SIG_MFCR2) {
12378             struct dahdi_mfcr2 *r2_link;
12379             r2_link = dahdi_r2_get_link();
12380             if (!r2_link) {
12381                ast_log(LOG_WARNING, "Cannot get another R2 DAHDI context!\n");
12382                destroy_dahdi_pvt(tmp);
12383                return NULL;
12384             }
12385             if (!r2_link->protocol_context && dahdi_r2_set_context(r2_link, conf)) {
12386                ast_log(LOG_ERROR, "Cannot create OpenR2 protocol context.\n");
12387                destroy_dahdi_pvt(tmp);
12388                return NULL;
12389             }
12390             if (r2_link->numchans == ARRAY_LEN(r2_link->pvts)) {
12391                ast_log(LOG_ERROR, "Cannot add more channels to this link!\n");
12392                destroy_dahdi_pvt(tmp);
12393                return NULL;
12394             }
12395             r2_link->pvts[r2_link->numchans++] = tmp;
12396             tmp->r2chan = openr2_chan_new_from_fd(r2_link->protocol_context,
12397                                         tmp->subs[SUB_REAL].dfd,
12398                                         NULL, NULL);
12399             if (!tmp->r2chan) {
12400                openr2_liberr_t err = openr2_context_get_last_error(r2_link->protocol_context);
12401                ast_log(LOG_ERROR, "Cannot create OpenR2 channel: %s\n", openr2_context_error_string(err));
12402                destroy_dahdi_pvt(tmp);
12403                return NULL;
12404             }
12405             tmp->mfcr2 = r2_link;
12406             if (conf->mfcr2.call_files) {
12407                openr2_chan_enable_call_files(tmp->r2chan);
12408             }
12409             openr2_chan_set_client_data(tmp->r2chan, tmp);
12410             /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
12411             openr2_chan_set_logging_func(tmp->r2chan, (openr2_logging_func_t)dahdi_r2_on_chan_log);
12412             openr2_chan_set_log_level(tmp->r2chan, conf->mfcr2.loglevel);
12413             tmp->mfcr2_category = conf->mfcr2.category;
12414             tmp->mfcr2_charge_calls = conf->mfcr2.charge_calls;
12415             tmp->mfcr2_allow_collect_calls = conf->mfcr2.allow_collect_calls;
12416             tmp->mfcr2_forced_release = conf->mfcr2.forced_release;
12417             tmp->mfcr2_accept_on_offer = conf->mfcr2.accept_on_offer;
12418             tmp->mfcr2call = 0;
12419             tmp->mfcr2_dnis_index = 0;
12420             tmp->mfcr2_ani_index = 0;
12421             r2_link->monitored_count++;
12422          }
12423 #endif
12424 #ifdef HAVE_PRI
12425          if (dahdi_sig_pri_lib_handles(chan_sig)) {
12426             int offset;
12427             int matchesdchan;
12428             int x,y;
12429             int myswitchtype = 0;
12430 
12431             offset = 0;
12432             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &offset)) {
12433                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
12434                destroy_dahdi_pvt(tmp);
12435                return NULL;
12436             }
12437             if (span >= NUM_SPANS) {
12438                ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
12439                destroy_dahdi_pvt(tmp);
12440                return NULL;
12441             } else {
12442                si.spanno = 0;
12443                if (ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SPANSTAT,&si) == -1) {
12444                   ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
12445                   destroy_dahdi_pvt(tmp);
12446                   return NULL;
12447                }
12448                /* Store the logical span first based upon the real span */
12449                tmp->logicalspan = pris[span].prilogicalspan;
12450                pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
12451                if (span < 0) {
12452                   ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
12453                   destroy_dahdi_pvt(tmp);
12454                   return NULL;
12455                }
12456                myswitchtype = conf->pri.pri.switchtype;
12457                /* Make sure this isn't a d-channel */
12458                matchesdchan=0;
12459                for (x = 0; x < NUM_SPANS; x++) {
12460                   for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
12461                      if (pris[x].dchannels[y] == tmp->channel) {
12462                         matchesdchan = 1;
12463                         break;
12464                      }
12465                   }
12466                }
12467                if (!matchesdchan) {
12468                   if (pris[span].pri.nodetype && (pris[span].pri.nodetype != conf->pri.pri.nodetype)) {
12469                      ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].pri.nodetype));
12470                      destroy_dahdi_pvt(tmp);
12471                      return NULL;
12472                   }
12473                   if (pris[span].pri.switchtype && (pris[span].pri.switchtype != myswitchtype)) {
12474                      ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].pri.switchtype));
12475                      destroy_dahdi_pvt(tmp);
12476                      return NULL;
12477                   }
12478                   if ((pris[span].pri.dialplan) && (pris[span].pri.dialplan != conf->pri.pri.dialplan)) {
12479                      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));
12480                      destroy_dahdi_pvt(tmp);
12481                      return NULL;
12482                   }
12483                   if (!ast_strlen_zero(pris[span].pri.idledial) && strcmp(pris[span].pri.idledial, conf->pri.pri.idledial)) {
12484                      ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf->pri.pri.idledial);
12485                      destroy_dahdi_pvt(tmp);
12486                      return NULL;
12487                   }
12488                   if (!ast_strlen_zero(pris[span].pri.idleext) && strcmp(pris[span].pri.idleext, conf->pri.pri.idleext)) {
12489                      ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf->pri.pri.idleext);
12490                      destroy_dahdi_pvt(tmp);
12491                      return NULL;
12492                   }
12493                   if (pris[span].pri.minunused && (pris[span].pri.minunused != conf->pri.pri.minunused)) {
12494                      ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf->pri.pri.minunused);
12495                      destroy_dahdi_pvt(tmp);
12496                      return NULL;
12497                   }
12498                   if (pris[span].pri.minidle && (pris[span].pri.minidle != conf->pri.pri.minidle)) {
12499                      ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf->pri.pri.minidle);
12500                      destroy_dahdi_pvt(tmp);
12501                      return NULL;
12502                   }
12503                   if (pris[span].pri.numchans >= ARRAY_LEN(pris[span].pri.pvts)) {
12504                      ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
12505                         pris[span].pri.trunkgroup);
12506                      destroy_dahdi_pvt(tmp);
12507                      return NULL;
12508                   }
12509 
12510                   ast_debug(4, "Adding callbacks %p to chan %d\n", &dahdi_pri_callbacks, tmp->channel);
12511                   pri_chan = sig_pri_chan_new(tmp, &dahdi_pri_callbacks, &pris[span].pri, tmp->logicalspan, p.chanpos, pris[span].mastertrunkgroup);
12512                   if (!pri_chan) {
12513                      destroy_dahdi_pvt(tmp);
12514                      return NULL;
12515                   }
12516                   tmp->sig_pvt = pri_chan;
12517                   tmp->pri = &pris[span].pri;
12518 
12519                   tmp->priexclusive = conf->chan.priexclusive;
12520 
12521                   if (!tmp->pri->cc_params) {
12522                      tmp->pri->cc_params = ast_cc_config_params_init();
12523                      if (!tmp->pri->cc_params) {
12524                         destroy_dahdi_pvt(tmp);
12525                         return NULL;
12526                      }
12527                   }
12528                   ast_cc_copy_config_params(tmp->pri->cc_params,
12529                      conf->chan.cc_params);
12530 
12531                   pris[span].pri.sig = chan_sig;
12532                   pris[span].pri.nodetype = conf->pri.pri.nodetype;
12533                   pris[span].pri.switchtype = myswitchtype;
12534                   pris[span].pri.nsf = conf->pri.pri.nsf;
12535                   pris[span].pri.dialplan = conf->pri.pri.dialplan;
12536                   pris[span].pri.localdialplan = conf->pri.pri.localdialplan;
12537                   pris[span].pri.pvts[pris[span].pri.numchans++] = tmp->sig_pvt;
12538                   pris[span].pri.minunused = conf->pri.pri.minunused;
12539                   pris[span].pri.minidle = conf->pri.pri.minidle;
12540                   pris[span].pri.overlapdial = conf->pri.pri.overlapdial;
12541                   pris[span].pri.qsigchannelmapping = conf->pri.pri.qsigchannelmapping;
12542                   pris[span].pri.discardremoteholdretrieval = conf->pri.pri.discardremoteholdretrieval;
12543 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12544                   pris[span].pri.enable_service_message_support = conf->pri.pri.enable_service_message_support;
12545 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
12546 #ifdef HAVE_PRI_INBANDDISCONNECT
12547                   pris[span].pri.inbanddisconnect = conf->pri.pri.inbanddisconnect;
12548 #endif
12549 #if defined(HAVE_PRI_CALL_HOLD)
12550                   pris[span].pri.hold_disconnect_transfer =
12551                      conf->pri.pri.hold_disconnect_transfer;
12552 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
12553 #if defined(HAVE_PRI_CCSS)
12554                   pris[span].pri.cc_ptmp_recall_mode =
12555                      conf->pri.pri.cc_ptmp_recall_mode;
12556                   pris[span].pri.cc_qsig_signaling_link_req =
12557                      conf->pri.pri.cc_qsig_signaling_link_req;
12558                   pris[span].pri.cc_qsig_signaling_link_rsp =
12559                      conf->pri.pri.cc_qsig_signaling_link_rsp;
12560 #endif   /* defined(HAVE_PRI_CCSS) */
12561 #if defined(HAVE_PRI_CALL_WAITING)
12562                   pris[span].pri.max_call_waiting_calls =
12563                      conf->pri.pri.max_call_waiting_calls;
12564                   pris[span].pri.allow_call_waiting_calls =
12565                      conf->pri.pri.allow_call_waiting_calls;
12566 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12567                   pris[span].pri.transfer = conf->chan.transfer;
12568                   pris[span].pri.facilityenable = conf->pri.pri.facilityenable;
12569 #if defined(HAVE_PRI_L2_PERSISTENCE)
12570                   pris[span].pri.l2_persistence = conf->pri.pri.l2_persistence;
12571 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
12572 #if defined(HAVE_PRI_AOC_EVENTS)
12573                   pris[span].pri.aoc_passthrough_flag = conf->pri.pri.aoc_passthrough_flag;
12574                   pris[span].pri.aoce_delayhangup = conf->pri.pri.aoce_delayhangup;
12575 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
12576                   pris[span].pri.append_msn_to_user_tag = conf->pri.pri.append_msn_to_user_tag;
12577                   ast_copy_string(pris[span].pri.initial_user_tag, conf->chan.cid_tag, sizeof(pris[span].pri.initial_user_tag));
12578                   ast_copy_string(pris[span].pri.msn_list, conf->pri.pri.msn_list, sizeof(pris[span].pri.msn_list));
12579 #if defined(HAVE_PRI_MWI)
12580                   ast_copy_string(pris[span].pri.mwi_mailboxes,
12581                      conf->pri.pri.mwi_mailboxes,
12582                      sizeof(pris[span].pri.mwi_mailboxes));
12583 #endif   /* defined(HAVE_PRI_MWI) */
12584                   ast_copy_string(pris[span].pri.idledial, conf->pri.pri.idledial, sizeof(pris[span].pri.idledial));
12585                   ast_copy_string(pris[span].pri.idleext, conf->pri.pri.idleext, sizeof(pris[span].pri.idleext));
12586                   ast_copy_string(pris[span].pri.internationalprefix, conf->pri.pri.internationalprefix, sizeof(pris[span].pri.internationalprefix));
12587                   ast_copy_string(pris[span].pri.nationalprefix, conf->pri.pri.nationalprefix, sizeof(pris[span].pri.nationalprefix));
12588                   ast_copy_string(pris[span].pri.localprefix, conf->pri.pri.localprefix, sizeof(pris[span].pri.localprefix));
12589                   ast_copy_string(pris[span].pri.privateprefix, conf->pri.pri.privateprefix, sizeof(pris[span].pri.privateprefix));
12590                   ast_copy_string(pris[span].pri.unknownprefix, conf->pri.pri.unknownprefix, sizeof(pris[span].pri.unknownprefix));
12591                   pris[span].pri.resetinterval = conf->pri.pri.resetinterval;
12592 
12593                   for (x = 0; x < PRI_MAX_TIMERS; x++) {
12594                      pris[span].pri.pritimers[x] = conf->pri.pri.pritimers[x];
12595                   }
12596 
12597 #if defined(HAVE_PRI_CALL_WAITING)
12598                   /* Channel initial config parameters. */
12599                   pris[span].pri.ch_cfg.stripmsd = conf->chan.stripmsd;
12600                   pris[span].pri.ch_cfg.hidecallerid = conf->chan.hidecallerid;
12601                   pris[span].pri.ch_cfg.hidecalleridname = conf->chan.hidecalleridname;
12602                   pris[span].pri.ch_cfg.immediate = conf->chan.immediate;
12603                   pris[span].pri.ch_cfg.priexclusive = conf->chan.priexclusive;
12604                   pris[span].pri.ch_cfg.priindication_oob = conf->chan.priindication_oob;
12605                   pris[span].pri.ch_cfg.use_callerid = conf->chan.use_callerid;
12606                   pris[span].pri.ch_cfg.use_callingpres = conf->chan.use_callingpres;
12607                   ast_copy_string(pris[span].pri.ch_cfg.context, conf->chan.context, sizeof(pris[span].pri.ch_cfg.context));
12608                   ast_copy_string(pris[span].pri.ch_cfg.mohinterpret, conf->chan.mohinterpret, sizeof(pris[span].pri.ch_cfg.mohinterpret));
12609 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12610                } else {
12611                   ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", p.chanpos);
12612                   destroy_dahdi_pvt(tmp);
12613                   return NULL;
12614                }
12615             }
12616          }
12617 #endif
12618       } else {
12619          /* already exists in interface list */
12620          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));
12621          chan_sig = tmp->sig;
12622          if (tmp->subs[SUB_REAL].dfd > -1) {
12623             memset(&p, 0, sizeof(p));
12624             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12625          }
12626       }
12627       /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
12628       switch (chan_sig) {
12629       case SIG_FXSKS:
12630       case SIG_FXSLS:
12631       case SIG_EM:
12632       case SIG_EM_E1:
12633       case SIG_EMWINK:
12634       case SIG_FEATD:
12635       case SIG_FEATDMF:
12636       case SIG_FEATDMF_TA:
12637       case SIG_FEATB:
12638       case SIG_E911:
12639       case SIG_SF:
12640       case SIG_SFWINK:
12641       case SIG_FGC_CAMA:
12642       case SIG_FGC_CAMAMF:
12643       case SIG_SF_FEATD:
12644       case SIG_SF_FEATDMF:
12645       case SIG_SF_FEATB:
12646          p.starttime = 250;
12647          break;
12648       }
12649 
12650       if (tmp->radio) {
12651          /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
12652          p.channo = channel;
12653          p.rxwinktime = 1;
12654          p.rxflashtime = 1;
12655          p.starttime = 1;
12656          p.debouncetime = 5;
12657       } else {
12658          p.channo = channel;
12659          /* Override timing settings based on config file */
12660          if (conf->timing.prewinktime >= 0)
12661             p.prewinktime = conf->timing.prewinktime;
12662          if (conf->timing.preflashtime >= 0)
12663             p.preflashtime = conf->timing.preflashtime;
12664          if (conf->timing.winktime >= 0)
12665             p.winktime = conf->timing.winktime;
12666          if (conf->timing.flashtime >= 0)
12667             p.flashtime = conf->timing.flashtime;
12668          if (conf->timing.starttime >= 0)
12669             p.starttime = conf->timing.starttime;
12670          if (conf->timing.rxwinktime >= 0)
12671             p.rxwinktime = conf->timing.rxwinktime;
12672          if (conf->timing.rxflashtime >= 0)
12673             p.rxflashtime = conf->timing.rxflashtime;
12674          if (conf->timing.debouncetime >= 0)
12675             p.debouncetime = conf->timing.debouncetime;
12676       }
12677 
12678       /* don't set parms on a pseudo-channel */
12679       if (tmp->subs[SUB_REAL].dfd >= 0)
12680       {
12681          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_PARAMS, &p);
12682          if (res < 0) {
12683             ast_log(LOG_ERROR, "Unable to set parameters: %s\n", strerror(errno));
12684             destroy_dahdi_pvt(tmp);
12685             return NULL;
12686          }
12687       }
12688 #if 1
12689       if (!here && (tmp->subs[SUB_REAL].dfd > -1)) {
12690          memset(&bi, 0, sizeof(bi));
12691          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
12692          if (!res) {
12693             bi.txbufpolicy = conf->chan.buf_policy;
12694             bi.rxbufpolicy = conf->chan.buf_policy;
12695             bi.numbufs = conf->chan.buf_no;
12696             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
12697             if (res < 0) {
12698                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", channel, strerror(errno));
12699             }
12700          } else {
12701             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", channel, strerror(errno));
12702          }
12703          tmp->buf_policy = conf->chan.buf_policy;
12704          tmp->buf_no = conf->chan.buf_no;
12705          tmp->usefaxbuffers = conf->chan.usefaxbuffers;
12706          tmp->faxbuf_policy = conf->chan.faxbuf_policy;
12707          tmp->faxbuf_no = conf->chan.faxbuf_no;
12708          /* This is not as gnarly as it may first appear.  If the ioctl above failed, we'd be setting
12709           * tmp->bufsize to zero which would cause subsequent faxbuffer-related ioctl calls to fail.
12710           * The reason the ioctl call above failed should to be determined before worrying about the
12711           * faxbuffer-related ioctl calls */
12712          tmp->bufsize = bi.bufsize;
12713       }
12714 #endif
12715       tmp->immediate = conf->chan.immediate;
12716       tmp->transfertobusy = conf->chan.transfertobusy;
12717       if (chan_sig & __DAHDI_SIG_FXS) {
12718          tmp->mwimonitor_fsk = conf->chan.mwimonitor_fsk;
12719          tmp->mwimonitor_neon = conf->chan.mwimonitor_neon;
12720          tmp->mwimonitor_rpas = conf->chan.mwimonitor_rpas;
12721       }
12722       tmp->ringt_base = ringt_base;
12723       tmp->firstradio = 0;
12724       if ((chan_sig == SIG_FXOKS) || (chan_sig == SIG_FXOLS) || (chan_sig == SIG_FXOGS))
12725          tmp->permcallwaiting = conf->chan.callwaiting;
12726       else
12727          tmp->permcallwaiting = 0;
12728       /* Flag to destroy the channel must be cleared on new mkif.  Part of changes for reload to work */
12729       tmp->destroy = 0;
12730       tmp->drings = conf->chan.drings;
12731 
12732       /* 10 is a nice default. */
12733       if (tmp->drings.ringnum[0].range == 0)
12734          tmp->drings.ringnum[0].range = 10;
12735       if (tmp->drings.ringnum[1].range == 0)
12736          tmp->drings.ringnum[1].range = 10;
12737       if (tmp->drings.ringnum[2].range == 0)
12738          tmp->drings.ringnum[2].range = 10;
12739 
12740       tmp->usedistinctiveringdetection = usedistinctiveringdetection;
12741       tmp->callwaitingcallerid = conf->chan.callwaitingcallerid;
12742       tmp->threewaycalling = conf->chan.threewaycalling;
12743       tmp->adsi = conf->chan.adsi;
12744       tmp->use_smdi = conf->chan.use_smdi;
12745       tmp->permhidecallerid = conf->chan.hidecallerid;
12746       tmp->hidecalleridname = conf->chan.hidecalleridname;
12747       tmp->callreturn = conf->chan.callreturn;
12748       tmp->echocancel = conf->chan.echocancel;
12749       tmp->echotraining = conf->chan.echotraining;
12750       tmp->pulse = conf->chan.pulse;
12751       if (tmp->echocancel.head.tap_length) {
12752          tmp->echocanbridged = conf->chan.echocanbridged;
12753       } else {
12754          if (conf->chan.echocanbridged)
12755             ast_log(LOG_NOTICE, "echocancelwhenbridged requires echocancel to be enabled; ignoring\n");
12756          tmp->echocanbridged = 0;
12757       }
12758       tmp->busydetect = conf->chan.busydetect;
12759       tmp->busycount = conf->chan.busycount;
12760       tmp->busy_tonelength = conf->chan.busy_tonelength;
12761       tmp->busy_quietlength = conf->chan.busy_quietlength;
12762       tmp->callprogress = conf->chan.callprogress;
12763       tmp->waitfordialtone = conf->chan.waitfordialtone;
12764       tmp->cancallforward = conf->chan.cancallforward;
12765       tmp->dtmfrelax = conf->chan.dtmfrelax;
12766       tmp->callwaiting = tmp->permcallwaiting;
12767       tmp->hidecallerid = tmp->permhidecallerid;
12768       tmp->channel = channel;
12769       tmp->stripmsd = conf->chan.stripmsd;
12770       tmp->use_callerid = conf->chan.use_callerid;
12771       tmp->cid_signalling = conf->chan.cid_signalling;
12772       tmp->cid_start = conf->chan.cid_start;
12773       tmp->dahditrcallerid = conf->chan.dahditrcallerid;
12774       tmp->restrictcid = conf->chan.restrictcid;
12775       tmp->use_callingpres = conf->chan.use_callingpres;
12776       if (tmp->usedistinctiveringdetection) {
12777          if (!tmp->use_callerid) {
12778             ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
12779             tmp->use_callerid = 1;
12780          }
12781       }
12782 
12783       if (tmp->cid_signalling == CID_SIG_SMDI) {
12784          if (!tmp->use_smdi) {
12785             ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
12786             tmp->use_smdi = 1;
12787          }
12788       }
12789       if (tmp->use_smdi) {
12790          tmp->smdi_iface = ast_smdi_interface_find(conf->smdi_port);
12791          if (!(tmp->smdi_iface)) {
12792             ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
12793             tmp->use_smdi = 0;
12794          }
12795       }
12796 
12797       ast_copy_string(tmp->accountcode, conf->chan.accountcode, sizeof(tmp->accountcode));
12798       tmp->amaflags = conf->chan.amaflags;
12799       if (!here) {
12800          tmp->confno = -1;
12801          tmp->propconfno = -1;
12802       }
12803       tmp->canpark = conf->chan.canpark;
12804       tmp->transfer = conf->chan.transfer;
12805       ast_copy_string(tmp->defcontext,conf->chan.context,sizeof(tmp->defcontext));
12806       ast_copy_string(tmp->language, conf->chan.language, sizeof(tmp->language));
12807       ast_copy_string(tmp->mohinterpret, conf->chan.mohinterpret, sizeof(tmp->mohinterpret));
12808       ast_copy_string(tmp->mohsuggest, conf->chan.mohsuggest, sizeof(tmp->mohsuggest));
12809       ast_copy_string(tmp->context, conf->chan.context, sizeof(tmp->context));
12810       ast_copy_string(tmp->parkinglot, conf->chan.parkinglot, sizeof(tmp->parkinglot));
12811       tmp->cid_ton = 0;
12812       if (analog_lib_handles(tmp->sig, tmp->radio, tmp->oprmode)) {
12813          ast_copy_string(tmp->cid_num, conf->chan.cid_num, sizeof(tmp->cid_num));
12814          ast_copy_string(tmp->cid_name, conf->chan.cid_name, sizeof(tmp->cid_name));
12815       } else {
12816          tmp->cid_num[0] = '\0';
12817          tmp->cid_name[0] = '\0';
12818       }
12819 #if defined(HAVE_PRI)
12820       if (dahdi_sig_pri_lib_handles(tmp->sig)) {
12821          tmp->cid_tag[0] = '\0';
12822       } else
12823 #endif   /* defined(HAVE_PRI) */
12824       {
12825          ast_copy_string(tmp->cid_tag, conf->chan.cid_tag, sizeof(tmp->cid_tag));
12826       }
12827       tmp->cid_subaddr[0] = '\0';
12828       ast_copy_string(tmp->mailbox, conf->chan.mailbox, sizeof(tmp->mailbox));
12829       if (channel != CHAN_PSEUDO && !ast_strlen_zero(tmp->mailbox)) {
12830          char *mailbox, *context;
12831          mailbox = context = ast_strdupa(tmp->mailbox);
12832          strsep(&context, "@");
12833          if (ast_strlen_zero(context))
12834             context = "default";
12835          tmp->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "Dahdi MWI subscription", NULL,
12836             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12837             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12838             AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
12839             AST_EVENT_IE_END);
12840       }
12841 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
12842       tmp->mwisend_setting = conf->chan.mwisend_setting;
12843       tmp->mwisend_fsk  = conf->chan.mwisend_fsk;
12844       tmp->mwisend_rpas = conf->chan.mwisend_rpas;
12845 #endif
12846 
12847       tmp->group = conf->chan.group;
12848       tmp->callgroup = conf->chan.callgroup;
12849       tmp->pickupgroup= conf->chan.pickupgroup;
12850       if (conf->chan.vars) {
12851          struct ast_variable *v, *tmpvar;
12852                    for (v = conf->chan.vars ; v ; v = v->next) {
12853                          if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
12854                                   tmpvar->next = tmp->vars;
12855                                    tmp->vars = tmpvar;
12856                            }
12857                   }
12858       }
12859       tmp->cid_rxgain = conf->chan.cid_rxgain;
12860       tmp->rxgain = conf->chan.rxgain;
12861       tmp->txgain = conf->chan.txgain;
12862       tmp->txdrc = conf->chan.txdrc;
12863       tmp->rxdrc = conf->chan.rxdrc;
12864       tmp->tonezone = conf->chan.tonezone;
12865       if (tmp->subs[SUB_REAL].dfd > -1) {
12866          set_actual_gain(tmp->subs[SUB_REAL].dfd, tmp->rxgain, tmp->txgain, tmp->rxdrc, tmp->txdrc, tmp->law);
12867          if (tmp->dsp)
12868             ast_dsp_set_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
12869          update_conf(tmp);
12870          if (!here) {
12871             switch (chan_sig) {
12872             case SIG_PRI_LIB_HANDLE_CASES:
12873             case SIG_SS7:
12874             case SIG_MFCR2:
12875                break;
12876             default:
12877                /* Hang it up to be sure it's good */
12878                dahdi_set_hook(tmp->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
12879                break;
12880             }
12881          }
12882          ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SETTONEZONE,&tmp->tonezone);
12883          if ((res = get_alarms(tmp)) != DAHDI_ALARM_NONE) {
12884             /* the dchannel is down so put the channel in alarm */
12885             switch (tmp->sig) {
12886 #ifdef HAVE_PRI
12887             case SIG_PRI_LIB_HANDLE_CASES:
12888                sig_pri_set_alarm(tmp->sig_pvt, 1);
12889                break;
12890 #endif
12891 #if defined(HAVE_SS7)
12892             case SIG_SS7:
12893                sig_ss7_set_alarm(tmp->sig_pvt, 1);
12894                break;
12895 #endif   /* defined(HAVE_SS7) */
12896             default:
12897                /* The only sig submodule left should be sig_analog. */
12898                analog_p = tmp->sig_pvt;
12899                if (analog_p) {
12900                   analog_p->inalarm = 1;
12901                }
12902                tmp->inalarm = 1;
12903                break;
12904             }
12905             handle_alarms(tmp, res);
12906          }
12907       }
12908 
12909       tmp->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
12910       tmp->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
12911       tmp->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
12912       tmp->sendcalleridafter = conf->chan.sendcalleridafter;
12913       ast_cc_copy_config_params(tmp->cc_params, conf->chan.cc_params);
12914 
12915       if (!here) {
12916          tmp->locallyblocked = 0;
12917          tmp->remotelyblocked = 0;
12918          switch (tmp->sig) {
12919 #if defined(HAVE_PRI)
12920          case SIG_PRI_LIB_HANDLE_CASES:
12921             tmp->inservice = 1;/* Inservice until actually implemented. */
12922 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12923             ((struct sig_pri_chan *) tmp->sig_pvt)->service_status = 0;
12924             if (chan_sig == SIG_PRI) {
12925                char db_chan_name[20];
12926                char db_answer[5];
12927 
12928                /*
12929                 * Initialize the active out-of-service status
12930                 * and delete any record if the feature is not enabled.
12931                 */
12932                snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, tmp->channel);
12933                if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
12934                   unsigned *why;
12935 
12936                   why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
12937                   if (tmp->pri->enable_service_message_support) {
12938                      char state;
12939 
12940                      sscanf(db_answer, "%1c:%30u", &state, why);
12941 
12942                      /* Ensure that only the implemented bits could be set.*/
12943                      *why &= (SRVST_NEAREND | SRVST_FAREND);
12944                   }
12945                   if (!*why) {
12946                      ast_db_del(db_chan_name, SRVST_DBKEY);
12947                   }
12948                }
12949             }
12950 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
12951             break;
12952 #endif   /* defined(HAVE_PRI) */
12953 #if defined(HAVE_SS7)
12954          case SIG_SS7:
12955             tmp->inservice = 0;
12956             break;
12957 #endif   /* defined(HAVE_SS7) */
12958          default:
12959              /* We default to in service on protocols that don't have a reset */
12960             tmp->inservice = 1;
12961             break;
12962          }
12963       }
12964 
12965       switch (tmp->sig) {
12966 #if defined(HAVE_PRI)
12967       case SIG_PRI_LIB_HANDLE_CASES:
12968          if (pri_chan) {
12969             pri_chan->channel = tmp->channel;
12970             pri_chan->hidecallerid = tmp->hidecallerid;
12971             pri_chan->hidecalleridname = tmp->hidecalleridname;
12972             pri_chan->immediate = tmp->immediate;
12973             pri_chan->inalarm = tmp->inalarm;
12974             pri_chan->priexclusive = tmp->priexclusive;
12975             pri_chan->priindication_oob = tmp->priindication_oob;
12976             pri_chan->use_callerid = tmp->use_callerid;
12977             pri_chan->use_callingpres = tmp->use_callingpres;
12978             ast_copy_string(pri_chan->context, tmp->context,
12979                sizeof(pri_chan->context));
12980             ast_copy_string(pri_chan->mohinterpret, tmp->mohinterpret,
12981                sizeof(pri_chan->mohinterpret));
12982             pri_chan->stripmsd = tmp->stripmsd;
12983          }
12984          break;
12985 #endif   /* defined(HAVE_PRI) */
12986 #if defined(HAVE_SS7)
12987       case SIG_SS7:
12988          if (ss7_chan) {
12989             ss7_chan->inalarm = tmp->inalarm;
12990 
12991             ss7_chan->stripmsd = tmp->stripmsd;
12992             ss7_chan->hidecallerid = tmp->hidecallerid;
12993             ss7_chan->use_callerid = tmp->use_callerid;
12994             ss7_chan->use_callingpres = tmp->use_callingpres;
12995             ss7_chan->immediate = tmp->immediate;
12996             ss7_chan->locallyblocked = tmp->locallyblocked;
12997             ss7_chan->remotelyblocked = tmp->remotelyblocked;
12998             ast_copy_string(ss7_chan->context, tmp->context,
12999                sizeof(ss7_chan->context));
13000             ast_copy_string(ss7_chan->mohinterpret, tmp->mohinterpret,
13001                sizeof(ss7_chan->mohinterpret));
13002          }
13003          break;
13004 #endif   /* defined(HAVE_SS7) */
13005       default:
13006          /* The only sig submodule left should be sig_analog. */
13007          analog_p = tmp->sig_pvt;
13008          if (analog_p) {
13009             analog_p->channel = tmp->channel;
13010             analog_p->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
13011             analog_p->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
13012             analog_p->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
13013             analog_p->permcallwaiting = conf->chan.callwaiting; /* permcallwaiting possibly modified in analog_config_complete */
13014             analog_p->callreturn = conf->chan.callreturn;
13015             analog_p->cancallforward = conf->chan.cancallforward;
13016             analog_p->canpark = conf->chan.canpark;
13017             analog_p->dahditrcallerid = conf->chan.dahditrcallerid;
13018             analog_p->immediate = conf->chan.immediate;
13019             analog_p->permhidecallerid = conf->chan.permhidecallerid;
13020             analog_p->pulse = conf->chan.pulse;
13021             analog_p->threewaycalling = conf->chan.threewaycalling;
13022             analog_p->transfer = conf->chan.transfer;
13023             analog_p->transfertobusy = conf->chan.transfertobusy;
13024             analog_p->use_callerid = tmp->use_callerid;
13025             analog_p->use_smdi = tmp->use_smdi;
13026             analog_p->smdi_iface = tmp->smdi_iface;
13027             analog_p->outsigmod = ANALOG_SIG_NONE;
13028             analog_p->echotraining = conf->chan.echotraining;
13029             analog_p->cid_signalling = conf->chan.cid_signalling;
13030             analog_p->stripmsd = conf->chan.stripmsd;
13031             switch (conf->chan.cid_start) {
13032             case CID_START_POLARITY:
13033                analog_p->cid_start = ANALOG_CID_START_POLARITY;
13034                break;
13035             case CID_START_POLARITY_IN:
13036                analog_p->cid_start = ANALOG_CID_START_POLARITY_IN;
13037                break;
13038             case CID_START_DTMF_NOALERT:
13039                analog_p->cid_start = ANALOG_CID_START_DTMF_NOALERT;
13040                break;
13041             default:
13042                analog_p->cid_start = ANALOG_CID_START_RING;
13043                break;
13044             }
13045             analog_p->callwaitingcallerid = conf->chan.callwaitingcallerid;
13046             analog_p->ringt = conf->chan.ringt;
13047             analog_p->ringt_base = ringt_base;
13048             analog_p->chan_tech = &dahdi_tech;
13049             analog_p->onhooktime = time(NULL);
13050             if (chan_sig & __DAHDI_SIG_FXO) {
13051                memset(&p, 0, sizeof(p));
13052                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
13053                if (!res) {
13054                   analog_p->fxsoffhookstate = p.rxisoffhook;
13055                }
13056 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
13057                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_VMWI_CONFIG, &tmp->mwisend_setting);
13058 #endif
13059             }
13060             analog_p->msgstate = -1;
13061 
13062             ast_copy_string(analog_p->mohsuggest, conf->chan.mohsuggest, sizeof(analog_p->mohsuggest));
13063             ast_copy_string(analog_p->cid_num, conf->chan.cid_num, sizeof(analog_p->cid_num));
13064             ast_copy_string(analog_p->cid_name, conf->chan.cid_name, sizeof(analog_p->cid_name));
13065 
13066             analog_config_complete(analog_p);
13067          }
13068          break;
13069       }
13070 #if defined(HAVE_PRI)
13071       if (tmp->channel == CHAN_PSEUDO) {
13072          /*
13073           * Save off pseudo channel buffer policy values for dynamic creation of
13074           * no B channel interfaces.
13075           */
13076          dahdi_pseudo_parms.buf_no = tmp->buf_no;
13077          dahdi_pseudo_parms.buf_policy = tmp->buf_policy;
13078          dahdi_pseudo_parms.faxbuf_no = tmp->faxbuf_no;
13079          dahdi_pseudo_parms.faxbuf_policy = tmp->faxbuf_policy;
13080       }
13081 #endif   /* defined(HAVE_PRI) */
13082    }
13083    if (tmp && !here) {
13084       /* Add the new channel interface to the sorted channel interface list. */
13085       dahdi_iflist_insert(tmp);
13086    }
13087    return tmp;
13088 }
13089 
13090 static int is_group_or_channel_match(struct dahdi_pvt *p, int span, ast_group_t groupmatch, int *groupmatched, int channelmatch, int *channelmatched)
13091 {
13092 #if defined(HAVE_PRI)
13093    if (0 < span) {
13094       /* The channel must be on the specified PRI span. */
13095       if (!p->pri || p->pri->span != span) {
13096          return 0;
13097       }
13098       if (!groupmatch && channelmatch == -1) {
13099          /* Match any group since it only needs to be on the PRI span. */
13100          *groupmatched = 1;
13101          return 1;
13102       }
13103    }
13104 #endif   /* defined(HAVE_PRI) */
13105    /* check group matching */
13106    if (groupmatch) {
13107       if ((p->group & groupmatch) != groupmatch)
13108          /* Doesn't match the specified group, try the next one */
13109          return 0;
13110       *groupmatched = 1;
13111    }
13112    /* Check to see if we have a channel match */
13113    if (channelmatch != -1) {
13114       if (p->channel != channelmatch)
13115          /* Doesn't match the specified channel, try the next one */
13116          return 0;
13117       *channelmatched = 1;
13118    }
13119 
13120    return 1;
13121 }
13122 
13123 static int available(struct dahdi_pvt **pvt, int is_specific_channel)
13124 {
13125    struct dahdi_pvt *p = *pvt;
13126 
13127    if (p->inalarm)
13128       return 0;
13129 
13130    if (analog_lib_handles(p->sig, p->radio, p->oprmode))
13131       return analog_available(p->sig_pvt);
13132 
13133    switch (p->sig) {
13134 #if defined(HAVE_PRI)
13135    case SIG_PRI_LIB_HANDLE_CASES:
13136       {
13137          struct sig_pri_chan *pvt_chan;
13138          int res;
13139 
13140          pvt_chan = p->sig_pvt;
13141          res = sig_pri_available(&pvt_chan, is_specific_channel);
13142          *pvt = pvt_chan->chan_pvt;
13143          return res;
13144       }
13145 #endif   /* defined(HAVE_PRI) */
13146 #if defined(HAVE_SS7)
13147    case SIG_SS7:
13148       return sig_ss7_available(p->sig_pvt);
13149 #endif   /* defined(HAVE_SS7) */
13150    default:
13151       break;
13152    }
13153 
13154    if (p->locallyblocked || p->remotelyblocked) {
13155       return 0;
13156    }
13157 
13158    /* If no owner definitely available */
13159    if (!p->owner) {
13160 #ifdef HAVE_OPENR2
13161       /* Trust MFC/R2 */
13162       if (p->mfcr2) {
13163          if (p->mfcr2call) {
13164             return 0;
13165          } else {
13166             return 1;
13167          }
13168       }
13169 #endif
13170       return 1;
13171    }
13172 
13173    return 0;
13174 }
13175 
13176 #if defined(HAVE_PRI)
13177 #if defined(HAVE_PRI_CALL_WAITING)
13178 /*!
13179  * \internal
13180  * \brief Init the private channel configuration using the span controller.
13181  * \since 1.8
13182  *
13183  * \param priv Channel to init the configuration.
13184  * \param pri sig_pri PRI control structure.
13185  *
13186  * \note Assumes the pri->lock is already obtained.
13187  *
13188  * \return Nothing
13189  */
13190 static void my_pri_init_config(void *priv, struct sig_pri_span *pri)
13191 {
13192    struct dahdi_pvt *pvt = priv;
13193 
13194    pvt->stripmsd = pri->ch_cfg.stripmsd;
13195    pvt->hidecallerid = pri->ch_cfg.hidecallerid;
13196    pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
13197    pvt->immediate = pri->ch_cfg.immediate;
13198    pvt->priexclusive = pri->ch_cfg.priexclusive;
13199    pvt->priindication_oob = pri->ch_cfg.priindication_oob;
13200    pvt->use_callerid = pri->ch_cfg.use_callerid;
13201    pvt->use_callingpres = pri->ch_cfg.use_callingpres;
13202    ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
13203    ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
13204 }
13205 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13206 #endif   /* defined(HAVE_PRI) */
13207 
13208 #if defined(HAVE_PRI)
13209 /*!
13210  * \internal
13211  * \brief Create a no B channel interface.
13212  * \since 1.8
13213  *
13214  * \param pri sig_pri span controller to add interface.
13215  *
13216  * \note Assumes the pri->lock is already obtained.
13217  *
13218  * \retval array-index into private pointer array on success.
13219  * \retval -1 on error.
13220  */
13221 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri)
13222 {
13223    int pvt_idx;
13224    int res;
13225    unsigned idx;
13226    struct dahdi_pvt *pvt;
13227    struct sig_pri_chan *chan;
13228    struct dahdi_bufferinfo bi;
13229 
13230    static int nobch_channel = CHAN_PSEUDO;
13231 
13232    /* Find spot in the private pointer array for new interface. */
13233    for (pvt_idx = 0; pvt_idx < pri->numchans; ++pvt_idx) {
13234       if (!pri->pvts[pvt_idx]) {
13235          break;
13236       }
13237    }
13238    if (pri->numchans == pvt_idx) {
13239       if (ARRAY_LEN(pri->pvts) <= pvt_idx) {
13240          ast_log(LOG_ERROR, "Unable to add a no-B-channel interface!\n");
13241          return -1;
13242       }
13243 
13244       /* Add new spot to the private pointer array. */
13245       pri->pvts[pvt_idx] = NULL;
13246       ++pri->numchans;
13247    }
13248 
13249    pvt = ast_calloc(1, sizeof(*pvt));
13250    if (!pvt) {
13251       return -1;
13252    }
13253    pvt->cc_params = ast_cc_config_params_init();
13254    if (!pvt->cc_params) {
13255       ast_free(pvt);
13256       return -1;
13257    }
13258    ast_mutex_init(&pvt->lock);
13259    for (idx = 0; idx < ARRAY_LEN(pvt->subs); ++idx) {
13260       pvt->subs[idx].dfd = -1;
13261    }
13262    pvt->buf_no = dahdi_pseudo_parms.buf_no;
13263    pvt->buf_policy = dahdi_pseudo_parms.buf_policy;
13264    pvt->faxbuf_no = dahdi_pseudo_parms.faxbuf_no;
13265    pvt->faxbuf_policy = dahdi_pseudo_parms.faxbuf_policy;
13266 
13267    chan = sig_pri_chan_new(pvt, &dahdi_pri_callbacks, pri, 0, 0, 0);
13268    if (!chan) {
13269       destroy_dahdi_pvt(pvt);
13270       return -1;
13271    }
13272    chan->no_b_channel = 1;
13273 
13274    /*
13275     * Pseudo channel companding law.
13276     * Needed for outgoing call waiting calls.
13277     * XXX May need to make this determined by switchtype or user option.
13278     */
13279    pvt->law_default = DAHDI_LAW_ALAW;
13280 
13281    pvt->sig = pri->sig;
13282    pvt->outsigmod = -1;
13283    pvt->pri = pri;
13284    pvt->sig_pvt = chan;
13285    pri->pvts[pvt_idx] = chan;
13286 
13287    pvt->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
13288    if (pvt->subs[SUB_REAL].dfd < 0) {
13289       ast_log(LOG_ERROR, "Unable to open no B channel interface pseudo channel: %s\n",
13290          strerror(errno));
13291       destroy_dahdi_pvt(pvt);
13292       return -1;
13293    }
13294    memset(&bi, 0, sizeof(bi));
13295    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
13296    if (!res) {
13297       pvt->bufsize = bi.bufsize;
13298       bi.txbufpolicy = pvt->buf_policy;
13299       bi.rxbufpolicy = pvt->buf_policy;
13300       bi.numbufs = pvt->buf_no;
13301       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
13302       if (res < 0) {
13303          ast_log(LOG_WARNING,
13304             "Unable to set buffer policy on no B channel interface: %s\n",
13305             strerror(errno));
13306       }
13307    } else
13308       ast_log(LOG_WARNING,
13309          "Unable to check buffer policy on no B channel interface: %s\n",
13310          strerror(errno));
13311 
13312    --nobch_channel;
13313    if (CHAN_PSEUDO < nobch_channel) {
13314       nobch_channel = CHAN_PSEUDO - 1;
13315    }
13316    pvt->channel = nobch_channel;
13317    pvt->span = pri->span;
13318    chan->channel = pvt->channel;
13319 
13320    dahdi_nobch_insert(pri, pvt);
13321 
13322    return pvt_idx;
13323 }
13324 #endif   /* defined(HAVE_PRI) */
13325 
13326 /* This function can *ONLY* be used for copying pseudo (CHAN_PSEUDO) private
13327    structures; it makes no attempt to safely copy regular channel private
13328    structures that might contain reference-counted object pointers and other
13329    scary bits
13330 */
13331 static struct dahdi_pvt *duplicate_pseudo(struct dahdi_pvt *src)
13332 {
13333    struct dahdi_pvt *p;
13334    struct dahdi_bufferinfo bi;
13335    int res;
13336 
13337    p = ast_malloc(sizeof(*p));
13338    if (!p) {
13339       return NULL;
13340    }
13341    *p = *src;
13342 
13343    /* Must deep copy the cc_params. */
13344    p->cc_params = ast_cc_config_params_init();
13345    if (!p->cc_params) {
13346       ast_free(p);
13347       return NULL;
13348    }
13349    ast_cc_copy_config_params(p->cc_params, src->cc_params);
13350 
13351    p->which_iflist = DAHDI_IFLIST_NONE;
13352    p->next = NULL;
13353    p->prev = NULL;
13354    ast_mutex_init(&p->lock);
13355    p->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
13356    if (p->subs[SUB_REAL].dfd < 0) {
13357       ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
13358       destroy_dahdi_pvt(p);
13359       return NULL;
13360    }
13361    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
13362    if (!res) {
13363       bi.txbufpolicy = src->buf_policy;
13364       bi.rxbufpolicy = src->buf_policy;
13365       bi.numbufs = src->buf_no;
13366       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
13367       if (res < 0) {
13368          ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel: %s\n", strerror(errno));
13369       }
13370    } else
13371       ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel: %s\n", strerror(errno));
13372    p->destroy = 1;
13373    dahdi_iflist_insert(p);
13374    return p;
13375 }
13376 
13377 struct dahdi_starting_point {
13378    /*! Group matching mask.  Zero if not specified. */
13379    ast_group_t groupmatch;
13380    /*! DAHDI channel to match with.  -1 if not specified. */
13381    int channelmatch;
13382    /*! Round robin saved search location index. (Valid if roundrobin TRUE) */
13383    int rr_starting_point;
13384    /*! ISDN span where channels can be picked (Zero if not specified) */
13385    int span;
13386    /*! Analog channel distinctive ring cadance index. */
13387    int cadance;
13388    /*! Dialing option. c/r/d if present and valid. */
13389    char opt;
13390    /*! TRUE if to search the channel list backwards. */
13391    char backwards;
13392    /*! TRUE if search is done with round robin sequence. */
13393    char roundrobin;
13394 };
13395 static struct dahdi_pvt *determine_starting_point(const char *data, struct dahdi_starting_point *param)
13396 {
13397    char *dest;
13398    char *s;
13399    int x;
13400    int res = 0;
13401    struct dahdi_pvt *p;
13402    char *subdir = NULL;
13403    AST_DECLARE_APP_ARGS(args,
13404       AST_APP_ARG(group);  /* channel/group token */
13405       //AST_APP_ARG(ext);  /* extension token */
13406       //AST_APP_ARG(opts); /* options token */
13407       AST_APP_ARG(other);  /* Any remining unused arguments */
13408    );
13409 
13410    /*
13411     * data is ---v
13412     * Dial(DAHDI/pseudo[/extension[/options]])
13413     * Dial(DAHDI/<channel#>[c|r<cadance#>|d][/extension[/options]])
13414     * Dial(DAHDI/<subdir>!<channel#>[c|r<cadance#>|d][/extension[/options]])
13415     * Dial(DAHDI/i<span>[/extension[/options]])
13416     * Dial(DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]])
13417     *
13418     * i - ISDN span channel restriction.
13419     *     Used by CC to ensure that the CC recall goes out the same span.
13420     *     Also to make ISDN channel names dialable when the sequence number
13421     *     is stripped off.  (Used by DTMF attended transfer feature.)
13422     *
13423     * g - channel group allocation search forward
13424     * G - channel group allocation search backward
13425     * r - channel group allocation round robin search forward
13426     * R - channel group allocation round robin search backward
13427     *
13428     * c - Wait for DTMF digit to confirm answer
13429     * r<cadance#> - Set distintive ring cadance number
13430     * d - Force bearer capability for ISDN/SS7 call to digital.
13431     */
13432 
13433    if (data) {
13434       dest = ast_strdupa(data);
13435    } else {
13436       ast_log(LOG_WARNING, "Channel requested with no data\n");
13437       return NULL;
13438    }
13439    AST_NONSTANDARD_APP_ARGS(args, dest, '/');
13440    if (!args.argc || ast_strlen_zero(args.group)) {
13441       ast_log(LOG_WARNING, "No channel/group specified\n");
13442       return NULL;
13443    }
13444 
13445    /* Initialize the output parameters */
13446    memset(param, 0, sizeof(*param));
13447    param->channelmatch = -1;
13448 
13449    if (strchr(args.group, '!') != NULL) {
13450       char *prev = args.group;
13451       while ((s = strchr(prev, '!')) != NULL) {
13452          *s++ = '/';
13453          prev = s;
13454       }
13455       *(prev - 1) = '\0';
13456       subdir = args.group;
13457       args.group = prev;
13458    } else if (args.group[0] == 'i') {
13459       /* Extract the ISDN span channel restriction specifier. */
13460       res = sscanf(args.group + 1, "%30d", &x);
13461       if (res < 1) {
13462          ast_log(LOG_WARNING, "Unable to determine ISDN span for data %s\n", data);
13463          return NULL;
13464       }
13465       param->span = x;
13466 
13467       /* Remove the ISDN span channel restriction specifier. */
13468       s = strchr(args.group, '-');
13469       if (!s) {
13470          /* Search all groups since we are ISDN span restricted. */
13471          return iflist;
13472       }
13473       args.group = s + 1;
13474       res = 0;
13475    }
13476    if (toupper(args.group[0]) == 'G' || toupper(args.group[0])=='R') {
13477       /* Retrieve the group number */
13478       s = args.group + 1;
13479       res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13480       if (res < 1) {
13481          ast_log(LOG_WARNING, "Unable to determine group for data %s\n", data);
13482          return NULL;
13483       }
13484       param->groupmatch = ((ast_group_t) 1 << x);
13485 
13486       if (toupper(args.group[0]) == 'G') {
13487          if (args.group[0] == 'G') {
13488             param->backwards = 1;
13489             p = ifend;
13490          } else
13491             p = iflist;
13492       } else {
13493          if (ARRAY_LEN(round_robin) <= x) {
13494             ast_log(LOG_WARNING, "Round robin index %d out of range for data %s\n",
13495                x, data);
13496             return NULL;
13497          }
13498          if (args.group[0] == 'R') {
13499             param->backwards = 1;
13500             p = round_robin[x] ? round_robin[x]->prev : ifend;
13501             if (!p)
13502                p = ifend;
13503          } else {
13504             p = round_robin[x] ? round_robin[x]->next : iflist;
13505             if (!p)
13506                p = iflist;
13507          }
13508          param->roundrobin = 1;
13509          param->rr_starting_point = x;
13510       }
13511    } else {
13512       s = args.group;
13513       if (!strcasecmp(s, "pseudo")) {
13514          /* Special case for pseudo */
13515          x = CHAN_PSEUDO;
13516          param->channelmatch = x;
13517       } else {
13518          res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13519          if (res < 1) {
13520             ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", data);
13521             return NULL;
13522          } else {
13523             param->channelmatch = x;
13524          }
13525       }
13526       if (subdir) {
13527          char path[PATH_MAX];
13528          struct stat stbuf;
13529 
13530          snprintf(path, sizeof(path), "/dev/dahdi/%s/%d",
13531                subdir, param->channelmatch);
13532          if (stat(path, &stbuf) < 0) {
13533             ast_log(LOG_WARNING, "stat(%s) failed: %s\n",
13534                   path, strerror(errno));
13535             return NULL;
13536          }
13537          if (!S_ISCHR(stbuf.st_mode)) {
13538             ast_log(LOG_ERROR, "%s: Not a character device file\n",
13539                   path);
13540             return NULL;
13541          }
13542          param->channelmatch = minor(stbuf.st_rdev);
13543       }
13544 
13545       p = iflist;
13546    }
13547 
13548    if (param->opt == 'r' && res < 3) {
13549       ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", data);
13550       param->opt = '\0';
13551    }
13552 
13553    return p;
13554 }
13555 
13556 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
13557 {
13558    int callwait = 0;
13559    struct dahdi_pvt *p;
13560    struct ast_channel *tmp = NULL;
13561    struct dahdi_pvt *exitpvt;
13562    int channelmatched = 0;
13563    int groupmatched = 0;
13564 #if defined(HAVE_PRI) || defined(HAVE_SS7)
13565    int transcapdigital = 0;
13566 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
13567    struct dahdi_starting_point start;
13568 
13569    ast_mutex_lock(&iflock);
13570    p = determine_starting_point(data, &start);
13571    if (!p) {
13572       /* We couldn't determine a starting point, which likely means badly-formatted channel name. Abort! */
13573       ast_mutex_unlock(&iflock);
13574       return NULL;
13575    }
13576 
13577    /* Search for an unowned channel */
13578    exitpvt = p;
13579    while (p && !tmp) {
13580       if (start.roundrobin)
13581          round_robin[start.rr_starting_point] = p;
13582 
13583       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)
13584          && available(&p, channelmatched)) {
13585          ast_debug(1, "Using channel %d\n", p->channel);
13586 
13587          callwait = (p->owner != NULL);
13588 #ifdef HAVE_OPENR2
13589          if (p->mfcr2) {
13590             ast_mutex_lock(&p->lock);
13591             if (p->mfcr2call) {
13592                ast_mutex_unlock(&p->lock);
13593                ast_log(LOG_DEBUG, "Yay!, someone just beat us in the race for channel %d.\n", p->channel);
13594                goto next;
13595             }
13596             p->mfcr2call = 1;
13597             ast_mutex_unlock(&p->lock);
13598          }
13599 #endif
13600          if (p->channel == CHAN_PSEUDO) {
13601             p = duplicate_pseudo(p);
13602             if (!p) {
13603                break;
13604             }
13605          }
13606 
13607          p->distinctivering = 0;
13608          /* Make special notes */
13609          switch (start.opt) {
13610          case '\0':
13611             /* No option present. */
13612             break;
13613          case 'c':
13614             /* Confirm answer */
13615             p->confirmanswer = 1;
13616             break;
13617          case 'r':
13618             /* Distinctive ring */
13619             p->distinctivering = start.cadance;
13620             break;
13621          case 'd':
13622 #if defined(HAVE_PRI) || defined(HAVE_SS7)
13623             /* If this is an ISDN call, make it digital */
13624             transcapdigital = AST_TRANS_CAP_DIGITAL;
13625 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
13626             break;
13627          default:
13628             ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", start.opt, (char *)data);
13629             break;
13630          }
13631 
13632          p->outgoing = 1;
13633          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
13634             tmp = analog_request(p->sig_pvt, &callwait, requestor);
13635 #ifdef HAVE_PRI
13636          } else if (dahdi_sig_pri_lib_handles(p->sig)) {
13637             /*
13638              * We already have the B channel reserved for this call.  We
13639              * just need to make sure that dahdi_hangup() has completed
13640              * cleaning up before continuing.
13641              */
13642             ast_mutex_lock(&p->lock);
13643             ast_mutex_unlock(&p->lock);
13644 
13645             sig_pri_extract_called_num_subaddr(p->sig_pvt, data, p->dnid,
13646                sizeof(p->dnid));
13647             tmp = sig_pri_request(p->sig_pvt, SIG_PRI_DEFLAW, requestor, transcapdigital);
13648 #endif
13649 #if defined(HAVE_SS7)
13650          } else if (p->sig == SIG_SS7) {
13651             tmp = sig_ss7_request(p->sig_pvt, SIG_SS7_DEFLAW, requestor, transcapdigital);
13652 #endif   /* defined(HAVE_SS7) */
13653          } else {
13654             tmp = dahdi_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, requestor ? requestor->linkedid : "");
13655          }
13656          if (!tmp) {
13657             p->outgoing = 0;
13658 #if defined(HAVE_PRI)
13659             switch (p->sig) {
13660             case SIG_PRI_LIB_HANDLE_CASES:
13661 #if defined(HAVE_PRI_CALL_WAITING)
13662                if (((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting) {
13663                   ((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting = 0;
13664                   ast_atomic_fetchadd_int(&p->pri->num_call_waiting_calls, -1);
13665                }
13666 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13667                /*
13668                 * This should be the last thing to clear when we are done with
13669                 * the channel.
13670                 */
13671                ((struct sig_pri_chan *) p->sig_pvt)->allocated = 0;
13672                break;
13673             default:
13674                break;
13675             }
13676 #endif   /* defined(HAVE_PRI) */
13677          } else {
13678             snprintf(p->dialstring, sizeof(p->dialstring), "DAHDI/%s", (char *) data);
13679          }
13680          break;
13681       }
13682 #ifdef HAVE_OPENR2
13683 next:
13684 #endif
13685       if (start.backwards) {
13686          p = p->prev;
13687          if (!p)
13688             p = ifend;
13689       } else {
13690          p = p->next;
13691          if (!p)
13692             p = iflist;
13693       }
13694       /* stop when you roll to the one that we started from */
13695       if (p == exitpvt)
13696          break;
13697    }
13698    ast_mutex_unlock(&iflock);
13699    restart_monitor();
13700    if (cause && !tmp) {
13701       if (callwait || channelmatched) {
13702          *cause = AST_CAUSE_BUSY;
13703       } else if (groupmatched) {
13704          *cause = AST_CAUSE_CONGESTION;
13705       } else {
13706          /*
13707           * We did not match any channel requested.
13708           * Dialplan error requesting non-existant channel?
13709           */
13710       }
13711    }
13712 
13713    return tmp;
13714 }
13715 
13716 /*!
13717  * \internal
13718  * \brief Determine the device state for a given DAHDI device if we can.
13719  * \since 1.8
13720  *
13721  * \param data DAHDI device name after "DAHDI/".
13722  *
13723  * \retval device_state enum ast_device_state value.
13724  * \retval AST_DEVICE_UNKNOWN if we could not determine the device's state.
13725  */
13726 static int dahdi_devicestate(void *data)
13727 {
13728 #if defined(HAVE_PRI)
13729    char *device;
13730    unsigned span;
13731    int res;
13732 
13733    device = data;
13734 
13735    if (*device != 'I') {
13736       /* The request is not for an ISDN span device. */
13737       return AST_DEVICE_UNKNOWN;
13738    }
13739    res = sscanf(device, "I%30u", &span);
13740    if (res != 1 || !span || NUM_SPANS < span) {
13741       /* Bad format for ISDN span device name. */
13742       return AST_DEVICE_UNKNOWN;
13743    }
13744    device = strchr(device, '/');
13745    if (!device) {
13746       /* Bad format for ISDN span device name. */
13747       return AST_DEVICE_UNKNOWN;
13748    }
13749 
13750    /*
13751     * Since there are currently no other span devstate's defined,
13752     * it must be congestion.
13753     */
13754 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13755    ++device;
13756    if (!strcmp(device, "congestion"))
13757 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13758    {
13759       return pris[span - 1].pri.congestion_devstate;
13760    }
13761 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13762    else if (!strcmp(device, "threshold")) {
13763       return pris[span - 1].pri.threshold_devstate;
13764    }
13765    return AST_DEVICE_UNKNOWN;
13766 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13767 #else
13768    return AST_DEVICE_UNKNOWN;
13769 #endif   /* defined(HAVE_PRI) */
13770 }
13771 
13772 /*!
13773  * \brief Callback made when dial failed to get a channel out of dahdi_request().
13774  * \since 1.8
13775  *
13776  * \param inbound Incoming asterisk channel.
13777  * \param dest Same dial string passed to dahdi_request().
13778  * \param callback Callback into CC core to announce a busy channel available for CC.
13779  *
13780  * \details
13781  * This callback acts like a forked dial with all prongs of the fork busy.
13782  * Essentially, for each channel that could have taken the call, indicate that
13783  * it is busy.
13784  *
13785  * \retval 0 on success.
13786  * \retval -1 on error.
13787  */
13788 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback)
13789 {
13790    struct dahdi_pvt *p;
13791    struct dahdi_pvt *exitpvt;
13792    struct dahdi_starting_point start;
13793    int groupmatched = 0;
13794    int channelmatched = 0;
13795 
13796    ast_mutex_lock(&iflock);
13797    p = determine_starting_point(dest, &start);
13798    if (!p) {
13799       ast_mutex_unlock(&iflock);
13800       return -1;
13801    }
13802    exitpvt = p;
13803    for (;;) {
13804       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)) {
13805          /* We found a potential match. call the callback */
13806          struct ast_str *device_name;
13807          char *dash;
13808          const char *monitor_type;
13809          char dialstring[AST_CHANNEL_NAME];
13810          char full_device_name[AST_CHANNEL_NAME];
13811 
13812          switch (ast_get_cc_monitor_policy(p->cc_params)) {
13813          case AST_CC_MONITOR_NEVER:
13814             break;
13815          case AST_CC_MONITOR_NATIVE:
13816          case AST_CC_MONITOR_ALWAYS:
13817          case AST_CC_MONITOR_GENERIC:
13818 #if defined(HAVE_PRI)
13819             if (dahdi_sig_pri_lib_handles(p->sig)) {
13820                /*
13821                 * ISDN is in a trunk busy condition so we need to monitor
13822                 * the span congestion device state.
13823                 */
13824                snprintf(full_device_name, sizeof(full_device_name),
13825                   "DAHDI/I%d/congestion", p->pri->span);
13826             } else
13827 #endif   /* defined(HAVE_PRI) */
13828             {
13829 #if defined(HAVE_PRI)
13830                device_name = create_channel_name(p, 1, "");
13831 #else
13832                device_name = create_channel_name(p);
13833 #endif   /* defined(HAVE_PRI) */
13834                snprintf(full_device_name, sizeof(full_device_name), "DAHDI/%s",
13835                   device_name ? ast_str_buffer(device_name) : "");
13836                ast_free(device_name);
13837                /*
13838                 * The portion after the '-' in the channel name is either a random
13839                 * number, a sequence number, or a subchannel number. None are
13840                 * necessary so strip them off.
13841                 */
13842                dash = strrchr(full_device_name, '-');
13843                if (dash) {
13844                   *dash = '\0';
13845                }
13846             }
13847             snprintf(dialstring, sizeof(dialstring), "DAHDI/%s", dest);
13848 
13849             /*
13850              * Analog can only do generic monitoring.
13851              * ISDN is in a trunk busy condition and any "device" is going
13852              * to be busy until a B channel becomes available.  The generic
13853              * monitor can do this task.
13854              */
13855             monitor_type = AST_CC_GENERIC_MONITOR_TYPE;
13856             callback(inbound,
13857 #if defined(HAVE_PRI)
13858                p->pri ? p->pri->cc_params : p->cc_params,
13859 #else
13860                p->cc_params,
13861 #endif   /* defined(HAVE_PRI) */
13862                monitor_type, full_device_name, dialstring, NULL);
13863             break;
13864          }
13865       }
13866       p = start.backwards ? p->prev : p->next;
13867       if (!p) {
13868          p = start.backwards ? ifend : iflist;
13869       }
13870       if (p == exitpvt) {
13871          break;
13872       }
13873    }
13874    ast_mutex_unlock(&iflock);
13875    return 0;
13876 }
13877 
13878 #if defined(HAVE_SS7)
13879 static void dahdi_ss7_message(struct ss7 *ss7, char *s)
13880 {
13881    int i;
13882 
13883    if (ss7) {
13884       for (i = 0; i < NUM_SPANS; i++) {
13885          if (linksets[i].ss7.ss7 == ss7) {
13886             ast_verbose("[%d] %s", i + 1, s);
13887             return;
13888          }
13889       }
13890    }
13891    ast_verbose("%s", s);
13892 }
13893 #endif   /* defined(HAVE_SS7) */
13894 
13895 #if defined(HAVE_SS7)
13896 static void dahdi_ss7_error(struct ss7 *ss7, char *s)
13897 {
13898    int i;
13899 
13900    if (ss7) {
13901       for (i = 0; i < NUM_SPANS; i++) {
13902          if (linksets[i].ss7.ss7 == ss7) {
13903             ast_log(LOG_ERROR, "[%d] %s", i + 1, s);
13904             return;
13905          }
13906       }
13907    }
13908    ast_log(LOG_ERROR, "%s", s);
13909 }
13910 #endif   /* defined(HAVE_SS7) */
13911 
13912 #if defined(HAVE_OPENR2)
13913 static void *mfcr2_monitor(void *data)
13914 {
13915    struct dahdi_mfcr2 *mfcr2 = data;
13916    /* we should be using pthread_key_create
13917       and allocate pollers dynamically.
13918       I think do_monitor() could be leaking, since it
13919       could be cancelled at any time and is not
13920       using thread keys, why?, */
13921    struct pollfd pollers[ARRAY_LEN(mfcr2->pvts)];
13922    int res = 0;
13923    int i = 0;
13924    int oldstate = 0;
13925    int quit_loop = 0;
13926    int maxsleep = 20;
13927    int was_idle = 0;
13928    int pollsize = 0;
13929    /* now that we're ready to get calls, unblock our side and
13930       get current line state */
13931    for (i = 0; i < mfcr2->numchans; i++) {
13932       openr2_chan_set_idle(mfcr2->pvts[i]->r2chan);
13933       openr2_chan_handle_cas(mfcr2->pvts[i]->r2chan);
13934    }
13935    while (1) {
13936       /* we trust here that the mfcr2 channel list will not ever change once
13937          the module is loaded */
13938       pollsize = 0;
13939       for (i = 0; i < mfcr2->numchans; i++) {
13940          pollers[i].revents = 0;
13941          pollers[i].events = 0;
13942          if (mfcr2->pvts[i]->owner) {
13943             continue;
13944          }
13945          if (!mfcr2->pvts[i]->r2chan) {
13946             ast_log(LOG_DEBUG, "Wow, no r2chan on channel %d\n", mfcr2->pvts[i]->channel);
13947             quit_loop = 1;
13948             break;
13949          }
13950          openr2_chan_enable_read(mfcr2->pvts[i]->r2chan);
13951          pollers[i].events = POLLIN | POLLPRI;
13952          pollers[i].fd = mfcr2->pvts[i]->subs[SUB_REAL].dfd;
13953          pollsize++;
13954       }
13955       if (quit_loop) {
13956          break;
13957       }
13958       if (pollsize == 0) {
13959          if (!was_idle) {
13960             ast_log(LOG_DEBUG, "Monitor thread going idle since everybody has an owner\n");
13961             was_idle = 1;
13962          }
13963          poll(NULL, 0, maxsleep);
13964          continue;
13965       }
13966       was_idle = 0;
13967       /* probably poll() is a valid cancel point, lets just be on the safe side
13968          by calling pthread_testcancel */
13969       pthread_testcancel();
13970       res = poll(pollers, mfcr2->numchans, maxsleep);
13971       pthread_testcancel();
13972       if ((res < 0) && (errno != EINTR)) {
13973          ast_log(LOG_ERROR, "going out, poll failed: %s\n", strerror(errno));
13974          break;
13975       }
13976       /* do we want to allow to cancel while processing events? */
13977       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
13978       for (i = 0; i < mfcr2->numchans; i++) {
13979          if (pollers[i].revents & POLLPRI || pollers[i].revents & POLLIN) {
13980             openr2_chan_process_event(mfcr2->pvts[i]->r2chan);
13981          }
13982       }
13983       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
13984    }
13985    ast_log(LOG_NOTICE, "Quitting MFC/R2 monitor thread\n");
13986    return 0;
13987 }
13988 #endif /* HAVE_OPENR2 */
13989 
13990 #if defined(HAVE_PRI)
13991 #ifndef PRI_RESTART
13992 #error "Upgrade your libpri"
13993 #endif
13994 static void dahdi_pri_message(struct pri *pri, char *s)
13995 {
13996    int x;
13997    int y;
13998    int dchan = -1;
13999    int span = -1;
14000    int dchancount = 0;
14001 
14002    if (pri) {
14003       for (x = 0; x < NUM_SPANS; x++) {
14004          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14005             if (pris[x].pri.dchans[y]) {
14006                dchancount++;
14007             }
14008 
14009             if (pris[x].pri.dchans[y] == pri) {
14010                dchan = y;
14011             }
14012          }
14013          if (dchan >= 0) {
14014             span = x;
14015             break;
14016          }
14017          dchancount = 0;
14018       }
14019       if (-1 < span) {
14020          if (1 < dchancount) {
14021             ast_verbose("[PRI Span: %d D-Channel: %d] %s", span + 1, dchan, s);
14022          } else {
14023             ast_verbose("PRI Span: %d %s", span + 1, s);
14024          }
14025       } else {
14026          ast_verbose("PRI Span: ? %s", s);
14027       }
14028    } else {
14029       ast_verbose("PRI Span: ? %s", s);
14030    }
14031 
14032    ast_mutex_lock(&pridebugfdlock);
14033 
14034    if (pridebugfd >= 0) {
14035       if (write(pridebugfd, s, strlen(s)) < 0) {
14036          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14037       }
14038    }
14039 
14040    ast_mutex_unlock(&pridebugfdlock);
14041 }
14042 #endif   /* defined(HAVE_PRI) */
14043 
14044 #if defined(HAVE_PRI)
14045 static void dahdi_pri_error(struct pri *pri, char *s)
14046 {
14047    int x;
14048    int y;
14049    int dchan = -1;
14050    int span = -1;
14051    int dchancount = 0;
14052 
14053    if (pri) {
14054       for (x = 0; x < NUM_SPANS; x++) {
14055          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14056             if (pris[x].pri.dchans[y]) {
14057                dchancount++;
14058             }
14059 
14060             if (pris[x].pri.dchans[y] == pri) {
14061                dchan = y;
14062             }
14063          }
14064          if (dchan >= 0) {
14065             span = x;
14066             break;
14067          }
14068          dchancount = 0;
14069       }
14070       if (-1 < span) {
14071          if (1 < dchancount) {
14072             ast_log(LOG_ERROR, "[PRI Span: %d D-Channel: %d] %s", span + 1, dchan, s);
14073          } else {
14074             ast_log(LOG_ERROR, "PRI Span: %d %s", span + 1, s);
14075          }
14076       } else {
14077          ast_log(LOG_ERROR, "PRI Span: ? %s", s);
14078       }
14079    } else {
14080       ast_log(LOG_ERROR, "PRI Span: ? %s", s);
14081    }
14082 
14083    ast_mutex_lock(&pridebugfdlock);
14084 
14085    if (pridebugfd >= 0) {
14086       if (write(pridebugfd, s, strlen(s)) < 0) {
14087          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14088       }
14089    }
14090 
14091    ast_mutex_unlock(&pridebugfdlock);
14092 }
14093 #endif   /* defined(HAVE_PRI) */
14094 
14095 #if defined(HAVE_PRI)
14096 static int prepare_pri(struct dahdi_pri *pri)
14097 {
14098    int i, res, x;
14099    struct dahdi_params p;
14100    struct dahdi_bufferinfo bi;
14101    struct dahdi_spaninfo si;
14102 
14103    pri->pri.calls = &dahdi_pri_callbacks;
14104 
14105    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
14106       if (!pri->dchannels[i])
14107          break;
14108       pri->pri.fds[i] = open("/dev/dahdi/channel", O_RDWR);
14109       x = pri->dchannels[i];
14110       if ((pri->pri.fds[i] < 0) || (ioctl(pri->pri.fds[i],DAHDI_SPECIFY,&x) == -1)) {
14111          ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
14112          return -1;
14113       }
14114       memset(&p, 0, sizeof(p));
14115       res = ioctl(pri->pri.fds[i], DAHDI_GET_PARAMS, &p);
14116       if (res) {
14117          dahdi_close_pri_fd(pri, i);
14118          ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
14119          return -1;
14120       }
14121       if ((p.sigtype != DAHDI_SIG_HDLCFCS) && (p.sigtype != DAHDI_SIG_HARDHDLC)) {
14122          dahdi_close_pri_fd(pri, i);
14123          ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode.\n", x);
14124          return -1;
14125       }
14126       memset(&si, 0, sizeof(si));
14127       res = ioctl(pri->pri.fds[i], DAHDI_SPANSTAT, &si);
14128       if (res) {
14129          dahdi_close_pri_fd(pri, i);
14130          ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
14131       }
14132       if (!si.alarms) {
14133          pri_event_noalarm(&pri->pri, i, 1);
14134       } else {
14135          pri_event_alarm(&pri->pri, i, 1);
14136       }
14137       memset(&bi, 0, sizeof(bi));
14138       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
14139       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
14140       bi.numbufs = 32;
14141       bi.bufsize = 1024;
14142       if (ioctl(pri->pri.fds[i], DAHDI_SET_BUFINFO, &bi)) {
14143          ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n", x, strerror(errno));
14144          dahdi_close_pri_fd(pri, i);
14145          return -1;
14146       }
14147       pri->pri.dchan_logical_span[i] = pris[p.spanno - 1].prilogicalspan;
14148    }
14149    return 0;
14150 }
14151 #endif   /* defined(HAVE_PRI) */
14152 
14153 #if defined(HAVE_PRI)
14154 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
14155 {
14156    int which, span;
14157    char *ret = NULL;
14158 
14159    if (pos != rpos)
14160       return ret;
14161 
14162    for (which = span = 0; span < NUM_SPANS; span++) {
14163       if (pris[span].pri.pri && ++which > state) {
14164          if (asprintf(&ret, "%d", span + 1) < 0) { /* user indexes start from 1 */
14165             ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
14166          }
14167          break;
14168       }
14169    }
14170    return ret;
14171 }
14172 #endif   /* defined(HAVE_PRI) */
14173 
14174 #if defined(HAVE_PRI)
14175 static char *complete_span_4(const char *line, const char *word, int pos, int state)
14176 {
14177    return complete_span_helper(line,word,pos,state,3);
14178 }
14179 #endif   /* defined(HAVE_PRI) */
14180 
14181 #if defined(HAVE_PRI)
14182 static char *handle_pri_set_debug_file(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14183 {
14184    int myfd;
14185    switch (cmd) {
14186    case CLI_INIT:
14187       e->command = "pri set debug file";
14188       e->usage = "Usage: pri set debug file [output-file]\n"
14189          "       Sends PRI debug output to the specified output file\n";
14190       return NULL;
14191    case CLI_GENERATE:
14192       return NULL;
14193    }
14194    if (a->argc < 5)
14195       return CLI_SHOWUSAGE;
14196 
14197    if (ast_strlen_zero(a->argv[4]))
14198       return CLI_SHOWUSAGE;
14199 
14200    myfd = open(a->argv[4], O_CREAT|O_WRONLY, AST_FILE_MODE);
14201    if (myfd < 0) {
14202       ast_cli(a->fd, "Unable to open '%s' for writing\n", a->argv[4]);
14203       return CLI_SUCCESS;
14204    }
14205 
14206    ast_mutex_lock(&pridebugfdlock);
14207 
14208    if (pridebugfd >= 0)
14209       close(pridebugfd);
14210 
14211    pridebugfd = myfd;
14212    ast_copy_string(pridebugfilename,a->argv[4],sizeof(pridebugfilename));
14213    ast_mutex_unlock(&pridebugfdlock);
14214    ast_cli(a->fd, "PRI debug output will be sent to '%s'\n", a->argv[4]);
14215    return CLI_SUCCESS;
14216 }
14217 #endif   /* defined(HAVE_PRI) */
14218 
14219 #if defined(HAVE_PRI)
14220 static char *handle_pri_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14221 {
14222    int span;
14223    int x;
14224    int level = 0;
14225    switch (cmd) {
14226    case CLI_INIT:
14227       e->command = "pri set debug {on|off|0|1|2} span";
14228       e->usage =
14229          "Usage: pri set debug {<level>|on|off} span <span>\n"
14230          "       Enables debugging on a given PRI span\n";
14231       return NULL;
14232    case CLI_GENERATE:
14233       return complete_span_4(a->line, a->word, a->pos, a->n);
14234    }
14235    if (a->argc < 6) {
14236       return CLI_SHOWUSAGE;
14237    }
14238 
14239    if (!strcasecmp(a->argv[3], "on")) {
14240       level = 1;
14241    } else if (!strcasecmp(a->argv[3], "off")) {
14242       level = 0;
14243    } else {
14244       level = atoi(a->argv[3]);
14245    }
14246    span = atoi(a->argv[5]);
14247    if ((span < 1) || (span > NUM_SPANS)) {
14248       ast_cli(a->fd, "Invalid span %s.  Should be a number %d to %d\n", a->argv[5], 1, NUM_SPANS);
14249       return CLI_SUCCESS;
14250    }
14251    if (!pris[span-1].pri.pri) {
14252       ast_cli(a->fd, "No PRI running on span %d\n", span);
14253       return CLI_SUCCESS;
14254    }
14255 
14256    /* Set debug level in libpri */
14257    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14258       if (pris[span - 1].pri.dchans[x]) {
14259          switch (level) {
14260          case 0:
14261             pri_set_debug(pris[span - 1].pri.dchans[x], 0);
14262             break;
14263          case 1:
14264             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_NORMAL);
14265             break;
14266          default:
14267             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_INTENSE);
14268             break;
14269          }
14270       }
14271    }
14272    if (level == 0) {
14273       /* Close the debugging file if it's set */
14274       ast_mutex_lock(&pridebugfdlock);
14275       if (0 <= pridebugfd) {
14276          close(pridebugfd);
14277          pridebugfd = -1;
14278          ast_cli(a->fd, "Disabled PRI debug output to file '%s'\n",
14279             pridebugfilename);
14280       }
14281       ast_mutex_unlock(&pridebugfdlock);
14282    }
14283    pris[span - 1].pri.debug = (level) ? 1 : 0;
14284    ast_cli(a->fd, "%s debugging on span %d\n", (level) ? "Enabled" : "Disabled", span);
14285    return CLI_SUCCESS;
14286 }
14287 #endif   /* defined(HAVE_PRI) */
14288 
14289 #if defined(HAVE_PRI)
14290 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14291 static char *handle_pri_service_generic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a, int changestatus)
14292 {
14293    unsigned *why;
14294    int channel;
14295    int trunkgroup;
14296    int x, y, fd = a->fd;
14297    int interfaceid = 0;
14298    char *c;
14299    char db_chan_name[20], db_answer[5];
14300    struct dahdi_pvt *tmp;
14301    struct dahdi_pri *pri;
14302 
14303    if (a->argc < 5 || a->argc > 6)
14304       return CLI_SHOWUSAGE;
14305    if ((c = strchr(a->argv[4], ':'))) {
14306       if (sscanf(a->argv[4], "%30d:%30d", &trunkgroup, &channel) != 2)
14307          return CLI_SHOWUSAGE;
14308       if ((trunkgroup < 1) || (channel < 1))
14309          return CLI_SHOWUSAGE;
14310       pri = NULL;
14311       for (x=0;x<NUM_SPANS;x++) {
14312          if (pris[x].pri.trunkgroup == trunkgroup) {
14313             pri = pris + x;
14314             break;
14315          }
14316       }
14317       if (!pri) {
14318          ast_cli(fd, "No such trunk group %d\n", trunkgroup);
14319          return CLI_FAILURE;
14320       }
14321    } else
14322       channel = atoi(a->argv[4]);
14323 
14324    if (a->argc == 6)
14325       interfaceid = atoi(a->argv[5]);
14326 
14327    /* either servicing a D-Channel */
14328    for (x = 0; x < NUM_SPANS; x++) {
14329       for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14330          if (pris[x].dchannels[y] == channel) {
14331             pri = pris + x;
14332             if (pri->pri.enable_service_message_support) {
14333                ast_mutex_lock(&pri->pri.lock);
14334                pri_maintenance_service(pri->pri.pri, interfaceid, -1, changestatus);
14335                ast_mutex_unlock(&pri->pri.lock);
14336             } else {
14337                ast_cli(fd,
14338                   "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
14339                   "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
14340             }
14341             return CLI_SUCCESS;
14342          }
14343       }
14344    }
14345 
14346    /* or servicing a B-Channel */
14347    ast_mutex_lock(&iflock);
14348    for (tmp = iflist; tmp; tmp = tmp->next) {
14349       if (tmp->pri && tmp->channel == channel) {
14350          ast_mutex_unlock(&iflock);
14351          ast_mutex_lock(&tmp->pri->lock);
14352          if (!tmp->pri->enable_service_message_support) {
14353             ast_mutex_unlock(&tmp->pri->lock);
14354             ast_cli(fd,
14355                "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
14356                "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
14357             return CLI_SUCCESS;
14358          }
14359          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, channel);
14360          why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
14361          switch(changestatus) {
14362          case 0: /* enable */
14363             /* Near end wants to be in service now. */
14364             ast_db_del(db_chan_name, SRVST_DBKEY);
14365             *why &= ~SRVST_NEAREND;
14366             if (*why) {
14367                snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
14368                ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
14369             } else {
14370                dahdi_pri_update_span_devstate(tmp->pri);
14371             }
14372             break;
14373          /* case 1:  -- loop */
14374          case 2: /* disable */
14375             /* Near end wants to be out-of-service now. */
14376             ast_db_del(db_chan_name, SRVST_DBKEY);
14377             *why |= SRVST_NEAREND;
14378             snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
14379             ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
14380             dahdi_pri_update_span_devstate(tmp->pri);
14381             break;
14382          /* case 3:  -- continuity */
14383          /* case 4:  -- shutdown */
14384          default:
14385             ast_log(LOG_WARNING, "Unsupported changestatus: '%d'\n", changestatus);
14386             break;
14387          }
14388          pri_maintenance_bservice(tmp->pri->pri, tmp->sig_pvt, changestatus);
14389          ast_mutex_unlock(&tmp->pri->lock);
14390          return CLI_SUCCESS;
14391       }
14392    }
14393    ast_mutex_unlock(&iflock);
14394 
14395    ast_cli(fd, "Unable to find given channel %d, possibly not a PRI\n", channel);
14396    return CLI_FAILURE;
14397 }
14398 
14399 static char *handle_pri_service_enable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14400 {
14401    switch (cmd) {
14402    case CLI_INIT:
14403       e->command = "pri service enable channel";
14404       e->usage =
14405          "Usage: pri service enable channel <channel> [<interface id>]\n"
14406          "       Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
14407          "  to restore a channel to service, with optional interface id\n"
14408          "  as agreed upon with remote switch operator\n";
14409       return NULL;
14410    case CLI_GENERATE:
14411       return NULL;
14412    }
14413    return handle_pri_service_generic(e, cmd, a, 0);
14414 }
14415 
14416 static char *handle_pri_service_disable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14417 {
14418    switch (cmd) {
14419    case CLI_INIT:
14420       e->command = "pri service disable channel";
14421       e->usage =
14422          "Usage: pri service disable channel <chan num> [<interface id>]\n"
14423          "  Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
14424          "  to remove a channel from service, with optional interface id\n"
14425          "  as agreed upon with remote switch operator\n";
14426       return NULL;
14427    case CLI_GENERATE:
14428       return NULL;
14429    }
14430    return handle_pri_service_generic(e, cmd, a, 2);
14431 }
14432 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14433 #endif   /* defined(HAVE_PRI) */
14434 
14435 #if defined(HAVE_PRI)
14436 static char *handle_pri_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14437 {
14438    int span;
14439 
14440    switch (cmd) {
14441    case CLI_INIT:
14442       e->command = "pri show channels";
14443       e->usage =
14444          "Usage: pri show channels\n"
14445          "       Displays PRI channel information such as the current mapping\n"
14446          "       of DAHDI B channels to Asterisk channel names and which calls\n"
14447          "       are on hold or call-waiting.  Calls on hold or call-waiting\n"
14448          "       are not associated with any B channel.\n";
14449       return NULL;
14450    case CLI_GENERATE:
14451       return NULL;
14452    }
14453 
14454    if (a->argc != 3)
14455       return CLI_SHOWUSAGE;
14456 
14457    sig_pri_cli_show_channels_header(a->fd);
14458    for (span = 0; span < NUM_SPANS; ++span) {
14459       if (pris[span].pri.pri) {
14460          sig_pri_cli_show_channels(a->fd, &pris[span].pri);
14461       }
14462    }
14463    return CLI_SUCCESS;
14464 }
14465 #endif   /* defined(HAVE_PRI) */
14466 
14467 #if defined(HAVE_PRI)
14468 static char *handle_pri_show_spans(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14469 {
14470    int span;
14471 
14472    switch (cmd) {
14473    case CLI_INIT:
14474       e->command = "pri show spans";
14475       e->usage =
14476          "Usage: pri show spans\n"
14477          "       Displays PRI span information\n";
14478       return NULL;
14479    case CLI_GENERATE:
14480       return NULL;
14481    }
14482 
14483    if (a->argc != 3)
14484       return CLI_SHOWUSAGE;
14485 
14486    for (span = 0; span < NUM_SPANS; span++) {
14487       if (pris[span].pri.pri) {
14488          sig_pri_cli_show_spans(a->fd, span + 1, &pris[span].pri);
14489       }
14490    }
14491    return CLI_SUCCESS;
14492 }
14493 #endif   /* defined(HAVE_PRI) */
14494 
14495 #if defined(HAVE_PRI)
14496 static char *handle_pri_show_span(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 span";
14503       e->usage =
14504          "Usage: pri show span <span>\n"
14505          "       Displays PRI Information on a given PRI span\n";
14506       return NULL;
14507    case CLI_GENERATE:
14508       return complete_span_4(a->line, a->word, a->pos, a->n);
14509    }
14510 
14511    if (a->argc < 4)
14512       return CLI_SHOWUSAGE;
14513    span = atoi(a->argv[3]);
14514    if ((span < 1) || (span > NUM_SPANS)) {
14515       ast_cli(a->fd, "Invalid span '%s'.  Should be a number from %d to %d\n", a->argv[3], 1, NUM_SPANS);
14516       return CLI_SUCCESS;
14517    }
14518    if (!pris[span-1].pri.pri) {
14519       ast_cli(a->fd, "No PRI running on span %d\n", span);
14520       return CLI_SUCCESS;
14521    }
14522 
14523    sig_pri_cli_show_span(a->fd, pris[span-1].dchannels, &pris[span-1].pri);
14524 
14525    return CLI_SUCCESS;
14526 }
14527 #endif   /* defined(HAVE_PRI) */
14528 
14529 #if defined(HAVE_PRI)
14530 static char *handle_pri_show_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14531 {
14532    int x;
14533    int span;
14534    int count=0;
14535    int debug;
14536 
14537    switch (cmd) {
14538    case CLI_INIT:
14539       e->command = "pri show debug";
14540       e->usage =
14541          "Usage: pri show debug\n"
14542          "  Show the debug state of pri spans\n";
14543       return NULL;
14544    case CLI_GENERATE:
14545       return NULL;
14546    }
14547 
14548    for (span = 0; span < NUM_SPANS; span++) {
14549       if (pris[span].pri.pri) {
14550          for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14551             if (pris[span].pri.dchans[x]) {
14552                debug = pri_get_debug(pris[span].pri.dchans[x]);
14553                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" );
14554                count++;
14555             }
14556          }
14557       }
14558 
14559    }
14560    ast_mutex_lock(&pridebugfdlock);
14561    if (pridebugfd >= 0)
14562       ast_cli(a->fd, "Logging PRI debug to file %s\n", pridebugfilename);
14563    ast_mutex_unlock(&pridebugfdlock);
14564 
14565    if (!count)
14566       ast_cli(a->fd, "No PRI running\n");
14567    return CLI_SUCCESS;
14568 }
14569 #endif   /* defined(HAVE_PRI) */
14570 
14571 #if defined(HAVE_PRI)
14572 static char *handle_pri_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14573 {
14574    switch (cmd) {
14575    case CLI_INIT:
14576       e->command = "pri show version";
14577       e->usage =
14578          "Usage: pri show version\n"
14579          "Show libpri version information\n";
14580       return NULL;
14581    case CLI_GENERATE:
14582       return NULL;
14583    }
14584 
14585    ast_cli(a->fd, "libpri version: %s\n", pri_get_version());
14586 
14587    return CLI_SUCCESS;
14588 }
14589 #endif   /* defined(HAVE_PRI) */
14590 
14591 #if defined(HAVE_PRI)
14592 static struct ast_cli_entry dahdi_pri_cli[] = {
14593    AST_CLI_DEFINE(handle_pri_debug, "Enables PRI debugging on a span"),
14594 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14595    AST_CLI_DEFINE(handle_pri_service_enable_channel, "Return a channel to service"),
14596    AST_CLI_DEFINE(handle_pri_service_disable_channel, "Remove a channel from service"),
14597 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14598    AST_CLI_DEFINE(handle_pri_show_channels, "Displays PRI channel information"),
14599    AST_CLI_DEFINE(handle_pri_show_spans, "Displays PRI span information"),
14600    AST_CLI_DEFINE(handle_pri_show_span, "Displays PRI span information"),
14601    AST_CLI_DEFINE(handle_pri_show_debug, "Displays current PRI debug settings"),
14602    AST_CLI_DEFINE(handle_pri_set_debug_file, "Sends PRI debug output to the specified file"),
14603    AST_CLI_DEFINE(handle_pri_version, "Displays libpri version"),
14604 };
14605 #endif   /* defined(HAVE_PRI) */
14606 
14607 #ifdef HAVE_OPENR2
14608 
14609 static char *handle_mfcr2_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14610 {
14611    switch (cmd) {
14612    case CLI_INIT:
14613       e->command = "mfcr2 show version";
14614       e->usage =
14615          "Usage: mfcr2 show version\n"
14616          "       Shows the version of the OpenR2 library being used.\n";
14617       return NULL;
14618    case CLI_GENERATE:
14619       return NULL;
14620    }
14621    ast_cli(a->fd, "OpenR2 version: %s, revision: %s\n", openr2_get_version(), openr2_get_revision());
14622    return CLI_SUCCESS;
14623 }
14624 
14625 static char *handle_mfcr2_show_variants(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14626 {
14627 #define FORMAT "%4s %40s\n"
14628    int i = 0;
14629    int numvariants = 0;
14630    const openr2_variant_entry_t *variants;
14631    switch (cmd) {
14632    case CLI_INIT:
14633       e->command = "mfcr2 show variants";
14634       e->usage =
14635          "Usage: mfcr2 show variants\n"
14636          "       Shows the list of MFC/R2 variants supported.\n";
14637       return NULL;
14638    case CLI_GENERATE:
14639       return NULL;
14640    }
14641    if (!(variants = openr2_proto_get_variant_list(&numvariants))) {
14642       ast_cli(a->fd, "Failed to get list of variants.\n");
14643       return CLI_FAILURE;
14644    }
14645    ast_cli(a->fd, FORMAT, "Variant Code", "Country");
14646    for (i = 0; i < numvariants; i++) {
14647       ast_cli(a->fd, FORMAT, variants[i].name, variants[i].country);
14648    }
14649    return CLI_SUCCESS;
14650 #undef FORMAT
14651 }
14652 
14653 static char *handle_mfcr2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14654 {
14655 #define FORMAT "%4s %-7.7s %-7.7s %-8.8s %-9.9s %-16.16s %-8.8s %-8.8s\n"
14656    int filtertype = 0;
14657    int targetnum = 0;
14658    char channo[5];
14659    char anino[5];
14660    char dnisno[5];
14661    struct dahdi_pvt *p;
14662    openr2_context_t *r2context;
14663    openr2_variant_t r2variant;
14664    switch (cmd) {
14665    case CLI_INIT:
14666       e->command = "mfcr2 show channels [group|context]";
14667       e->usage =
14668          "Usage: mfcr2 show channels [group <group> | context <context>]\n"
14669          "       Shows the DAHDI channels configured with MFC/R2 signaling.\n";
14670       return NULL;
14671    case CLI_GENERATE:
14672       return NULL;
14673    }
14674    if (!((a->argc == 3) || (a->argc == 5))) {
14675       return CLI_SHOWUSAGE;
14676    }
14677    if (a->argc == 5) {
14678       if (!strcasecmp(a->argv[3], "group")) {
14679          targetnum = atoi(a->argv[4]);
14680          if ((targetnum < 0) || (targetnum > 63))
14681             return CLI_SHOWUSAGE;
14682          targetnum = 1 << targetnum;
14683          filtertype = 1;
14684       } else if (!strcasecmp(a->argv[3], "context")) {
14685          filtertype = 2;
14686       } else {
14687          return CLI_SHOWUSAGE;
14688       }
14689    }
14690    ast_cli(a->fd, FORMAT, "Chan", "Variant", "Max ANI", "Max DNIS", "ANI First", "Immediate Accept", "Tx CAS", "Rx CAS");
14691    ast_mutex_lock(&iflock);
14692    for (p = iflist; p; p = p->next) {
14693       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14694          continue;
14695       }
14696       if (filtertype) {
14697          switch(filtertype) {
14698          case 1: /* mfcr2 show channels group <group> */
14699             if (p->group != targetnum) {
14700                continue;
14701             }
14702             break;
14703          case 2: /* mfcr2 show channels context <context> */
14704             if (strcasecmp(p->context, a->argv[4])) {
14705                continue;
14706             }
14707             break;
14708          default:
14709             ;
14710          }
14711       }
14712       r2context = openr2_chan_get_context(p->r2chan);
14713       r2variant = openr2_context_get_variant(r2context);
14714       snprintf(channo, sizeof(channo), "%d", p->channel);
14715       snprintf(anino, sizeof(anino), "%d", openr2_context_get_max_ani(r2context));
14716       snprintf(dnisno, sizeof(dnisno), "%d", openr2_context_get_max_dnis(r2context));
14717       ast_cli(a->fd, FORMAT, channo, openr2_proto_get_variant_string(r2variant),
14718             anino, dnisno, openr2_context_get_ani_first(r2context) ? "Yes" : "No",
14719             openr2_context_get_immediate_accept(r2context) ? "Yes" : "No",
14720             openr2_chan_get_tx_cas_string(p->r2chan), openr2_chan_get_rx_cas_string(p->r2chan));
14721    }
14722    ast_mutex_unlock(&iflock);
14723    return CLI_SUCCESS;
14724 #undef FORMAT
14725 }
14726 
14727 static char *handle_mfcr2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14728 {
14729    struct dahdi_pvt *p = NULL;
14730    int channo = 0;
14731    char *toklevel = NULL;
14732    char *saveptr = NULL;
14733    char *logval = NULL;
14734    openr2_log_level_t loglevel = OR2_LOG_NOTHING;
14735    openr2_log_level_t tmplevel = OR2_LOG_NOTHING;
14736    switch (cmd) {
14737    case CLI_INIT:
14738       e->command = "mfcr2 set debug";
14739       e->usage =
14740          "Usage: mfcr2 set debug <loglevel> <channel>\n"
14741          "       Set a new logging level for the specified channel.\n"
14742          "       If no channel is specified the logging level will be applied to all channels.\n";
14743       return NULL;
14744    case CLI_GENERATE:
14745       return NULL;
14746    }
14747    if (a->argc < 4) {
14748       return CLI_SHOWUSAGE;
14749    }
14750    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14751    logval = ast_strdupa(a->argv[3]);
14752    toklevel = strtok_r(logval, ",", &saveptr);
14753    if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14754       ast_cli(a->fd, "Invalid MFC/R2 logging level '%s'.\n", a->argv[3]);
14755       return CLI_FAILURE;
14756    } else if (OR2_LOG_NOTHING == tmplevel) {
14757       loglevel = tmplevel;
14758    } else {
14759       loglevel |= tmplevel;
14760       while ((toklevel = strtok_r(NULL, ",", &saveptr))) {
14761          if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14762             ast_cli(a->fd, "Ignoring invalid logging level: '%s'.\n", toklevel);
14763             continue;
14764          }
14765          loglevel |= tmplevel;
14766       }
14767    }
14768    ast_mutex_lock(&iflock);
14769    for (p = iflist; p; p = p->next) {
14770       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14771          continue;
14772       }
14773       if ((channo != -1) && (p->channel != channo )) {
14774          continue;
14775       }
14776       openr2_chan_set_log_level(p->r2chan, loglevel);
14777       if (channo != -1) {
14778          ast_cli(a->fd, "MFC/R2 debugging set to '%s' for channel %d.\n", a->argv[3], p->channel);
14779          break;
14780       }
14781    }
14782    if ((channo != -1) && !p) {
14783       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14784    }
14785    if (channo == -1) {
14786       ast_cli(a->fd, "MFC/R2 debugging set to '%s' for all channels.\n", a->argv[3]);
14787    }
14788    ast_mutex_unlock(&iflock);
14789    return CLI_SUCCESS;
14790 }
14791 
14792 static char *handle_mfcr2_call_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14793 {
14794    struct dahdi_pvt *p = NULL;
14795    int channo = 0;
14796    switch (cmd) {
14797    case CLI_INIT:
14798       e->command = "mfcr2 call files [on|off]";
14799       e->usage =
14800          "Usage: mfcr2 call files [on|off] <channel>\n"
14801          "       Enable call files creation on the specified channel.\n"
14802          "       If no channel is specified call files creation policy 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    ast_mutex_lock(&iflock);
14812    for (p = iflist; p; p = p->next) {
14813       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14814          continue;
14815       }
14816       if ((channo != -1) && (p->channel != channo )) {
14817          continue;
14818       }
14819       if (ast_true(a->argv[3])) {
14820          openr2_chan_enable_call_files(p->r2chan);
14821       } else {
14822          openr2_chan_disable_call_files(p->r2chan);
14823       }
14824       if (channo != -1) {
14825          if (ast_true(a->argv[3])) {
14826             ast_cli(a->fd, "MFC/R2 call files enabled for channel %d.\n", p->channel);
14827          } else {
14828             ast_cli(a->fd, "MFC/R2 call files disabled for channel %d.\n", p->channel);
14829          }
14830          break;
14831       }
14832    }
14833    if ((channo != -1) && !p) {
14834       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14835    }
14836    if (channo == -1) {
14837       if (ast_true(a->argv[3])) {
14838          ast_cli(a->fd, "MFC/R2 Call files enabled for all channels.\n");
14839       } else {
14840          ast_cli(a->fd, "MFC/R2 Call files disabled for all channels.\n");
14841       }
14842    }
14843    ast_mutex_unlock(&iflock);
14844    return CLI_SUCCESS;
14845 }
14846 
14847 static char *handle_mfcr2_set_idle(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14848 {
14849    struct dahdi_pvt *p = NULL;
14850    int channo = 0;
14851    switch (cmd) {
14852    case CLI_INIT:
14853       e->command = "mfcr2 set idle";
14854       e->usage =
14855          "Usage: mfcr2 set idle <channel>\n"
14856          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14857          "       Force the given channel into IDLE state.\n"
14858          "       If no channel is specified, all channels will be set to IDLE.\n";
14859       return NULL;
14860    case CLI_GENERATE:
14861       return NULL;
14862    }
14863    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14864    ast_mutex_lock(&iflock);
14865    for (p = iflist; p; p = p->next) {
14866       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14867          continue;
14868       }
14869       if ((channo != -1) && (p->channel != channo )) {
14870          continue;
14871       }
14872       openr2_chan_set_idle(p->r2chan);
14873       ast_mutex_lock(&p->lock);
14874       p->locallyblocked = 0;
14875       p->mfcr2call = 0;
14876       ast_mutex_unlock(&p->lock);
14877       if (channo != -1) {
14878          break;
14879       }
14880    }
14881    if ((channo != -1) && !p) {
14882       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14883    }
14884    ast_mutex_unlock(&iflock);
14885    return CLI_SUCCESS;
14886 }
14887 
14888 static char *handle_mfcr2_set_blocked(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14889 {
14890    struct dahdi_pvt *p = NULL;
14891    int channo = 0;
14892    switch (cmd) {
14893    case CLI_INIT:
14894       e->command = "mfcr2 set blocked";
14895       e->usage =
14896          "Usage: mfcr2 set blocked <channel>\n"
14897          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14898          "       Force the given channel into BLOCKED state.\n"
14899          "       If no channel is specified, all channels will be set to BLOCKED.\n";
14900       return NULL;
14901    case CLI_GENERATE:
14902       return NULL;
14903    }
14904    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14905    ast_mutex_lock(&iflock);
14906    for (p = iflist; p; p = p->next) {
14907       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14908          continue;
14909       }
14910       if ((channo != -1) && (p->channel != channo )) {
14911          continue;
14912       }
14913       openr2_chan_set_blocked(p->r2chan);
14914       ast_mutex_lock(&p->lock);
14915       p->locallyblocked = 1;
14916       ast_mutex_unlock(&p->lock);
14917       if (channo != -1) {
14918          break;
14919       }
14920    }
14921    if ((channo != -1) && !p) {
14922       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14923    }
14924    ast_mutex_unlock(&iflock);
14925    return CLI_SUCCESS;
14926 }
14927 
14928 static struct ast_cli_entry dahdi_mfcr2_cli[] = {
14929    AST_CLI_DEFINE(handle_mfcr2_version, "Show OpenR2 library version"),
14930    AST_CLI_DEFINE(handle_mfcr2_show_variants, "Show supported MFC/R2 variants"),
14931    AST_CLI_DEFINE(handle_mfcr2_show_channels, "Show MFC/R2 channels"),
14932    AST_CLI_DEFINE(handle_mfcr2_set_debug, "Set MFC/R2 channel logging level"),
14933    AST_CLI_DEFINE(handle_mfcr2_call_files, "Enable/Disable MFC/R2 call files"),
14934    AST_CLI_DEFINE(handle_mfcr2_set_idle, "Reset MFC/R2 channel forcing it to IDLE"),
14935    AST_CLI_DEFINE(handle_mfcr2_set_blocked, "Reset MFC/R2 channel forcing it to BLOCKED"),
14936 };
14937 
14938 #endif /* HAVE_OPENR2 */
14939 
14940 static char *dahdi_destroy_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14941 {
14942    int channel;
14943    int ret;
14944    switch (cmd) {
14945    case CLI_INIT:
14946       e->command = "dahdi destroy channel";
14947       e->usage =
14948          "Usage: dahdi destroy channel <chan num>\n"
14949          "  DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.  Immediately removes a given channel, whether it is in use or not\n";
14950       return NULL;
14951    case CLI_GENERATE:
14952       return NULL;
14953    }
14954    if (a->argc != 4)
14955       return CLI_SHOWUSAGE;
14956 
14957    channel = atoi(a->argv[3]);
14958    ret = dahdi_destroy_channel_bynum(channel);
14959    return ( RESULT_SUCCESS == ret ) ? CLI_SUCCESS : CLI_FAILURE;
14960 }
14961 
14962 static void dahdi_softhangup_all(void)
14963 {
14964    struct dahdi_pvt *p;
14965 retry:
14966    ast_mutex_lock(&iflock);
14967    for (p = iflist; p; p = p->next) {
14968       ast_mutex_lock(&p->lock);
14969       if (p->owner && !p->restartpending) {
14970          if (ast_channel_trylock(p->owner)) {
14971             if (option_debug > 2)
14972                ast_verbose("Avoiding deadlock\n");
14973             /* Avoid deadlock since you're not supposed to lock iflock or pvt before a channel */
14974             ast_mutex_unlock(&p->lock);
14975             ast_mutex_unlock(&iflock);
14976             goto retry;
14977          }
14978          if (option_debug > 2)
14979             ast_verbose("Softhanging up on %s\n", p->owner->name);
14980          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_EXPLICIT);
14981          p->restartpending = 1;
14982          num_restart_pending++;
14983          ast_channel_unlock(p->owner);
14984       }
14985       ast_mutex_unlock(&p->lock);
14986    }
14987    ast_mutex_unlock(&iflock);
14988 }
14989 
14990 static int setup_dahdi(int reload);
14991 static int dahdi_restart(void)
14992 {
14993 #if defined(HAVE_PRI) || defined(HAVE_SS7)
14994    int i, j;
14995 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
14996    int cancel_code;
14997    struct dahdi_pvt *p;
14998 
14999    ast_mutex_lock(&restart_lock);
15000    ast_verb(1, "Destroying channels and reloading DAHDI configuration.\n");
15001    dahdi_softhangup_all();
15002    ast_verb(4, "Initial softhangup of all DAHDI channels complete.\n");
15003 #ifdef HAVE_OPENR2
15004    dahdi_r2_destroy_links();
15005 #endif
15006 
15007 #if defined(HAVE_PRI)
15008    for (i = 0; i < NUM_SPANS; i++) {
15009       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL)) {
15010          cancel_code = pthread_cancel(pris[i].pri.master);
15011          pthread_kill(pris[i].pri.master, SIGURG);
15012          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);
15013          pthread_join(pris[i].pri.master, NULL);
15014          ast_debug(4, "Joined thread of span %d\n", i);
15015       }
15016    }
15017 #endif
15018 
15019 #if defined(HAVE_SS7)
15020    for (i = 0; i < NUM_SPANS; i++) {
15021       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL)) {
15022          cancel_code = pthread_cancel(linksets[i].ss7.master);
15023          pthread_kill(linksets[i].ss7.master, SIGURG);
15024          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);
15025          pthread_join(linksets[i].ss7.master, NULL);
15026          ast_debug(4, "Joined thread of span %d\n", i);
15027       }
15028    }
15029 #endif   /* defined(HAVE_SS7) */
15030 
15031    ast_mutex_lock(&monlock);
15032    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
15033       cancel_code = pthread_cancel(monitor_thread);
15034       pthread_kill(monitor_thread, SIGURG);
15035       ast_debug(4, "Waiting to join monitor thread with pid=%p, cancel_code=%d\n", (void *) monitor_thread, cancel_code);
15036       pthread_join(monitor_thread, NULL);
15037       ast_debug(4, "Joined monitor thread\n");
15038    }
15039    monitor_thread = AST_PTHREADT_NULL; /* prepare to restart thread in setup_dahdi once channels are reconfigured */
15040 
15041    ast_mutex_lock(&ss_thread_lock);
15042    while (ss_thread_count > 0) { /* let ss_threads finish and run dahdi_hangup before dahvi_pvts are destroyed */
15043       int x = DAHDI_FLASH;
15044       ast_debug(3, "Waiting on %d analog_ss_thread(s) to finish\n", ss_thread_count);
15045 
15046       ast_mutex_lock(&iflock);
15047       for (p = iflist; p; p = p->next) {
15048          if (p->owner) {
15049             /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
15050             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
15051          }
15052       }
15053       ast_mutex_unlock(&iflock);
15054       ast_cond_wait(&ss_thread_complete, &ss_thread_lock);
15055    }
15056 
15057    /* ensure any created channels before monitor threads were stopped are hungup */
15058    dahdi_softhangup_all();
15059    ast_verb(4, "Final softhangup of all DAHDI channels complete.\n");
15060    destroy_all_channels();
15061    ast_debug(1, "Channels destroyed. Now re-reading config. %d active channels remaining.\n", ast_active_channels());
15062 
15063    ast_mutex_unlock(&monlock);
15064 
15065 #ifdef HAVE_PRI
15066    for (i = 0; i < NUM_SPANS; i++) {
15067       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++)
15068          dahdi_close_pri_fd(&(pris[i]), j);
15069    }
15070 
15071    memset(pris, 0, sizeof(pris));
15072    for (i = 0; i < NUM_SPANS; i++) {
15073       sig_pri_init_pri(&pris[i].pri);
15074    }
15075    pri_set_error(dahdi_pri_error);
15076    pri_set_message(dahdi_pri_message);
15077 #endif
15078 #if defined(HAVE_SS7)
15079    for (i = 0; i < NUM_SPANS; i++) {
15080       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++)
15081          dahdi_close_ss7_fd(&(linksets[i]), j);
15082    }
15083 
15084    memset(linksets, 0, sizeof(linksets));
15085    for (i = 0; i < NUM_SPANS; i++) {
15086       sig_ss7_init_linkset(&linksets[i].ss7);
15087    }
15088    ss7_set_error(dahdi_ss7_error);
15089    ss7_set_message(dahdi_ss7_message);
15090 #endif   /* defined(HAVE_SS7) */
15091 
15092    if (setup_dahdi(2) != 0) {
15093       ast_log(LOG_WARNING, "Reload channels from dahdi config failed!\n");
15094       ast_mutex_unlock(&ss_thread_lock);
15095       return 1;
15096    }
15097    ast_mutex_unlock(&ss_thread_lock);
15098    ast_mutex_unlock(&restart_lock);
15099    return 0;
15100 }
15101 
15102 static char *dahdi_restart_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15103 {
15104    switch (cmd) {
15105    case CLI_INIT:
15106       e->command = "dahdi restart";
15107       e->usage =
15108          "Usage: dahdi restart\n"
15109          "  Restarts the DAHDI channels: destroys them all and then\n"
15110          "  re-reads them from chan_dahdi.conf.\n"
15111          "  Note that this will STOP any running CALL on DAHDI channels.\n"
15112          "";
15113       return NULL;
15114    case CLI_GENERATE:
15115       return NULL;
15116    }
15117    if (a->argc != 2)
15118       return CLI_SHOWUSAGE;
15119 
15120    if (dahdi_restart() != 0)
15121       return CLI_FAILURE;
15122    return CLI_SUCCESS;
15123 }
15124 
15125 static int action_dahdirestart(struct mansession *s, const struct message *m)
15126 {
15127    if (dahdi_restart() != 0) {
15128       astman_send_error(s, m, "Failed rereading DAHDI configuration");
15129       return 1;
15130    }
15131    astman_send_ack(s, m, "DAHDIRestart: Success");
15132    return 0;
15133 }
15134 
15135 static char *dahdi_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15136 {
15137 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
15138 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
15139    unsigned int targetnum = 0;
15140    int filtertype = 0;
15141    struct dahdi_pvt *tmp = NULL;
15142    char tmps[20] = "";
15143    char statestr[20] = "";
15144    char blockstr[20] = "";
15145 
15146    switch (cmd) {
15147    case CLI_INIT:
15148       e->command = "dahdi show channels [group|context]";
15149       e->usage =
15150          "Usage: dahdi show channels [ group <group> | context <context> ]\n"
15151          "  Shows a list of available channels with optional filtering\n"
15152          "  <group> must be a number between 0 and 63\n";
15153       return NULL;
15154    case CLI_GENERATE:
15155       return NULL;
15156    }
15157 
15158    /* syntax: dahdi show channels [ group <group> | context <context> ] */
15159 
15160    if (!((a->argc == 3) || (a->argc == 5)))
15161       return CLI_SHOWUSAGE;
15162 
15163    if (a->argc == 5) {
15164       if (!strcasecmp(a->argv[3], "group")) {
15165          targetnum = atoi(a->argv[4]);
15166          if ((targetnum < 0) || (targetnum > 63))
15167             return CLI_SHOWUSAGE;
15168          targetnum = 1 << targetnum;
15169          filtertype = 1;
15170       } else if (!strcasecmp(a->argv[3], "context")) {
15171          filtertype = 2;
15172       }
15173    }
15174 
15175    ast_cli(a->fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret", "Blocked", "State");
15176    ast_mutex_lock(&iflock);
15177    for (tmp = iflist; tmp; tmp = tmp->next) {
15178       if (filtertype) {
15179          switch(filtertype) {
15180          case 1: /* dahdi show channels group <group> */
15181             if (!(tmp->group & targetnum)) {
15182                continue;
15183             }
15184             break;
15185          case 2: /* dahdi show channels context <context> */
15186             if (strcasecmp(tmp->context, a->argv[4])) {
15187                continue;
15188             }
15189             break;
15190          default:
15191             break;
15192          }
15193       }
15194       if (tmp->channel > 0) {
15195          snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
15196       } else
15197          ast_copy_string(tmps, "pseudo", sizeof(tmps));
15198 
15199       if (tmp->locallyblocked)
15200          blockstr[0] = 'L';
15201       else
15202          blockstr[0] = ' ';
15203 
15204       if (tmp->remotelyblocked)
15205          blockstr[1] = 'R';
15206       else
15207          blockstr[1] = ' ';
15208 
15209       blockstr[2] = '\0';
15210 
15211       snprintf(statestr, sizeof(statestr), "%s", "In Service");
15212 
15213       ast_cli(a->fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret, blockstr, statestr);
15214    }
15215    ast_mutex_unlock(&iflock);
15216    return CLI_SUCCESS;
15217 #undef FORMAT
15218 #undef FORMAT2
15219 }
15220 
15221 static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15222 {
15223    int channel;
15224    struct dahdi_pvt *tmp = NULL;
15225    struct dahdi_confinfo ci;
15226    struct dahdi_params ps;
15227    int x;
15228 
15229    switch (cmd) {
15230    case CLI_INIT:
15231       e->command = "dahdi show channel";
15232       e->usage =
15233          "Usage: dahdi show channel <chan num>\n"
15234          "  Detailed information about a given channel\n";
15235       return NULL;
15236    case CLI_GENERATE:
15237       return NULL;
15238    }
15239 
15240    if (a->argc != 4)
15241       return CLI_SHOWUSAGE;
15242 
15243    channel = atoi(a->argv[3]);
15244 
15245    ast_mutex_lock(&iflock);
15246    for (tmp = iflist; tmp; tmp = tmp->next) {
15247       if (tmp->channel == channel) {
15248          ast_cli(a->fd, "Channel: %d\n", tmp->channel);
15249          ast_cli(a->fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].dfd);
15250          ast_cli(a->fd, "Span: %d\n", tmp->span);
15251          ast_cli(a->fd, "Extension: %s\n", tmp->exten);
15252          ast_cli(a->fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
15253          ast_cli(a->fd, "Context: %s\n", tmp->context);
15254          ast_cli(a->fd, "Caller ID: %s\n", tmp->cid_num);
15255          ast_cli(a->fd, "Calling TON: %d\n", tmp->cid_ton);
15256 #if defined(HAVE_PRI)
15257 #if defined(HAVE_PRI_SUBADDR)
15258          ast_cli(a->fd, "Caller ID subaddress: %s\n", tmp->cid_subaddr);
15259 #endif   /* defined(HAVE_PRI_SUBADDR) */
15260 #endif   /* defined(HAVE_PRI) */
15261          ast_cli(a->fd, "Caller ID name: %s\n", tmp->cid_name);
15262          ast_cli(a->fd, "Mailbox: %s\n", S_OR(tmp->mailbox, "none"));
15263          if (tmp->vars) {
15264             struct ast_variable *v;
15265             ast_cli(a->fd, "Variables:\n");
15266             for (v = tmp->vars ; v ; v = v->next)
15267                ast_cli(a->fd, "       %s = %s\n", v->name, v->value);
15268          }
15269          ast_cli(a->fd, "Destroy: %d\n", tmp->destroy);
15270          ast_cli(a->fd, "InAlarm: %d\n", tmp->inalarm);
15271          ast_cli(a->fd, "Signalling Type: %s\n", sig2str(tmp->sig));
15272          ast_cli(a->fd, "Radio: %d\n", tmp->radio);
15273          ast_cli(a->fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
15274          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)" : "");
15275          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)" : "");
15276          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)" : "");
15277          ast_cli(a->fd, "Confno: %d\n", tmp->confno);
15278          ast_cli(a->fd, "Propagated Conference: %d\n", tmp->propconfno);
15279          ast_cli(a->fd, "Real in conference: %d\n", tmp->inconference);
15280          ast_cli(a->fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
15281          ast_cli(a->fd, "Busy Detection: %s\n", tmp->busydetect ? "yes" : "no");
15282          if (tmp->busydetect) {
15283 #if defined(BUSYDETECT_TONEONLY)
15284             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_TONEONLY\n");
15285 #elif defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
15286             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_COMPARE_TONE_AND_SILENCE\n");
15287 #endif
15288 #ifdef BUSYDETECT_DEBUG
15289             ast_cli(a->fd, "    Busy Detector Debug: Enabled\n");
15290 #endif
15291             ast_cli(a->fd, "    Busy Count: %d\n", tmp->busycount);
15292             ast_cli(a->fd, "    Busy Pattern: %d,%d\n", tmp->busy_tonelength, tmp->busy_quietlength);
15293          }
15294          ast_cli(a->fd, "TDD: %s\n", tmp->tdd ? "yes" : "no");
15295          ast_cli(a->fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
15296          ast_cli(a->fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
15297          ast_cli(a->fd, "Default law: %s\n", tmp->law_default == DAHDI_LAW_MULAW ? "ulaw" : tmp->law_default == DAHDI_LAW_ALAW ? "alaw" : "unknown");
15298          ast_cli(a->fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
15299          ast_cli(a->fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
15300          ast_cli(a->fd, "Gains (RX/TX): %.2f/%.2f\n", tmp->rxgain, tmp->txgain);
15301          ast_cli(a->fd, "Dynamic Range Compression (RX/TX): %.2f/%.2f\n", tmp->rxdrc, tmp->txdrc);
15302          ast_cli(a->fd, "DND: %s\n", dahdi_dnd(tmp, -1) ? "yes" : "no");
15303          ast_cli(a->fd, "Echo Cancellation:\n");
15304 
15305          if (tmp->echocancel.head.tap_length) {
15306             ast_cli(a->fd, "\t%d taps\n", tmp->echocancel.head.tap_length);
15307             for (x = 0; x < tmp->echocancel.head.param_count; x++) {
15308                ast_cli(a->fd, "\t\t%s: %ud\n", tmp->echocancel.params[x].name, tmp->echocancel.params[x].value);
15309             }
15310             ast_cli(a->fd, "\t%scurrently %s\n", tmp->echocanbridged ? "" : "(unless TDM bridged) ", tmp->echocanon ? "ON" : "OFF");
15311          } else {
15312             ast_cli(a->fd, "\tnone\n");
15313          }
15314          ast_cli(a->fd, "Wait for dialtone: %dms\n", tmp->waitfordialtone);
15315          if (tmp->master)
15316             ast_cli(a->fd, "Master Channel: %d\n", tmp->master->channel);
15317          for (x = 0; x < MAX_SLAVES; x++) {
15318             if (tmp->slaves[x])
15319                ast_cli(a->fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
15320          }
15321 #ifdef HAVE_OPENR2
15322          if (tmp->mfcr2) {
15323             char calldir[OR2_MAX_PATH];
15324             openr2_context_t *r2context = openr2_chan_get_context(tmp->r2chan);
15325             openr2_variant_t r2variant = openr2_context_get_variant(r2context);
15326             ast_cli(a->fd, "MFC/R2 MF State: %s\n", openr2_chan_get_mf_state_string(tmp->r2chan));
15327             ast_cli(a->fd, "MFC/R2 MF Group: %s\n", openr2_chan_get_mf_group_string(tmp->r2chan));
15328             ast_cli(a->fd, "MFC/R2 State: %s\n", openr2_chan_get_r2_state_string(tmp->r2chan));
15329             ast_cli(a->fd, "MFC/R2 Call State: %s\n", openr2_chan_get_call_state_string(tmp->r2chan));
15330             ast_cli(a->fd, "MFC/R2 Call Files Enabled: %s\n", openr2_chan_get_call_files_enabled(tmp->r2chan) ? "Yes" : "No");
15331             ast_cli(a->fd, "MFC/R2 Variant: %s\n", openr2_proto_get_variant_string(r2variant));
15332             ast_cli(a->fd, "MFC/R2 Max ANI: %d\n", openr2_context_get_max_ani(r2context));
15333             ast_cli(a->fd, "MFC/R2 Max DNIS: %d\n", openr2_context_get_max_dnis(r2context));
15334             ast_cli(a->fd, "MFC/R2 Get ANI First: %s\n", openr2_context_get_ani_first(r2context) ? "Yes" : "No");
15335 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
15336             ast_cli(a->fd, "MFC/R2 Skip Category Request: %s\n", openr2_context_get_skip_category_request(r2context) ? "Yes" : "No");
15337 #endif
15338             ast_cli(a->fd, "MFC/R2 Immediate Accept: %s\n", openr2_context_get_immediate_accept(r2context) ? "Yes" : "No");
15339             ast_cli(a->fd, "MFC/R2 Accept on Offer: %s\n", tmp->mfcr2_accept_on_offer ? "Yes" : "No");
15340             ast_cli(a->fd, "MFC/R2 Charge Calls: %s\n", tmp->mfcr2_charge_calls ? "Yes" : "No");
15341             ast_cli(a->fd, "MFC/R2 Allow Collect Calls: %s\n", tmp->mfcr2_allow_collect_calls ? "Yes" : "No");
15342             ast_cli(a->fd, "MFC/R2 Forced Release: %s\n", tmp->mfcr2_forced_release ? "Yes" : "No");
15343             ast_cli(a->fd, "MFC/R2 MF Back Timeout: %dms\n", openr2_context_get_mf_back_timeout(r2context));
15344             ast_cli(a->fd, "MFC/R2 R2 Metering Pulse Timeout: %dms\n", openr2_context_get_metering_pulse_timeout(r2context));
15345             ast_cli(a->fd, "MFC/R2 Rx CAS: %s\n", openr2_chan_get_rx_cas_string(tmp->r2chan));
15346             ast_cli(a->fd, "MFC/R2 Tx CAS: %s\n", openr2_chan_get_tx_cas_string(tmp->r2chan));
15347             ast_cli(a->fd, "MFC/R2 MF Tx Signal: %d\n", openr2_chan_get_tx_mf_signal(tmp->r2chan));
15348             ast_cli(a->fd, "MFC/R2 MF Rx Signal: %d\n", openr2_chan_get_rx_mf_signal(tmp->r2chan));
15349             ast_cli(a->fd, "MFC/R2 Call Files Directory: %s\n", openr2_context_get_log_directory(r2context, calldir, sizeof(calldir)));
15350          }
15351 #endif
15352 #if defined(HAVE_SS7)
15353          if (tmp->ss7) {
15354             struct sig_ss7_chan *chan = tmp->sig_pvt;
15355 
15356             ast_cli(a->fd, "CIC: %d\n", chan->cic);
15357          }
15358 #endif   /* defined(HAVE_SS7) */
15359 #ifdef HAVE_PRI
15360          if (tmp->pri) {
15361             struct sig_pri_chan *chan = tmp->sig_pvt;
15362 
15363             ast_cli(a->fd, "PRI Flags: ");
15364             if (chan->resetting)
15365                ast_cli(a->fd, "Resetting ");
15366             if (chan->call)
15367                ast_cli(a->fd, "Call ");
15368             if (chan->allocated) {
15369                ast_cli(a->fd, "Allocated ");
15370             }
15371             ast_cli(a->fd, "\n");
15372             if (tmp->logicalspan)
15373                ast_cli(a->fd, "PRI Logical Span: %d\n", tmp->logicalspan);
15374             else
15375                ast_cli(a->fd, "PRI Logical Span: Implicit\n");
15376          }
15377 #endif
15378          memset(&ci, 0, sizeof(ci));
15379          ps.channo = tmp->channel;
15380          if (tmp->subs[SUB_REAL].dfd > -1) {
15381             memset(&ci, 0, sizeof(ci));
15382             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
15383                ast_cli(a->fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
15384             }
15385             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONFMUTE, &x)) {
15386                ast_cli(a->fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
15387             }
15388             memset(&ps, 0, sizeof(ps));
15389             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
15390                ast_log(LOG_WARNING, "Failed to get parameters on channel %d: %s\n", tmp->channel, strerror(errno));
15391             } else {
15392                ast_cli(a->fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
15393             }
15394          }
15395          ast_mutex_unlock(&iflock);
15396          return CLI_SUCCESS;
15397       }
15398    }
15399    ast_mutex_unlock(&iflock);
15400 
15401    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15402    return CLI_FAILURE;
15403 }
15404 
15405 static char *handle_dahdi_show_cadences(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15406 {
15407    int i, j;
15408    switch (cmd) {
15409    case CLI_INIT:
15410       e->command = "dahdi show cadences";
15411       e->usage =
15412          "Usage: dahdi show cadences\n"
15413          "       Shows all cadences currently defined\n";
15414       return NULL;
15415    case CLI_GENERATE:
15416       return NULL;
15417    }
15418    for (i = 0; i < num_cadence; i++) {
15419       char output[1024];
15420       char tmp[16], tmp2[64];
15421       snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
15422       term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
15423 
15424       for (j = 0; j < 16; j++) {
15425          if (cadences[i].ringcadence[j] == 0)
15426             break;
15427          snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
15428          if (cidrings[i] * 2 - 1 == j)
15429             term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
15430          else
15431             term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
15432          if (j != 0)
15433             strncat(output, ",", sizeof(output) - strlen(output) - 1);
15434          strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
15435       }
15436       ast_cli(a->fd,"%s\n",output);
15437    }
15438    return CLI_SUCCESS;
15439 }
15440 
15441 /* Based on irqmiss.c */
15442 static char *dahdi_show_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15443 {
15444    #define FORMAT "%-40.40s %-7.7s %-6d %-6d %-6d %-3.3s %-4.4s %-8.8s %s\n"
15445    #define FORMAT2 "%-40.40s %-7.7s %-6.6s %-6.6s %-6.6s %-3.3s %-4.4s %-8.8s %s\n"
15446    int span;
15447    int res;
15448    char alarmstr[50];
15449 
15450    int ctl;
15451    struct dahdi_spaninfo s;
15452 
15453    switch (cmd) {
15454    case CLI_INIT:
15455       e->command = "dahdi show status";
15456       e->usage =
15457          "Usage: dahdi show status\n"
15458          "       Shows a list of DAHDI cards with status\n";
15459       return NULL;
15460    case CLI_GENERATE:
15461       return NULL;
15462    }
15463    ctl = open("/dev/dahdi/ctl", O_RDWR);
15464    if (ctl < 0) {
15465       ast_cli(a->fd, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
15466       return CLI_FAILURE;
15467    }
15468    ast_cli(a->fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC", "Framing", "Coding", "Options", "LBO");
15469 
15470    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
15471       s.spanno = span;
15472       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
15473       if (res) {
15474          continue;
15475       }
15476       alarmstr[0] = '\0';
15477       if (s.alarms > 0) {
15478          if (s.alarms & DAHDI_ALARM_BLUE)
15479             strcat(alarmstr, "BLU/");
15480          if (s.alarms & DAHDI_ALARM_YELLOW)
15481             strcat(alarmstr, "YEL/");
15482          if (s.alarms & DAHDI_ALARM_RED)
15483             strcat(alarmstr, "RED/");
15484          if (s.alarms & DAHDI_ALARM_LOOPBACK)
15485             strcat(alarmstr, "LB/");
15486          if (s.alarms & DAHDI_ALARM_RECOVER)
15487             strcat(alarmstr, "REC/");
15488          if (s.alarms & DAHDI_ALARM_NOTOPEN)
15489             strcat(alarmstr, "NOP/");
15490          if (!strlen(alarmstr))
15491             strcat(alarmstr, "UUU/");
15492          if (strlen(alarmstr)) {
15493             /* Strip trailing / */
15494             alarmstr[strlen(alarmstr) - 1] = '\0';
15495          }
15496       } else {
15497          if (s.numchans)
15498             strcpy(alarmstr, "OK");
15499          else
15500             strcpy(alarmstr, "UNCONFIGURED");
15501       }
15502 
15503       ast_cli(a->fd, FORMAT, s.desc, alarmstr, s.irqmisses, s.bpvcount, s.crc4count,
15504          s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
15505          s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
15506          s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
15507          "CAS",
15508          s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
15509          s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
15510          s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
15511          "Unk",
15512          s.lineconfig & DAHDI_CONFIG_CRC4 ?
15513             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
15514             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "",
15515          lbostr[s.lbo]
15516          );
15517    }
15518    close(ctl);
15519 
15520    return CLI_SUCCESS;
15521 #undef FORMAT
15522 #undef FORMAT2
15523 }
15524 
15525 static char *dahdi_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15526 {
15527    int pseudo_fd = -1;
15528    struct dahdi_versioninfo vi;
15529 
15530    switch (cmd) {
15531    case CLI_INIT:
15532       e->command = "dahdi show version";
15533       e->usage =
15534          "Usage: dahdi show version\n"
15535          "       Shows the DAHDI version in use\n";
15536       return NULL;
15537    case CLI_GENERATE:
15538       return NULL;
15539    }
15540    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
15541       ast_cli(a->fd, "Failed to open control file to get version.\n");
15542       return CLI_SUCCESS;
15543    }
15544 
15545    strcpy(vi.version, "Unknown");
15546    strcpy(vi.echo_canceller, "Unknown");
15547 
15548    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi))
15549       ast_cli(a->fd, "Failed to get DAHDI version: %s\n", strerror(errno));
15550    else
15551       ast_cli(a->fd, "DAHDI Version: %s Echo Canceller: %s\n", vi.version, vi.echo_canceller);
15552 
15553    close(pseudo_fd);
15554 
15555    return CLI_SUCCESS;
15556 }
15557 
15558 static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15559 {
15560    int channel;
15561    int gain;
15562    int tx;
15563    struct dahdi_hwgain hwgain;
15564    struct dahdi_pvt *tmp = NULL;
15565 
15566    switch (cmd) {
15567    case CLI_INIT:
15568       e->command = "dahdi set hwgain";
15569       e->usage =
15570          "Usage: dahdi set hwgain <rx|tx> <chan#> <gain>\n"
15571          "  Sets the hardware gain on a a given channel, overriding the\n"
15572          "   value provided at module loadtime, whether the channel is in\n"
15573          "   use or not.  Changes take effect immediately.\n"
15574          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15575          "   <chan num> is the channel number relative to the device\n"
15576          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15577       return NULL;
15578    case CLI_GENERATE:
15579       return NULL;
15580    }
15581 
15582    if (a->argc != 6)
15583       return CLI_SHOWUSAGE;
15584 
15585    if (!strcasecmp("rx", a->argv[3]))
15586       tx = 0; /* rx */
15587    else if (!strcasecmp("tx", a->argv[3]))
15588       tx = 1; /* tx */
15589    else
15590       return CLI_SHOWUSAGE;
15591 
15592    channel = atoi(a->argv[4]);
15593    gain = atof(a->argv[5])*10.0;
15594 
15595    ast_mutex_lock(&iflock);
15596 
15597    for (tmp = iflist; tmp; tmp = tmp->next) {
15598 
15599       if (tmp->channel != channel)
15600          continue;
15601 
15602       if (tmp->subs[SUB_REAL].dfd == -1)
15603          break;
15604 
15605       hwgain.newgain = gain;
15606       hwgain.tx = tx;
15607       if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_HWGAIN, &hwgain) < 0) {
15608          ast_cli(a->fd, "Unable to set the hardware gain for channel %d: %s\n", channel, strerror(errno));
15609          ast_mutex_unlock(&iflock);
15610          return CLI_FAILURE;
15611       }
15612       ast_cli(a->fd, "hardware %s gain set to %d (%.1f dB) on channel %d\n",
15613          tx ? "tx" : "rx", gain, (float)gain/10.0, channel);
15614       break;
15615    }
15616 
15617    ast_mutex_unlock(&iflock);
15618 
15619    if (tmp)
15620       return CLI_SUCCESS;
15621 
15622    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15623    return CLI_FAILURE;
15624 
15625 }
15626 
15627 static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15628 {
15629    int channel;
15630    float gain;
15631    int tx;
15632    int res;
15633    struct dahdi_pvt *tmp = NULL;
15634 
15635    switch (cmd) {
15636    case CLI_INIT:
15637       e->command = "dahdi set swgain";
15638       e->usage =
15639          "Usage: dahdi set swgain <rx|tx> <chan#> <gain>\n"
15640          "  Sets the software gain on a a given channel, overriding the\n"
15641          "   value provided at module loadtime, whether the channel is in\n"
15642          "   use or not.  Changes take effect immediately.\n"
15643          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15644          "   <chan num> is the channel number relative to the device\n"
15645          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15646       return NULL;
15647    case CLI_GENERATE:
15648       return NULL;
15649    }
15650 
15651    if (a->argc != 6)
15652       return CLI_SHOWUSAGE;
15653 
15654    if (!strcasecmp("rx", a->argv[3]))
15655       tx = 0; /* rx */
15656    else if (!strcasecmp("tx", a->argv[3]))
15657       tx = 1; /* tx */
15658    else
15659       return CLI_SHOWUSAGE;
15660 
15661    channel = atoi(a->argv[4]);
15662    gain = atof(a->argv[5]);
15663 
15664    ast_mutex_lock(&iflock);
15665    for (tmp = iflist; tmp; tmp = tmp->next) {
15666 
15667       if (tmp->channel != channel)
15668          continue;
15669 
15670       if (tmp->subs[SUB_REAL].dfd == -1)
15671          break;
15672 
15673       if (tx)
15674          res = set_actual_txgain(tmp->subs[SUB_REAL].dfd, gain, tmp->txdrc, tmp->law);
15675       else
15676          res = set_actual_rxgain(tmp->subs[SUB_REAL].dfd, gain, tmp->rxdrc, tmp->law);
15677 
15678       if (res) {
15679          ast_cli(a->fd, "Unable to set the software gain for channel %d\n", channel);
15680          ast_mutex_unlock(&iflock);
15681          return CLI_FAILURE;
15682       }
15683 
15684       ast_cli(a->fd, "software %s gain set to %.1f on channel %d\n",
15685          tx ? "tx" : "rx", gain, channel);
15686       break;
15687    }
15688    ast_mutex_unlock(&iflock);
15689 
15690    if (tmp)
15691       return CLI_SUCCESS;
15692 
15693    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15694    return CLI_FAILURE;
15695 
15696 }
15697 
15698 static char *dahdi_set_dnd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15699 {
15700    int channel;
15701    int on;
15702    struct dahdi_pvt *dahdi_chan = NULL;
15703 
15704    switch (cmd) {
15705    case CLI_INIT:
15706       e->command = "dahdi set dnd";
15707       e->usage =
15708          "Usage: dahdi set dnd <chan#> <on|off>\n"
15709          "  Sets/resets DND (Do Not Disturb) mode on a channel.\n"
15710          "  Changes take effect immediately.\n"
15711          "  <chan num> is the channel number\n"
15712          "  <on|off> Enable or disable DND mode?\n"
15713          ;
15714       return NULL;
15715    case CLI_GENERATE:
15716       return NULL;
15717    }
15718 
15719    if (a->argc != 5)
15720       return CLI_SHOWUSAGE;
15721 
15722    if ((channel = atoi(a->argv[3])) <= 0) {
15723       ast_cli(a->fd, "Expected channel number, got '%s'\n", a->argv[3]);
15724       return CLI_SHOWUSAGE;
15725    }
15726 
15727    if (ast_true(a->argv[4]))
15728       on = 1;
15729    else if (ast_false(a->argv[4]))
15730       on = 0;
15731    else {
15732       ast_cli(a->fd, "Expected 'on' or 'off', got '%s'\n", a->argv[4]);
15733       return CLI_SHOWUSAGE;
15734    }
15735 
15736    ast_mutex_lock(&iflock);
15737    for (dahdi_chan = iflist; dahdi_chan; dahdi_chan = dahdi_chan->next) {
15738       if (dahdi_chan->channel != channel)
15739          continue;
15740 
15741       /* Found the channel. Actually set it */
15742       dahdi_dnd(dahdi_chan, on);
15743       break;
15744    }
15745    ast_mutex_unlock(&iflock);
15746 
15747    if (!dahdi_chan) {
15748       ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15749       return CLI_FAILURE;
15750    }
15751 
15752    return CLI_SUCCESS;
15753 }
15754 
15755 static struct ast_cli_entry dahdi_cli[] = {
15756    AST_CLI_DEFINE(handle_dahdi_show_cadences, "List cadences"),
15757    AST_CLI_DEFINE(dahdi_show_channels, "Show active DAHDI channels"),
15758    AST_CLI_DEFINE(dahdi_show_channel, "Show information on a channel"),
15759    AST_CLI_DEFINE(dahdi_destroy_channel, "Destroy a channel"),
15760    AST_CLI_DEFINE(dahdi_restart_cmd, "Fully restart DAHDI channels"),
15761    AST_CLI_DEFINE(dahdi_show_status, "Show all DAHDI cards status"),
15762    AST_CLI_DEFINE(dahdi_show_version, "Show the DAHDI version in use"),
15763    AST_CLI_DEFINE(dahdi_set_hwgain, "Set hardware gain on a channel"),
15764    AST_CLI_DEFINE(dahdi_set_swgain, "Set software gain on a channel"),
15765    AST_CLI_DEFINE(dahdi_set_dnd, "Sets/resets DND (Do Not Disturb) mode on a channel"),
15766 };
15767 
15768 #define TRANSFER  0
15769 #define HANGUP    1
15770 
15771 static int dahdi_fake_event(struct dahdi_pvt *p, int mode)
15772 {
15773    if (p) {
15774       switch (mode) {
15775       case TRANSFER:
15776          p->fake_event = DAHDI_EVENT_WINKFLASH;
15777          break;
15778       case HANGUP:
15779          p->fake_event = DAHDI_EVENT_ONHOOK;
15780          break;
15781       default:
15782          ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
15783       }
15784    }
15785    return 0;
15786 }
15787 static struct dahdi_pvt *find_channel(int channel)
15788 {
15789    struct dahdi_pvt *p;
15790 
15791    ast_mutex_lock(&iflock);
15792    for (p = iflist; p; p = p->next) {
15793       if (p->channel == channel) {
15794          break;
15795       }
15796    }
15797    ast_mutex_unlock(&iflock);
15798    return p;
15799 }
15800 
15801 /*!
15802  * \internal
15803  * \brief Get private struct using given numeric channel string.
15804  *
15805  * \param channel Numeric channel number string get private struct.
15806  *
15807  * \retval pvt on success.
15808  * \retval NULL on error.
15809  */
15810 static struct dahdi_pvt *find_channel_from_str(const char *channel)
15811 {
15812    int chan_num;
15813 
15814    if (sscanf(channel, "%30d", &chan_num) != 1) {
15815       /* Not numeric string. */
15816       return NULL;
15817    }
15818 
15819    return find_channel(chan_num);
15820 }
15821 
15822 static int action_dahdidndon(struct mansession *s, const struct message *m)
15823 {
15824    struct dahdi_pvt *p;
15825    const char *channel = astman_get_header(m, "DAHDIChannel");
15826 
15827    if (ast_strlen_zero(channel)) {
15828       astman_send_error(s, m, "No channel specified");
15829       return 0;
15830    }
15831    p = find_channel_from_str(channel);
15832    if (!p) {
15833       astman_send_error(s, m, "No such channel");
15834       return 0;
15835    }
15836    dahdi_dnd(p, 1);
15837    astman_send_ack(s, m, "DND Enabled");
15838    return 0;
15839 }
15840 
15841 static int action_dahdidndoff(struct mansession *s, const struct message *m)
15842 {
15843    struct dahdi_pvt *p;
15844    const char *channel = astman_get_header(m, "DAHDIChannel");
15845 
15846    if (ast_strlen_zero(channel)) {
15847       astman_send_error(s, m, "No channel specified");
15848       return 0;
15849    }
15850    p = find_channel_from_str(channel);
15851    if (!p) {
15852       astman_send_error(s, m, "No such channel");
15853       return 0;
15854    }
15855    dahdi_dnd(p, 0);
15856    astman_send_ack(s, m, "DND Disabled");
15857    return 0;
15858 }
15859 
15860 static int action_transfer(struct mansession *s, const struct message *m)
15861 {
15862    struct dahdi_pvt *p;
15863    const char *channel = astman_get_header(m, "DAHDIChannel");
15864 
15865    if (ast_strlen_zero(channel)) {
15866       astman_send_error(s, m, "No channel specified");
15867       return 0;
15868    }
15869    p = find_channel_from_str(channel);
15870    if (!p) {
15871       astman_send_error(s, m, "No such channel");
15872       return 0;
15873    }
15874    if (!analog_lib_handles(p->sig, 0, 0)) {
15875       astman_send_error(s, m, "Channel signaling is not analog");
15876       return 0;
15877    }
15878    dahdi_fake_event(p,TRANSFER);
15879    astman_send_ack(s, m, "DAHDITransfer");
15880    return 0;
15881 }
15882 
15883 static int action_transferhangup(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    if (!analog_lib_handles(p->sig, 0, 0)) {
15898       astman_send_error(s, m, "Channel signaling is not analog");
15899       return 0;
15900    }
15901    dahdi_fake_event(p,HANGUP);
15902    astman_send_ack(s, m, "DAHDIHangup");
15903    return 0;
15904 }
15905 
15906 static int action_dahdidialoffhook(struct mansession *s, const struct message *m)
15907 {
15908    struct dahdi_pvt *p;
15909    const char *channel = astman_get_header(m, "DAHDIChannel");
15910    const char *number = astman_get_header(m, "Number");
15911    int i;
15912 
15913    if (ast_strlen_zero(channel)) {
15914       astman_send_error(s, m, "No channel specified");
15915       return 0;
15916    }
15917    if (ast_strlen_zero(number)) {
15918       astman_send_error(s, m, "No number specified");
15919       return 0;
15920    }
15921    p = find_channel_from_str(channel);
15922    if (!p) {
15923       astman_send_error(s, m, "No such channel");
15924       return 0;
15925    }
15926    if (!p->owner) {
15927       astman_send_error(s, m, "Channel does not have it's owner");
15928       return 0;
15929    }
15930    for (i = 0; i < strlen(number); i++) {
15931       struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = number[i] };
15932       dahdi_queue_frame(p, &f);
15933    }
15934    astman_send_ack(s, m, "DAHDIDialOffhook");
15935    return 0;
15936 }
15937 
15938 static int action_dahdishowchannels(struct mansession *s, const struct message *m)
15939 {
15940    struct dahdi_pvt *tmp = NULL;
15941    const char *id = astman_get_header(m, "ActionID");
15942    const char *dahdichannel = astman_get_header(m, "DAHDIChannel");
15943    char idText[256] = "";
15944    int channels = 0;
15945    int dahdichanquery;
15946 
15947    if (!dahdichannel || sscanf(dahdichannel, "%30d", &dahdichanquery) != 1) {
15948       /* Not numeric string. */
15949       dahdichanquery = -1;
15950    }
15951 
15952    astman_send_ack(s, m, "DAHDI channel status will follow");
15953    if (!ast_strlen_zero(id))
15954       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
15955 
15956    ast_mutex_lock(&iflock);
15957 
15958    for (tmp = iflist; tmp; tmp = tmp->next) {
15959       if (tmp->channel > 0) {
15960          int alm;
15961 
15962          /* If a specific channel is queried for, only deliver status for that channel */
15963          if (dahdichanquery > 0 && tmp->channel != dahdichanquery)
15964             continue;
15965 
15966          alm = get_alarms(tmp);
15967          channels++;
15968          if (tmp->owner) {
15969             /* Add data if we have a current call */
15970             astman_append(s,
15971                "Event: DAHDIShowChannels\r\n"
15972                "DAHDIChannel: %d\r\n"
15973                "Channel: %s\r\n"
15974                "Uniqueid: %s\r\n"
15975                "AccountCode: %s\r\n"
15976                "Signalling: %s\r\n"
15977                "SignallingCode: %d\r\n"
15978                "Context: %s\r\n"
15979                "DND: %s\r\n"
15980                "Alarm: %s\r\n"
15981                "%s"
15982                "\r\n",
15983                tmp->channel,
15984                tmp->owner->name,
15985                tmp->owner->uniqueid,
15986                tmp->owner->accountcode,
15987                sig2str(tmp->sig),
15988                tmp->sig,
15989                tmp->context,
15990                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
15991                alarm2str(alm), idText);
15992          } else {
15993             astman_append(s,
15994                "Event: DAHDIShowChannels\r\n"
15995                "DAHDIChannel: %d\r\n"
15996                "Signalling: %s\r\n"
15997                "SignallingCode: %d\r\n"
15998                "Context: %s\r\n"
15999                "DND: %s\r\n"
16000                "Alarm: %s\r\n"
16001                "%s"
16002                "\r\n",
16003                tmp->channel, sig2str(tmp->sig), tmp->sig,
16004                tmp->context,
16005                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
16006                alarm2str(alm), idText);
16007          }
16008       }
16009    }
16010 
16011    ast_mutex_unlock(&iflock);
16012 
16013    astman_append(s,
16014       "Event: DAHDIShowChannelsComplete\r\n"
16015       "%s"
16016       "Items: %d\r\n"
16017       "\r\n",
16018       idText,
16019       channels);
16020    return 0;
16021 }
16022 
16023 #if defined(HAVE_SS7)
16024 static int linkset_addsigchan(int sigchan)
16025 {
16026    struct dahdi_ss7 *link;
16027    int res;
16028    int curfd;
16029    struct dahdi_params params;
16030    struct dahdi_bufferinfo bi;
16031    struct dahdi_spaninfo si;
16032 
16033    if (sigchan < 0) {
16034       ast_log(LOG_ERROR, "Invalid sigchan!\n");
16035       return -1;
16036    }
16037    if (cur_ss7type < 0) {
16038       ast_log(LOG_ERROR, "Unspecified or invalid ss7type\n");
16039       return -1;
16040    }
16041    if (cur_pointcode < 0) {
16042       ast_log(LOG_ERROR, "Unspecified pointcode!\n");
16043       return -1;
16044    }
16045    if (cur_adjpointcode < 0) {
16046       ast_log(LOG_ERROR, "Unspecified adjpointcode!\n");
16047       return -1;
16048    }
16049    if (cur_defaultdpc < 0) {
16050       ast_log(LOG_ERROR, "Unspecified defaultdpc!\n");
16051       return -1;
16052    }
16053    if (cur_networkindicator < 0) {
16054       ast_log(LOG_ERROR, "Invalid networkindicator!\n");
16055       return -1;
16056    }
16057    link = ss7_resolve_linkset(cur_linkset);
16058    if (!link) {
16059       ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
16060       return -1;
16061    }
16062    if (link->ss7.numsigchans >= SIG_SS7_NUM_DCHANS) {
16063       ast_log(LOG_ERROR, "Too many sigchans on linkset %d\n", cur_linkset);
16064       return -1;
16065    }
16066 
16067    curfd = link->ss7.numsigchans;
16068 
16069    /* Open signaling channel */
16070    link->ss7.fds[curfd] = open("/dev/dahdi/channel", O_RDWR, 0600);
16071    if (link->ss7.fds[curfd] < 0) {
16072       ast_log(LOG_ERROR, "Unable to open SS7 sigchan %d (%s)\n", sigchan,
16073          strerror(errno));
16074       return -1;
16075    }
16076    if (ioctl(link->ss7.fds[curfd], DAHDI_SPECIFY, &sigchan) == -1) {
16077       dahdi_close_ss7_fd(link, curfd);
16078       ast_log(LOG_ERROR, "Unable to specify SS7 sigchan %d (%s)\n", sigchan,
16079          strerror(errno));
16080       return -1;
16081    }
16082 
16083    /* Get signaling channel parameters */
16084    memset(&params, 0, sizeof(params));
16085    res = ioctl(link->ss7.fds[curfd], DAHDI_GET_PARAMS, &params);
16086    if (res) {
16087       dahdi_close_ss7_fd(link, curfd);
16088       ast_log(LOG_ERROR, "Unable to get parameters for sigchan %d (%s)\n", sigchan,
16089          strerror(errno));
16090       return -1;
16091    }
16092    if (params.sigtype != DAHDI_SIG_HDLCFCS
16093       && params.sigtype != DAHDI_SIG_HARDHDLC
16094       && params.sigtype != DAHDI_SIG_MTP2) {
16095       dahdi_close_ss7_fd(link, curfd);
16096       ast_log(LOG_ERROR, "sigchan %d is not in HDLC/FCS mode.\n", sigchan);
16097       return -1;
16098    }
16099 
16100    /* Set signaling channel buffer policy. */
16101    memset(&bi, 0, sizeof(bi));
16102    bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
16103    bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
16104    bi.numbufs = 32;
16105    bi.bufsize = 512;
16106    if (ioctl(link->ss7.fds[curfd], DAHDI_SET_BUFINFO, &bi)) {
16107       ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n",
16108          sigchan, strerror(errno));
16109       dahdi_close_ss7_fd(link, curfd);
16110       return -1;
16111    }
16112 
16113    /* Get current signaling channel alarm status. */
16114    memset(&si, 0, sizeof(si));
16115    res = ioctl(link->ss7.fds[curfd], DAHDI_SPANSTAT, &si);
16116    if (res) {
16117       dahdi_close_ss7_fd(link, curfd);
16118       ast_log(LOG_ERROR, "Unable to get span state for sigchan %d (%s)\n", sigchan,
16119          strerror(errno));
16120    }
16121 
16122    res = sig_ss7_add_sigchan(&link->ss7, curfd, cur_ss7type,
16123       (params.sigtype == DAHDI_SIG_MTP2)
16124          ? SS7_TRANSPORT_DAHDIMTP2
16125          : SS7_TRANSPORT_DAHDIDCHAN,
16126       si.alarms, cur_networkindicator, cur_pointcode, cur_adjpointcode);
16127    if (res) {
16128       dahdi_close_ss7_fd(link, curfd);
16129       return -1;
16130    }
16131 
16132    ++link->ss7.numsigchans;
16133 
16134    return 0;
16135 }
16136 #endif   /* defined(HAVE_SS7) */
16137 
16138 #if defined(HAVE_SS7)
16139 static char *handle_ss7_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16140 {
16141    int span;
16142    switch (cmd) {
16143    case CLI_INIT:
16144       e->command = "ss7 set debug {on|off} linkset";
16145       e->usage =
16146          "Usage: ss7 set debug {on|off} linkset <linkset>\n"
16147          "       Enables debugging on a given SS7 linkset\n";
16148       return NULL;
16149    case CLI_GENERATE:
16150       return NULL;
16151    }
16152    if (a->argc < 6)
16153       return CLI_SHOWUSAGE;
16154    span = atoi(a->argv[5]);
16155    if ((span < 1) || (span > NUM_SPANS)) {
16156       ast_cli(a->fd, "Invalid linkset %s.  Should be a number from %d to %d\n", a->argv[5], 1, NUM_SPANS);
16157       return CLI_SUCCESS;
16158    }
16159    if (!linksets[span-1].ss7.ss7) {
16160       ast_cli(a->fd, "No SS7 running on linkset %d\n", span);
16161    } else {
16162       if (!strcasecmp(a->argv[3], "on")) {
16163          linksets[span - 1].ss7.debug = 1;
16164          ss7_set_debug(linksets[span-1].ss7.ss7, SIG_SS7_DEBUG);
16165          ast_cli(a->fd, "Enabled debugging on linkset %d\n", span);
16166       } else {
16167          linksets[span - 1].ss7.debug = 0;
16168          ss7_set_debug(linksets[span-1].ss7.ss7, 0);
16169          ast_cli(a->fd, "Disabled debugging on linkset %d\n", span);
16170       }
16171    }
16172 
16173    return CLI_SUCCESS;
16174 }
16175 #endif   /* defined(HAVE_SS7) */
16176 
16177 #if defined(HAVE_SS7)
16178 static char *handle_ss7_block_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16179 {
16180    int linkset, cic;
16181    int blocked = -1, i;
16182    switch (cmd) {
16183    case CLI_INIT:
16184       e->command = "ss7 block cic";
16185       e->usage =
16186          "Usage: ss7 block cic <linkset> <CIC>\n"
16187          "       Sends a remote blocking request for the given CIC on the specified linkset\n";
16188       return NULL;
16189    case CLI_GENERATE:
16190       return NULL;
16191    }
16192    if (a->argc == 5)
16193       linkset = atoi(a->argv[3]);
16194    else
16195       return CLI_SHOWUSAGE;
16196 
16197    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16198       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16199       return CLI_SUCCESS;
16200    }
16201 
16202    if (!linksets[linkset-1].ss7.ss7) {
16203       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16204       return CLI_SUCCESS;
16205    }
16206 
16207    cic = atoi(a->argv[4]);
16208 
16209    if (cic < 1) {
16210       ast_cli(a->fd, "Invalid CIC specified!\n");
16211       return CLI_SUCCESS;
16212    }
16213 
16214    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16215       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
16216          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
16217          if (!blocked) {
16218             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16219             isup_blo(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16220             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16221          }
16222       }
16223    }
16224 
16225    if (blocked < 0) {
16226       ast_cli(a->fd, "Invalid CIC specified!\n");
16227       return CLI_SUCCESS;
16228    }
16229 
16230    if (!blocked)
16231       ast_cli(a->fd, "Sent blocking request for linkset %d on CIC %d\n", linkset, cic);
16232    else
16233       ast_cli(a->fd, "CIC %d already locally blocked\n", cic);
16234 
16235    /* Break poll on the linkset so it sends our messages */
16236    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16237 
16238    return CLI_SUCCESS;
16239 }
16240 #endif   /* defined(HAVE_SS7) */
16241 
16242 #if defined(HAVE_SS7)
16243 static char *handle_ss7_block_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16244 {
16245    int linkset;
16246    int i;
16247    switch (cmd) {
16248    case CLI_INIT:
16249       e->command = "ss7 block linkset";
16250       e->usage =
16251          "Usage: ss7 block linkset <linkset number>\n"
16252          "       Sends a remote blocking request for all CICs on the given linkset\n";
16253       return NULL;
16254    case CLI_GENERATE:
16255       return NULL;
16256    }
16257    if (a->argc == 4)
16258       linkset = atoi(a->argv[3]);
16259    else
16260       return CLI_SHOWUSAGE;
16261 
16262    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16263       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16264       return CLI_SUCCESS;
16265    }
16266 
16267    if (!linksets[linkset-1].ss7.ss7) {
16268       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16269       return CLI_SUCCESS;
16270    }
16271 
16272    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16273       ast_cli(a->fd, "Sending remote blocking request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
16274       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16275       isup_blo(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16276       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16277    }
16278 
16279    /* Break poll on the linkset so it sends our messages */
16280    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16281 
16282    return CLI_SUCCESS;
16283 }
16284 #endif   /* defined(HAVE_SS7) */
16285 
16286 #if defined(HAVE_SS7)
16287 static char *handle_ss7_unblock_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16288 {
16289    int linkset, cic;
16290    int i, blocked = -1;
16291    switch (cmd) {
16292    case CLI_INIT:
16293       e->command = "ss7 unblock cic";
16294       e->usage =
16295          "Usage: ss7 unblock cic <linkset> <CIC>\n"
16296          "       Sends a remote unblocking request for the given CIC on the specified linkset\n";
16297       return NULL;
16298    case CLI_GENERATE:
16299       return NULL;
16300    }
16301 
16302    if (a->argc == 5)
16303       linkset = atoi(a->argv[3]);
16304    else
16305       return CLI_SHOWUSAGE;
16306 
16307    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16308       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16309       return CLI_SUCCESS;
16310    }
16311 
16312    if (!linksets[linkset-1].ss7.ss7) {
16313       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16314       return CLI_SUCCESS;
16315    }
16316 
16317    cic = atoi(a->argv[4]);
16318 
16319    if (cic < 1) {
16320       ast_cli(a->fd, "Invalid CIC specified!\n");
16321       return CLI_SUCCESS;
16322    }
16323 
16324    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16325       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
16326          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
16327          if (blocked) {
16328             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16329             isup_ubl(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16330             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16331          }
16332       }
16333    }
16334 
16335    if (blocked > 0)
16336       ast_cli(a->fd, "Sent unblocking request for linkset %d on CIC %d\n", linkset, cic);
16337 
16338    /* Break poll on the linkset so it sends our messages */
16339    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16340 
16341    return CLI_SUCCESS;
16342 }
16343 #endif   /* defined(HAVE_SS7) */
16344 
16345 #if defined(HAVE_SS7)
16346 static char *handle_ss7_unblock_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16347 {
16348    int linkset;
16349    int i;
16350    switch (cmd) {
16351    case CLI_INIT:
16352       e->command = "ss7 unblock linkset";
16353       e->usage =
16354          "Usage: ss7 unblock linkset <linkset number>\n"
16355          "       Sends a remote unblocking request for all CICs on the specified linkset\n";
16356       return NULL;
16357    case CLI_GENERATE:
16358       return NULL;
16359    }
16360 
16361    if (a->argc == 4)
16362       linkset = atoi(a->argv[3]);
16363    else
16364       return CLI_SHOWUSAGE;
16365 
16366    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16367       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16368       return CLI_SUCCESS;
16369    }
16370 
16371    if (!linksets[linkset-1].ss7.ss7) {
16372       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16373       return CLI_SUCCESS;
16374    }
16375 
16376    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16377       ast_cli(a->fd, "Sending remote unblock request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
16378       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16379       isup_ubl(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16380       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16381    }
16382 
16383    /* Break poll on the linkset so it sends our messages */
16384    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16385 
16386    return CLI_SUCCESS;
16387 }
16388 #endif   /* defined(HAVE_SS7) */
16389 
16390 #if defined(HAVE_SS7)
16391 static char *handle_ss7_show_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16392 {
16393    int linkset;
16394    struct sig_ss7_linkset *ss7;
16395    switch (cmd) {
16396    case CLI_INIT:
16397       e->command = "ss7 show linkset";
16398       e->usage =
16399          "Usage: ss7 show linkset <span>\n"
16400          "       Shows the status of an SS7 linkset.\n";
16401       return NULL;
16402    case CLI_GENERATE:
16403       return NULL;
16404    }
16405 
16406    if (a->argc < 4)
16407       return CLI_SHOWUSAGE;
16408    linkset = atoi(a->argv[3]);
16409    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16410       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16411       return CLI_SUCCESS;
16412    }
16413    ss7 = &linksets[linkset - 1].ss7;
16414    if (!ss7->ss7) {
16415       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16416       return CLI_SUCCESS;
16417    }
16418 
16419    ast_cli(a->fd, "SS7 linkset %d status: %s\n", linkset, (ss7->state == LINKSET_STATE_UP) ? "Up" : "Down");
16420 
16421    return CLI_SUCCESS;
16422 }
16423 #endif   /* defined(HAVE_SS7) */
16424 
16425 #if defined(HAVE_SS7)
16426 static char *handle_ss7_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16427 {
16428    int linkset;
16429 
16430    switch (cmd) {
16431    case CLI_INIT:
16432       e->command = "ss7 show channels";
16433       e->usage =
16434          "Usage: ss7 show channels\n"
16435          "       Displays SS7 channel information at a glance.\n";
16436       return NULL;
16437    case CLI_GENERATE:
16438       return NULL;
16439    }
16440 
16441    if (a->argc != 3)
16442       return CLI_SHOWUSAGE;
16443 
16444    sig_ss7_cli_show_channels_header(a->fd);
16445    for (linkset = 0; linkset < NUM_SPANS; ++linkset) {
16446       if (linksets[linkset].ss7.ss7) {
16447          sig_ss7_cli_show_channels(a->fd, &linksets[linkset].ss7);
16448       }
16449    }
16450    return CLI_SUCCESS;
16451 }
16452 #endif   /* defined(HAVE_SS7) */
16453 
16454 #if defined(HAVE_SS7)
16455 static char *handle_ss7_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16456 {
16457    switch (cmd) {
16458    case CLI_INIT:
16459       e->command = "ss7 show version";
16460       e->usage =
16461          "Usage: ss7 show version\n"
16462          "  Show the libss7 version\n";
16463       return NULL;
16464    case CLI_GENERATE:
16465       return NULL;
16466    }
16467 
16468    ast_cli(a->fd, "libss7 version: %s\n", ss7_get_version());
16469 
16470    return CLI_SUCCESS;
16471 }
16472 #endif   /* defined(HAVE_SS7) */
16473 
16474 #if defined(HAVE_SS7)
16475 static struct ast_cli_entry dahdi_ss7_cli[] = {
16476    AST_CLI_DEFINE(handle_ss7_debug, "Enables SS7 debugging on a linkset"),
16477    AST_CLI_DEFINE(handle_ss7_block_cic, "Blocks the given CIC"),
16478    AST_CLI_DEFINE(handle_ss7_unblock_cic, "Unblocks the given CIC"),
16479    AST_CLI_DEFINE(handle_ss7_block_linkset, "Blocks all CICs on a linkset"),
16480    AST_CLI_DEFINE(handle_ss7_unblock_linkset, "Unblocks all CICs on a linkset"),
16481    AST_CLI_DEFINE(handle_ss7_show_linkset, "Shows the status of a linkset"),
16482    AST_CLI_DEFINE(handle_ss7_show_channels, "Displays SS7 channel information"),
16483    AST_CLI_DEFINE(handle_ss7_version, "Displays libss7 version"),
16484 };
16485 #endif   /* defined(HAVE_SS7) */
16486 
16487 #if defined(HAVE_PRI)
16488 #if defined(HAVE_PRI_CCSS)
16489 /*!
16490  * \internal
16491  * \brief CC agent initialization.
16492  * \since 1.8
16493  *
16494  * \param agent CC core agent control.
16495  * \param chan Original channel the agent will attempt to recall.
16496  *
16497  * \details
16498  * This callback is called when the CC core is initialized.  Agents should allocate
16499  * any private data necessary for the call and assign it to the private_data
16500  * on the agent.  Additionally, if any ast_cc_agent_flags are pertinent to the
16501  * specific agent type, they should be set in this function as well.
16502  *
16503  * \retval 0 on success.
16504  * \retval -1 on error.
16505  */
16506 static int dahdi_pri_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
16507 {
16508    struct dahdi_pvt *pvt;
16509    struct sig_pri_chan *pvt_chan;
16510    int res;
16511 
16512    ast_assert(!strcmp(chan->tech->type, "DAHDI"));
16513 
16514    pvt = chan->tech_pvt;
16515    if (dahdi_sig_pri_lib_handles(pvt->sig)) {
16516       pvt_chan = pvt->sig_pvt;
16517    } else {
16518       pvt_chan = NULL;
16519    }
16520    if (!pvt_chan) {
16521       return -1;
16522    }
16523 
16524    ast_module_ref(ast_module_info->self);
16525 
16526    res = sig_pri_cc_agent_init(agent, pvt_chan);
16527    if (res) {
16528       ast_module_unref(ast_module_info->self);
16529    }
16530    return res;
16531 }
16532 #endif   /* defined(HAVE_PRI_CCSS) */
16533 #endif   /* defined(HAVE_PRI) */
16534 
16535 #if defined(HAVE_PRI)
16536 #if defined(HAVE_PRI_CCSS)
16537 /*!
16538  * \internal
16539  * \brief Destroy private data on the agent.
16540  * \since 1.8
16541  *
16542  * \param agent CC core agent control.
16543  *
16544  * \details
16545  * The core will call this function upon completion
16546  * or failure of CC.
16547  *
16548  * \return Nothing
16549  */
16550 static void dahdi_pri_cc_agent_destructor(struct ast_cc_agent *agent)
16551 {
16552    sig_pri_cc_agent_destructor(agent);
16553 
16554    ast_module_unref(ast_module_info->self);
16555 }
16556 #endif   /* defined(HAVE_PRI_CCSS) */
16557 #endif   /* defined(HAVE_PRI) */
16558 
16559 #if defined(HAVE_PRI)
16560 #if defined(HAVE_PRI_CCSS)
16561 static struct ast_cc_agent_callbacks dahdi_pri_cc_agent_callbacks = {
16562    .type = dahdi_pri_cc_type,
16563    .init = dahdi_pri_cc_agent_init,
16564    .start_offer_timer = sig_pri_cc_agent_start_offer_timer,
16565    .stop_offer_timer = sig_pri_cc_agent_stop_offer_timer,
16566    .respond = sig_pri_cc_agent_req_rsp,
16567    .status_request = sig_pri_cc_agent_status_req,
16568    .stop_ringing = sig_pri_cc_agent_stop_ringing,
16569    .party_b_free = sig_pri_cc_agent_party_b_free,
16570    .start_monitoring = sig_pri_cc_agent_start_monitoring,
16571    .callee_available = sig_pri_cc_agent_callee_available,
16572    .destructor = dahdi_pri_cc_agent_destructor,
16573 };
16574 #endif   /* defined(HAVE_PRI_CCSS) */
16575 #endif   /* defined(HAVE_PRI) */
16576 
16577 #if defined(HAVE_PRI)
16578 #if defined(HAVE_PRI_CCSS)
16579 static struct ast_cc_monitor_callbacks dahdi_pri_cc_monitor_callbacks = {
16580    .type = dahdi_pri_cc_type,
16581    .request_cc = sig_pri_cc_monitor_req_cc,
16582    .suspend = sig_pri_cc_monitor_suspend,
16583    .unsuspend = sig_pri_cc_monitor_unsuspend,
16584    .status_response = sig_pri_cc_monitor_status_rsp,
16585    .cancel_available_timer = sig_pri_cc_monitor_cancel_available_timer,
16586    .destructor = sig_pri_cc_monitor_destructor,
16587 };
16588 #endif   /* defined(HAVE_PRI_CCSS) */
16589 #endif   /* defined(HAVE_PRI) */
16590 
16591 static int __unload_module(void)
16592 {
16593    struct dahdi_pvt *p;
16594 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16595    int i, j;
16596 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16597 
16598 #ifdef HAVE_PRI
16599    for (i = 0; i < NUM_SPANS; i++) {
16600       if (pris[i].pri.master != AST_PTHREADT_NULL)
16601          pthread_cancel(pris[i].pri.master);
16602    }
16603    ast_cli_unregister_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
16604    ast_unregister_application(dahdi_send_keypad_facility_app);
16605 #ifdef HAVE_PRI_PROG_W_CAUSE
16606    ast_unregister_application(dahdi_send_callrerouting_facility_app);
16607 #endif
16608 #endif
16609 #if defined(HAVE_SS7)
16610    for (i = 0; i < NUM_SPANS; i++) {
16611       if (linksets[i].ss7.master != AST_PTHREADT_NULL)
16612          pthread_cancel(linksets[i].ss7.master);
16613       }
16614    ast_cli_unregister_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
16615 #endif   /* defined(HAVE_SS7) */
16616 #if defined(HAVE_OPENR2)
16617    dahdi_r2_destroy_links();
16618    ast_cli_unregister_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
16619    ast_unregister_application(dahdi_accept_r2_call_app);
16620 #endif
16621 
16622    ast_cli_unregister_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
16623    ast_manager_unregister("DAHDIDialOffhook");
16624    ast_manager_unregister("DAHDIHangup");
16625    ast_manager_unregister("DAHDITransfer");
16626    ast_manager_unregister("DAHDIDNDoff");
16627    ast_manager_unregister("DAHDIDNDon");
16628    ast_manager_unregister("DAHDIShowChannels");
16629    ast_manager_unregister("DAHDIRestart");
16630    ast_data_unregister(NULL);
16631    ast_channel_unregister(&dahdi_tech);
16632 
16633    /* Hangup all interfaces if they have an owner */
16634    ast_mutex_lock(&iflock);
16635    for (p = iflist; p; p = p->next) {
16636       if (p->owner)
16637          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16638    }
16639    ast_mutex_unlock(&iflock);
16640 
16641    ast_mutex_lock(&monlock);
16642    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
16643       pthread_cancel(monitor_thread);
16644       pthread_kill(monitor_thread, SIGURG);
16645       pthread_join(monitor_thread, NULL);
16646    }
16647    monitor_thread = AST_PTHREADT_STOP;
16648    ast_mutex_unlock(&monlock);
16649 
16650    destroy_all_channels();
16651 
16652 #if defined(HAVE_PRI)
16653    for (i = 0; i < NUM_SPANS; i++) {
16654       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL))
16655          pthread_join(pris[i].pri.master, NULL);
16656       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++) {
16657          dahdi_close_pri_fd(&(pris[i]), j);
16658       }
16659       sig_pri_stop_pri(&pris[i].pri);
16660    }
16661 #if defined(HAVE_PRI_CCSS)
16662    ast_cc_agent_unregister(&dahdi_pri_cc_agent_callbacks);
16663    ast_cc_monitor_unregister(&dahdi_pri_cc_monitor_callbacks);
16664 #endif   /* defined(HAVE_PRI_CCSS) */
16665    sig_pri_unload();
16666 #endif
16667 
16668 #if defined(HAVE_SS7)
16669    for (i = 0; i < NUM_SPANS; i++) {
16670       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL))
16671          pthread_join(linksets[i].ss7.master, NULL);
16672       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++) {
16673          dahdi_close_ss7_fd(&(linksets[i]), j);
16674       }
16675    }
16676 #endif   /* defined(HAVE_SS7) */
16677    ast_cond_destroy(&ss_thread_complete);
16678    return 0;
16679 }
16680 
16681 static int unload_module(void)
16682 {
16683 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16684    int y;
16685 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16686 #ifdef HAVE_PRI
16687    for (y = 0; y < NUM_SPANS; y++)
16688       ast_mutex_destroy(&pris[y].pri.lock);
16689 #endif
16690 #if defined(HAVE_SS7)
16691    for (y = 0; y < NUM_SPANS; y++)
16692       ast_mutex_destroy(&linksets[y].ss7.lock);
16693 #endif   /* defined(HAVE_SS7) */
16694    return __unload_module();
16695 }
16696 
16697 static void string_replace(char *str, int char1, int char2)
16698 {
16699    for (; *str; str++) {
16700       if (*str == char1) {
16701          *str = char2;
16702       }
16703    }
16704 }
16705 
16706 static char *parse_spanchan(char *chanstr, char **subdir)
16707 {
16708    char *p;
16709 
16710    if ((p = strrchr(chanstr, '!')) == NULL) {
16711       *subdir = NULL;
16712       return chanstr;
16713    }
16714    *p++ = '\0';
16715    string_replace(chanstr, '!', '/');
16716    *subdir = chanstr;
16717    return p;
16718 }
16719 
16720 static int build_channels(struct dahdi_chan_conf *conf, const char *value, int reload, int lineno, int *found_pseudo)
16721 {
16722    char *c, *chan;
16723    char *subdir;
16724    int x, start, finish;
16725    struct dahdi_pvt *tmp;
16726 
16727    if ((reload == 0) && (conf->chan.sig < 0) && !conf->is_sig_auto) {
16728       ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
16729       return -1;
16730    }
16731 
16732    c = ast_strdupa(value);
16733    c = parse_spanchan(c, &subdir);
16734 
16735    while ((chan = strsep(&c, ","))) {
16736       if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
16737          /* Range */
16738       } else if (sscanf(chan, "%30d", &start)) {
16739          /* Just one */
16740          finish = start;
16741       } else if (!strcasecmp(chan, "pseudo")) {
16742          finish = start = CHAN_PSEUDO;
16743          if (found_pseudo)
16744             *found_pseudo = 1;
16745       } else {
16746          ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
16747          return -1;
16748       }
16749       if (finish < start) {
16750          ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
16751          x = finish;
16752          finish = start;
16753          start = x;
16754       }
16755 
16756       for (x = start; x <= finish; x++) {
16757          char fn[PATH_MAX];
16758          int real_channel = x;
16759 
16760          if (!ast_strlen_zero(subdir)) {
16761             real_channel = device2chan(subdir, x, fn, sizeof(fn));
16762             if (real_channel < 0) {
16763                if (conf->ignore_failed_channels) {
16764                   ast_log(LOG_WARNING, "Failed configuring %s!%d, (got %d). But moving on to others.\n",
16765                         subdir, x, real_channel);
16766                   continue;
16767                } else {
16768                   ast_log(LOG_ERROR, "Failed configuring %s!%d, (got %d).\n",
16769                         subdir, x, real_channel);
16770                   return -1;
16771                }
16772             }
16773          }
16774          tmp = mkintf(real_channel, conf, reload);
16775 
16776          if (tmp) {
16777             ast_verb(3, "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", real_channel, sig2str(tmp->sig));
16778          } else {
16779             ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
16780                   (reload == 1) ? "reconfigure" : "register", value);
16781             return -1;
16782          }
16783       }
16784    }
16785 
16786    return 0;
16787 }
16788 
16789 /** The length of the parameters list of 'dahdichan'.
16790  * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
16791 #define MAX_CHANLIST_LEN 80
16792 
16793 static void process_echocancel(struct dahdi_chan_conf *confp, const char *data, unsigned int line)
16794 {
16795    char *parse = ast_strdupa(data);
16796    char *params[DAHDI_MAX_ECHOCANPARAMS + 1];
16797    unsigned int param_count;
16798    unsigned int x;
16799 
16800    if (!(param_count = ast_app_separate_args(parse, ',', params, ARRAY_LEN(params))))
16801       return;
16802 
16803    memset(&confp->chan.echocancel, 0, sizeof(confp->chan.echocancel));
16804 
16805    /* first parameter is tap length, process it here */
16806 
16807    x = ast_strlen_zero(params[0]) ? 0 : atoi(params[0]);
16808 
16809    if ((x == 32) || (x == 64) || (x == 128) || (x == 256) || (x == 512) || (x == 1024))
16810       confp->chan.echocancel.head.tap_length = x;
16811    else if ((confp->chan.echocancel.head.tap_length = ast_true(params[0])))
16812       confp->chan.echocancel.head.tap_length = 128;
16813 
16814    /* now process any remaining parameters */
16815 
16816    for (x = 1; x < param_count; x++) {
16817       struct {
16818          char *name;
16819          char *value;
16820       } param;
16821 
16822       if (ast_app_separate_args(params[x], '=', (char **) &param, 2) < 1) {
16823          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, params[x]);
16824          continue;
16825       }
16826 
16827       if (ast_strlen_zero(param.name) || (strlen(param.name) > sizeof(confp->chan.echocancel.params[0].name)-1)) {
16828          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, param.name);
16829          continue;
16830       }
16831 
16832       strcpy(confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].name, param.name);
16833 
16834       if (param.value) {
16835          if (sscanf(param.value, "%30d", &confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].value) != 1) {
16836             ast_log(LOG_WARNING, "Invalid echocancel parameter value supplied at line %d: '%s'\n", line, param.value);
16837             continue;
16838          }
16839       }
16840       confp->chan.echocancel.head.param_count++;
16841    }
16842 }
16843 
16844 /*! process_dahdi() - ignore keyword 'channel' and similar */
16845 #define PROC_DAHDI_OPT_NOCHAN  (1 << 0)
16846 /*! process_dahdi() - No warnings on non-existing cofiguration keywords */
16847 #define PROC_DAHDI_OPT_NOWARN  (1 << 1)
16848 
16849 static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct ast_variable *v, int reload, int options)
16850 {
16851    struct dahdi_pvt *tmp;
16852    int y;
16853    int found_pseudo = 0;
16854    struct ast_variable *dahdichan = NULL;
16855 
16856    for (; v; v = v->next) {
16857       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16858          continue;
16859 
16860       /* Create the interface list */
16861       if (!strcasecmp(v->name, "channel") || !strcasecmp(v->name, "channels")) {
16862          if (options & PROC_DAHDI_OPT_NOCHAN) {
16863             ast_log(LOG_WARNING, "Channel '%s' ignored.\n", v->value);
16864             continue;
16865          }
16866          if (build_channels(confp, v->value, reload, v->lineno, &found_pseudo)) {
16867             if (confp->ignore_failed_channels) {
16868                ast_log(LOG_WARNING, "Channel '%s' failure ignored: ignore_failed_channels.\n", v->value);
16869                continue;
16870             } else {
16871                return -1;
16872             }
16873          }
16874          ast_log(LOG_DEBUG, "Channel '%s' configured.\n", v->value);
16875       } else if (!strcasecmp(v->name, "ignore_failed_channels")) {
16876          confp->ignore_failed_channels = ast_true(v->value);
16877       } else if (!strcasecmp(v->name, "buffers")) {
16878          if (parse_buffers_policy(v->value, &confp->chan.buf_no, &confp->chan.buf_policy)) {
16879             ast_log(LOG_WARNING, "Using default buffer policy.\n");
16880             confp->chan.buf_no = numbufs;
16881             confp->chan.buf_policy = DAHDI_POLICY_IMMEDIATE;
16882          }
16883       } else if (!strcasecmp(v->name, "faxbuffers")) {
16884          if (!parse_buffers_policy(v->value, &confp->chan.faxbuf_no, &confp->chan.faxbuf_policy)) {
16885             confp->chan.usefaxbuffers = 1;
16886          }
16887       } else if (!strcasecmp(v->name, "dahdichan")) {
16888          /* Only process the last dahdichan value. */
16889          dahdichan = v;
16890       } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
16891          usedistinctiveringdetection = ast_true(v->value);
16892       } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
16893          distinctiveringaftercid = ast_true(v->value);
16894       } else if (!strcasecmp(v->name, "dring1context")) {
16895          ast_copy_string(confp->chan.drings.ringContext[0].contextData,v->value,sizeof(confp->chan.drings.ringContext[0].contextData));
16896       } else if (!strcasecmp(v->name, "dring2context")) {
16897          ast_copy_string(confp->chan.drings.ringContext[1].contextData,v->value,sizeof(confp->chan.drings.ringContext[1].contextData));
16898       } else if (!strcasecmp(v->name, "dring3context")) {
16899          ast_copy_string(confp->chan.drings.ringContext[2].contextData,v->value,sizeof(confp->chan.drings.ringContext[2].contextData));
16900       } else if (!strcasecmp(v->name, "dring1range")) {
16901          confp->chan.drings.ringnum[0].range = atoi(v->value);
16902       } else if (!strcasecmp(v->name, "dring2range")) {
16903          confp->chan.drings.ringnum[1].range = atoi(v->value);
16904       } else if (!strcasecmp(v->name, "dring3range")) {
16905          confp->chan.drings.ringnum[2].range = atoi(v->value);
16906       } else if (!strcasecmp(v->name, "dring1")) {
16907          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]);
16908       } else if (!strcasecmp(v->name, "dring2")) {
16909          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]);
16910       } else if (!strcasecmp(v->name, "dring3")) {
16911          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]);
16912       } else if (!strcasecmp(v->name, "usecallerid")) {
16913          confp->chan.use_callerid = ast_true(v->value);
16914       } else if (!strcasecmp(v->name, "cidsignalling")) {
16915          if (!strcasecmp(v->value, "bell"))
16916             confp->chan.cid_signalling = CID_SIG_BELL;
16917          else if (!strcasecmp(v->value, "v23"))
16918             confp->chan.cid_signalling = CID_SIG_V23;
16919          else if (!strcasecmp(v->value, "dtmf"))
16920             confp->chan.cid_signalling = CID_SIG_DTMF;
16921          else if (!strcasecmp(v->value, "smdi"))
16922             confp->chan.cid_signalling = CID_SIG_SMDI;
16923          else if (!strcasecmp(v->value, "v23_jp"))
16924             confp->chan.cid_signalling = CID_SIG_V23_JP;
16925          else if (ast_true(v->value))
16926             confp->chan.cid_signalling = CID_SIG_BELL;
16927       } else if (!strcasecmp(v->name, "cidstart")) {
16928          if (!strcasecmp(v->value, "ring"))
16929             confp->chan.cid_start = CID_START_RING;
16930          else if (!strcasecmp(v->value, "polarity_in"))
16931             confp->chan.cid_start = CID_START_POLARITY_IN;
16932          else if (!strcasecmp(v->value, "polarity"))
16933             confp->chan.cid_start = CID_START_POLARITY;
16934          else if (!strcasecmp(v->value, "dtmf"))
16935             confp->chan.cid_start = CID_START_DTMF_NOALERT;
16936          else if (ast_true(v->value))
16937             confp->chan.cid_start = CID_START_RING;
16938       } else if (!strcasecmp(v->name, "threewaycalling")) {
16939          confp->chan.threewaycalling = ast_true(v->value);
16940       } else if (!strcasecmp(v->name, "cancallforward")) {
16941          confp->chan.cancallforward = ast_true(v->value);
16942       } else if (!strcasecmp(v->name, "relaxdtmf")) {
16943          if (ast_true(v->value))
16944             confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
16945          else
16946             confp->chan.dtmfrelax = 0;
16947       } else if (!strcasecmp(v->name, "mailbox")) {
16948          ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
16949       } else if (!strcasecmp(v->name, "hasvoicemail")) {
16950          if (ast_true(v->value) && ast_strlen_zero(confp->chan.mailbox)) {
16951             ast_copy_string(confp->chan.mailbox, cat, sizeof(confp->chan.mailbox));
16952          }
16953       } else if (!strcasecmp(v->name, "adsi")) {
16954          confp->chan.adsi = ast_true(v->value);
16955       } else if (!strcasecmp(v->name, "usesmdi")) {
16956          confp->chan.use_smdi = ast_true(v->value);
16957       } else if (!strcasecmp(v->name, "smdiport")) {
16958          ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
16959       } else if (!strcasecmp(v->name, "transfer")) {
16960          confp->chan.transfer = ast_true(v->value);
16961       } else if (!strcasecmp(v->name, "canpark")) {
16962          confp->chan.canpark = ast_true(v->value);
16963       } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
16964          confp->chan.echocanbridged = ast_true(v->value);
16965       } else if (!strcasecmp(v->name, "busydetect")) {
16966          confp->chan.busydetect = ast_true(v->value);
16967       } else if (!strcasecmp(v->name, "busycount")) {
16968          confp->chan.busycount = atoi(v->value);
16969       } else if (!strcasecmp(v->name, "busypattern")) {
16970          if (sscanf(v->value, "%30d,%30d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
16971             ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength at line %d.\n", v->lineno);
16972          }
16973       } else if (!strcasecmp(v->name, "callprogress")) {
16974          confp->chan.callprogress &= ~CALLPROGRESS_PROGRESS;
16975          if (ast_true(v->value))
16976             confp->chan.callprogress |= CALLPROGRESS_PROGRESS;
16977       } else if (!strcasecmp(v->name, "waitfordialtone")) {
16978          confp->chan.waitfordialtone = atoi(v->value);
16979       } else if (!strcasecmp(v->name, "faxdetect")) {
16980          confp->chan.callprogress &= ~CALLPROGRESS_FAX;
16981          if (!strcasecmp(v->value, "incoming")) {
16982             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING;
16983          } else if (!strcasecmp(v->value, "outgoing")) {
16984             confp->chan.callprogress |= CALLPROGRESS_FAX_OUTGOING;
16985          } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
16986             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING;
16987       } else if (!strcasecmp(v->name, "echocancel")) {
16988          process_echocancel(confp, v->value, v->lineno);
16989       } else if (!strcasecmp(v->name, "echotraining")) {
16990          if (sscanf(v->value, "%30d", &y) == 1) {
16991             if ((y < 10) || (y > 4000)) {
16992                ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d.\n", v->lineno);
16993             } else {
16994                confp->chan.echotraining = y;
16995             }
16996          } else if (ast_true(v->value)) {
16997             confp->chan.echotraining = 400;
16998          } else
16999             confp->chan.echotraining = 0;
17000       } else if (!strcasecmp(v->name, "hidecallerid")) {
17001          confp->chan.hidecallerid = ast_true(v->value);
17002       } else if (!strcasecmp(v->name, "hidecalleridname")) {
17003          confp->chan.hidecalleridname = ast_true(v->value);
17004       } else if (!strcasecmp(v->name, "pulsedial")) {
17005          confp->chan.pulse = ast_true(v->value);
17006       } else if (!strcasecmp(v->name, "callreturn")) {
17007          confp->chan.callreturn = ast_true(v->value);
17008       } else if (!strcasecmp(v->name, "callwaiting")) {
17009          confp->chan.callwaiting = ast_true(v->value);
17010       } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
17011          confp->chan.callwaitingcallerid = ast_true(v->value);
17012       } else if (!strcasecmp(v->name, "context")) {
17013          ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
17014       } else if (!strcasecmp(v->name, "language")) {
17015          ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
17016       } else if (!strcasecmp(v->name, "progzone")) {
17017          ast_copy_string(progzone, v->value, sizeof(progzone));
17018       } else if (!strcasecmp(v->name, "mohinterpret")
17019          ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
17020          ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
17021       } else if (!strcasecmp(v->name, "mohsuggest")) {
17022          ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
17023       } else if (!strcasecmp(v->name, "parkinglot")) {
17024          ast_copy_string(confp->chan.parkinglot, v->value, sizeof(confp->chan.parkinglot));
17025       } else if (!strcasecmp(v->name, "stripmsd")) {
17026          ast_log(LOG_NOTICE, "Configuration option \"%s\" has been deprecated. Please use dialplan instead\n", v->name);
17027          confp->chan.stripmsd = atoi(v->value);
17028       } else if (!strcasecmp(v->name, "jitterbuffers")) {
17029          numbufs = atoi(v->value);
17030       } else if (!strcasecmp(v->name, "group")) {
17031          confp->chan.group = ast_get_group(v->value);
17032       } else if (!strcasecmp(v->name, "callgroup")) {
17033          if (!strcasecmp(v->value, "none"))
17034             confp->chan.callgroup = 0;
17035          else
17036             confp->chan.callgroup = ast_get_group(v->value);
17037       } else if (!strcasecmp(v->name, "pickupgroup")) {
17038          if (!strcasecmp(v->value, "none"))
17039             confp->chan.pickupgroup = 0;
17040          else
17041             confp->chan.pickupgroup = ast_get_group(v->value);
17042       } else if (!strcasecmp(v->name, "setvar")) {
17043          char *varname = ast_strdupa(v->value), *varval = NULL;
17044          struct ast_variable *tmpvar;
17045          if (varname && (varval = strchr(varname, '='))) {
17046             *varval++ = '\0';
17047             if ((tmpvar = ast_variable_new(varname, varval, ""))) {
17048                tmpvar->next = confp->chan.vars;
17049                confp->chan.vars = tmpvar;
17050             }
17051          }
17052       } else if (!strcasecmp(v->name, "immediate")) {
17053          confp->chan.immediate = ast_true(v->value);
17054       } else if (!strcasecmp(v->name, "transfertobusy")) {
17055          confp->chan.transfertobusy = ast_true(v->value);
17056       } else if (!strcasecmp(v->name, "mwimonitor")) {
17057          confp->chan.mwimonitor_neon = 0;
17058          confp->chan.mwimonitor_fsk = 0;
17059          confp->chan.mwimonitor_rpas = 0;
17060          if (strcasestr(v->value, "fsk")) {
17061             confp->chan.mwimonitor_fsk = 1;
17062          }
17063          if (strcasestr(v->value, "rpas")) {
17064             confp->chan.mwimonitor_rpas = 1;
17065          }
17066          if (strcasestr(v->value, "neon")) {
17067             confp->chan.mwimonitor_neon = 1;
17068          }
17069          /* If set to true or yes, assume that simple fsk is desired */
17070          if (ast_true(v->value)) {
17071             confp->chan.mwimonitor_fsk = 1;
17072          }
17073       } else if (!strcasecmp(v->name, "cid_rxgain")) {
17074          if (sscanf(v->value, "%30f", &confp->chan.cid_rxgain) != 1) {
17075             ast_log(LOG_WARNING, "Invalid cid_rxgain: %s at line %d.\n", v->value, v->lineno);
17076          }
17077       } else if (!strcasecmp(v->name, "rxgain")) {
17078          if (sscanf(v->value, "%30f", &confp->chan.rxgain) != 1) {
17079             ast_log(LOG_WARNING, "Invalid rxgain: %s at line %d.\n", v->value, v->lineno);
17080          }
17081       } else if (!strcasecmp(v->name, "txgain")) {
17082          if (sscanf(v->value, "%30f", &confp->chan.txgain) != 1) {
17083             ast_log(LOG_WARNING, "Invalid txgain: %s at line %d.\n", v->value, v->lineno);
17084          }
17085       } else if (!strcasecmp(v->name, "txdrc")) {
17086          if (sscanf(v->value, "%f", &confp->chan.txdrc) != 1) {
17087             ast_log(LOG_WARNING, "Invalid txdrc: %s\n", v->value);
17088          }
17089       } else if (!strcasecmp(v->name, "rxdrc")) {
17090          if (sscanf(v->value, "%f", &confp->chan.rxdrc) != 1) {
17091             ast_log(LOG_WARNING, "Invalid rxdrc: %s\n", v->value);
17092          }
17093       } else if (!strcasecmp(v->name, "tonezone")) {
17094          if (sscanf(v->value, "%30d", &confp->chan.tonezone) != 1) {
17095             ast_log(LOG_WARNING, "Invalid tonezone: %s at line %d.\n", v->value, v->lineno);
17096          }
17097       } else if (!strcasecmp(v->name, "callerid")) {
17098          if (!strcasecmp(v->value, "asreceived")) {
17099             confp->chan.cid_num[0] = '\0';
17100             confp->chan.cid_name[0] = '\0';
17101          } else {
17102             ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
17103          }
17104       } else if (!strcasecmp(v->name, "fullname")) {
17105          ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
17106       } else if (!strcasecmp(v->name, "cid_number")) {
17107          ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
17108       } else if (!strcasecmp(v->name, "cid_tag")) {
17109          ast_copy_string(confp->chan.cid_tag, v->value, sizeof(confp->chan.cid_tag));
17110       } else if (!strcasecmp(v->name, "useincomingcalleridondahditransfer")) {
17111          confp->chan.dahditrcallerid = ast_true(v->value);
17112       } else if (!strcasecmp(v->name, "restrictcid")) {
17113          confp->chan.restrictcid = ast_true(v->value);
17114       } else if (!strcasecmp(v->name, "usecallingpres")) {
17115          confp->chan.use_callingpres = ast_true(v->value);
17116       } else if (!strcasecmp(v->name, "accountcode")) {
17117          ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
17118       } else if (!strcasecmp(v->name, "amaflags")) {
17119          y = ast_cdr_amaflags2int(v->value);
17120          if (y < 0)
17121             ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d.\n", v->value, v->lineno);
17122          else
17123             confp->chan.amaflags = y;
17124       } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
17125          confp->chan.polarityonanswerdelay = atoi(v->value);
17126       } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
17127          confp->chan.answeronpolarityswitch = ast_true(v->value);
17128       } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
17129          confp->chan.hanguponpolarityswitch = ast_true(v->value);
17130       } else if (!strcasecmp(v->name, "sendcalleridafter")) {
17131          confp->chan.sendcalleridafter = atoi(v->value);
17132       } else if (!strcasecmp(v->name, "mwimonitornotify")) {
17133          ast_copy_string(mwimonitornotify, v->value, sizeof(mwimonitornotify));
17134       } else if (ast_cc_is_config_param(v->name)) {
17135          ast_cc_set_param(confp->chan.cc_params, v->name, v->value);
17136       } else if (!strcasecmp(v->name, "mwisendtype")) {
17137 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI  /* backward compatibility for older dahdi VMWI implementation */
17138          if (!strcasecmp(v->value, "rpas")) { /* Ring Pulse Alert Signal */
17139             mwisend_rpas = 1;
17140          } else {
17141             mwisend_rpas = 0;
17142          }
17143 #else
17144          /* Default is fsk, to turn it off you must specify nofsk */
17145          memset(&confp->chan.mwisend_setting, 0, sizeof(confp->chan.mwisend_setting));
17146          if (strcasestr(v->value, "nofsk")) {      /* NoFSK */
17147             confp->chan.mwisend_fsk = 0;
17148          } else {             /* Default FSK */
17149             confp->chan.mwisend_fsk = 1;
17150          }
17151          if (strcasestr(v->value, "rpas")) {       /* Ring Pulse Alert Signal, normally followed by FSK */
17152             confp->chan.mwisend_rpas = 1;
17153          } else {
17154             confp->chan.mwisend_rpas = 0;
17155          }
17156          if (strcasestr(v->value, "lrev")) {       /* Line Reversal */
17157             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_LREV;
17158          }
17159          if (strcasestr(v->value, "hvdc")) {       /* HV 90VDC */
17160             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVDC;
17161          }
17162          if ( (strcasestr(v->value, "neon")) || (strcasestr(v->value, "hvac")) ){   /* 90V DC pulses */
17163             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVAC;
17164          }
17165 #endif
17166       } else if (reload != 1) {
17167           if (!strcasecmp(v->name, "signalling") || !strcasecmp(v->name, "signaling")) {
17168             int orig_radio = confp->chan.radio;
17169             int orig_outsigmod = confp->chan.outsigmod;
17170             int orig_auto = confp->is_sig_auto;
17171 
17172             confp->chan.radio = 0;
17173             confp->chan.outsigmod = -1;
17174             confp->is_sig_auto = 0;
17175             if (!strcasecmp(v->value, "em")) {
17176                confp->chan.sig = SIG_EM;
17177             } else if (!strcasecmp(v->value, "em_e1")) {
17178                confp->chan.sig = SIG_EM_E1;
17179             } else if (!strcasecmp(v->value, "em_w")) {
17180                confp->chan.sig = SIG_EMWINK;
17181             } else if (!strcasecmp(v->value, "fxs_ls")) {
17182                confp->chan.sig = SIG_FXSLS;
17183             } else if (!strcasecmp(v->value, "fxs_gs")) {
17184                confp->chan.sig = SIG_FXSGS;
17185             } else if (!strcasecmp(v->value, "fxs_ks")) {
17186                confp->chan.sig = SIG_FXSKS;
17187             } else if (!strcasecmp(v->value, "fxo_ls")) {
17188                confp->chan.sig = SIG_FXOLS;
17189             } else if (!strcasecmp(v->value, "fxo_gs")) {
17190                confp->chan.sig = SIG_FXOGS;
17191             } else if (!strcasecmp(v->value, "fxo_ks")) {
17192                confp->chan.sig = SIG_FXOKS;
17193             } else if (!strcasecmp(v->value, "fxs_rx")) {
17194                confp->chan.sig = SIG_FXSKS;
17195                confp->chan.radio = 1;
17196             } else if (!strcasecmp(v->value, "fxo_rx")) {
17197                confp->chan.sig = SIG_FXOLS;
17198                confp->chan.radio = 1;
17199             } else if (!strcasecmp(v->value, "fxs_tx")) {
17200                confp->chan.sig = SIG_FXSLS;
17201                confp->chan.radio = 1;
17202             } else if (!strcasecmp(v->value, "fxo_tx")) {
17203                confp->chan.sig = SIG_FXOGS;
17204                confp->chan.radio = 1;
17205             } else if (!strcasecmp(v->value, "em_rx")) {
17206                confp->chan.sig = SIG_EM;
17207                confp->chan.radio = 1;
17208             } else if (!strcasecmp(v->value, "em_tx")) {
17209                confp->chan.sig = SIG_EM;
17210                confp->chan.radio = 1;
17211             } else if (!strcasecmp(v->value, "em_rxtx")) {
17212                confp->chan.sig = SIG_EM;
17213                confp->chan.radio = 2;
17214             } else if (!strcasecmp(v->value, "em_txrx")) {
17215                confp->chan.sig = SIG_EM;
17216                confp->chan.radio = 2;
17217             } else if (!strcasecmp(v->value, "sf")) {
17218                confp->chan.sig = SIG_SF;
17219             } else if (!strcasecmp(v->value, "sf_w")) {
17220                confp->chan.sig = SIG_SFWINK;
17221             } else if (!strcasecmp(v->value, "sf_featd")) {
17222                confp->chan.sig = SIG_FEATD;
17223             } else if (!strcasecmp(v->value, "sf_featdmf")) {
17224                confp->chan.sig = SIG_FEATDMF;
17225             } else if (!strcasecmp(v->value, "sf_featb")) {
17226                confp->chan.sig = SIG_SF_FEATB;
17227             } else if (!strcasecmp(v->value, "sf")) {
17228                confp->chan.sig = SIG_SF;
17229             } else if (!strcasecmp(v->value, "sf_rx")) {
17230                confp->chan.sig = SIG_SF;
17231                confp->chan.radio = 1;
17232             } else if (!strcasecmp(v->value, "sf_tx")) {
17233                confp->chan.sig = SIG_SF;
17234                confp->chan.radio = 1;
17235             } else if (!strcasecmp(v->value, "sf_rxtx")) {
17236                confp->chan.sig = SIG_SF;
17237                confp->chan.radio = 2;
17238             } else if (!strcasecmp(v->value, "sf_txrx")) {
17239                confp->chan.sig = SIG_SF;
17240                confp->chan.radio = 2;
17241             } else if (!strcasecmp(v->value, "featd")) {
17242                confp->chan.sig = SIG_FEATD;
17243             } else if (!strcasecmp(v->value, "featdmf")) {
17244                confp->chan.sig = SIG_FEATDMF;
17245             } else if (!strcasecmp(v->value, "featdmf_ta")) {
17246                confp->chan.sig = SIG_FEATDMF_TA;
17247             } else if (!strcasecmp(v->value, "e911")) {
17248                confp->chan.sig = SIG_E911;
17249             } else if (!strcasecmp(v->value, "fgccama")) {
17250                confp->chan.sig = SIG_FGC_CAMA;
17251             } else if (!strcasecmp(v->value, "fgccamamf")) {
17252                confp->chan.sig = SIG_FGC_CAMAMF;
17253             } else if (!strcasecmp(v->value, "featb")) {
17254                confp->chan.sig = SIG_FEATB;
17255 #ifdef HAVE_PRI
17256             } else if (!strcasecmp(v->value, "pri_net")) {
17257                confp->chan.sig = SIG_PRI;
17258                confp->pri.pri.nodetype = PRI_NETWORK;
17259             } else if (!strcasecmp(v->value, "pri_cpe")) {
17260                confp->chan.sig = SIG_PRI;
17261                confp->pri.pri.nodetype = PRI_CPE;
17262             } else if (!strcasecmp(v->value, "bri_cpe")) {
17263                confp->chan.sig = SIG_BRI;
17264                confp->pri.pri.nodetype = PRI_CPE;
17265             } else if (!strcasecmp(v->value, "bri_net")) {
17266                confp->chan.sig = SIG_BRI;
17267                confp->pri.pri.nodetype = PRI_NETWORK;
17268             } else if (!strcasecmp(v->value, "bri_cpe_ptmp")) {
17269                confp->chan.sig = SIG_BRI_PTMP;
17270                confp->pri.pri.nodetype = PRI_CPE;
17271             } else if (!strcasecmp(v->value, "bri_net_ptmp")) {
17272 #if defined(HAVE_PRI_CALL_HOLD)
17273                confp->chan.sig = SIG_BRI_PTMP;
17274                confp->pri.pri.nodetype = PRI_NETWORK;
17275 #else
17276                ast_log(LOG_WARNING, "How cool would it be if someone implemented this mode!  For now, sucks for you. (line %d)\n", v->lineno);
17277 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
17278 #endif
17279 #if defined(HAVE_SS7)
17280             } else if (!strcasecmp(v->value, "ss7")) {
17281                confp->chan.sig = SIG_SS7;
17282 #endif   /* defined(HAVE_SS7) */
17283 #ifdef HAVE_OPENR2
17284             } else if (!strcasecmp(v->value, "mfcr2")) {
17285                confp->chan.sig = SIG_MFCR2;
17286 #endif
17287             } else if (!strcasecmp(v->value, "auto")) {
17288                confp->is_sig_auto = 1;
17289             } else {
17290                confp->chan.outsigmod = orig_outsigmod;
17291                confp->chan.radio = orig_radio;
17292                confp->is_sig_auto = orig_auto;
17293                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
17294             }
17295           } else if (!strcasecmp(v->name, "outsignalling") || !strcasecmp(v->name, "outsignaling")) {
17296             if (!strcasecmp(v->value, "em")) {
17297                confp->chan.outsigmod = SIG_EM;
17298             } else if (!strcasecmp(v->value, "em_e1")) {
17299                confp->chan.outsigmod = SIG_EM_E1;
17300             } else if (!strcasecmp(v->value, "em_w")) {
17301                confp->chan.outsigmod = SIG_EMWINK;
17302             } else if (!strcasecmp(v->value, "sf")) {
17303                confp->chan.outsigmod = SIG_SF;
17304             } else if (!strcasecmp(v->value, "sf_w")) {
17305                confp->chan.outsigmod = SIG_SFWINK;
17306             } else if (!strcasecmp(v->value, "sf_featd")) {
17307                confp->chan.outsigmod = SIG_FEATD;
17308             } else if (!strcasecmp(v->value, "sf_featdmf")) {
17309                confp->chan.outsigmod = SIG_FEATDMF;
17310             } else if (!strcasecmp(v->value, "sf_featb")) {
17311                confp->chan.outsigmod = SIG_SF_FEATB;
17312             } else if (!strcasecmp(v->value, "sf")) {
17313                confp->chan.outsigmod = SIG_SF;
17314             } else if (!strcasecmp(v->value, "featd")) {
17315                confp->chan.outsigmod = SIG_FEATD;
17316             } else if (!strcasecmp(v->value, "featdmf")) {
17317                confp->chan.outsigmod = SIG_FEATDMF;
17318             } else if (!strcasecmp(v->value, "featdmf_ta")) {
17319                confp->chan.outsigmod = SIG_FEATDMF_TA;
17320             } else if (!strcasecmp(v->value, "e911")) {
17321                confp->chan.outsigmod = SIG_E911;
17322             } else if (!strcasecmp(v->value, "fgccama")) {
17323                confp->chan.outsigmod = SIG_FGC_CAMA;
17324             } else if (!strcasecmp(v->value, "fgccamamf")) {
17325                confp->chan.outsigmod = SIG_FGC_CAMAMF;
17326             } else if (!strcasecmp(v->value, "featb")) {
17327                confp->chan.outsigmod = SIG_FEATB;
17328             } else {
17329                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
17330             }
17331 #ifdef HAVE_PRI
17332          } else if (!strcasecmp(v->name, "pridialplan")) {
17333             if (!strcasecmp(v->value, "national")) {
17334                confp->pri.pri.dialplan = PRI_NATIONAL_ISDN + 1;
17335             } else if (!strcasecmp(v->value, "unknown")) {
17336                confp->pri.pri.dialplan = PRI_UNKNOWN + 1;
17337             } else if (!strcasecmp(v->value, "private")) {
17338                confp->pri.pri.dialplan = PRI_PRIVATE + 1;
17339             } else if (!strcasecmp(v->value, "international")) {
17340                confp->pri.pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
17341             } else if (!strcasecmp(v->value, "local")) {
17342                confp->pri.pri.dialplan = PRI_LOCAL_ISDN + 1;
17343             } else if (!strcasecmp(v->value, "dynamic")) {
17344                confp->pri.pri.dialplan = -1;
17345             } else if (!strcasecmp(v->value, "redundant")) {
17346                confp->pri.pri.dialplan = -2;
17347             } else {
17348                ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
17349             }
17350          } else if (!strcasecmp(v->name, "prilocaldialplan")) {
17351             if (!strcasecmp(v->value, "national")) {
17352                confp->pri.pri.localdialplan = PRI_NATIONAL_ISDN + 1;
17353             } else if (!strcasecmp(v->value, "unknown")) {
17354                confp->pri.pri.localdialplan = PRI_UNKNOWN + 1;
17355             } else if (!strcasecmp(v->value, "private")) {
17356                confp->pri.pri.localdialplan = PRI_PRIVATE + 1;
17357             } else if (!strcasecmp(v->value, "international")) {
17358                confp->pri.pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
17359             } else if (!strcasecmp(v->value, "local")) {
17360                confp->pri.pri.localdialplan = PRI_LOCAL_ISDN + 1;
17361             } else if (!strcasecmp(v->value, "dynamic")) {
17362                confp->pri.pri.localdialplan = -1;
17363             } else if (!strcasecmp(v->value, "redundant")) {
17364                confp->pri.pri.localdialplan = -2;
17365             } else {
17366                ast_log(LOG_WARNING, "Unknown PRI localdialplan '%s' at line %d.\n", v->value, v->lineno);
17367             }
17368          } else if (!strcasecmp(v->name, "switchtype")) {
17369             if (!strcasecmp(v->value, "national"))
17370                confp->pri.pri.switchtype = PRI_SWITCH_NI2;
17371             else if (!strcasecmp(v->value, "ni1"))
17372                confp->pri.pri.switchtype = PRI_SWITCH_NI1;
17373             else if (!strcasecmp(v->value, "dms100"))
17374                confp->pri.pri.switchtype = PRI_SWITCH_DMS100;
17375             else if (!strcasecmp(v->value, "4ess"))
17376                confp->pri.pri.switchtype = PRI_SWITCH_ATT4ESS;
17377             else if (!strcasecmp(v->value, "5ess"))
17378                confp->pri.pri.switchtype = PRI_SWITCH_LUCENT5E;
17379             else if (!strcasecmp(v->value, "euroisdn"))
17380                confp->pri.pri.switchtype = PRI_SWITCH_EUROISDN_E1;
17381             else if (!strcasecmp(v->value, "qsig"))
17382                confp->pri.pri.switchtype = PRI_SWITCH_QSIG;
17383             else {
17384                ast_log(LOG_ERROR, "Unknown switchtype '%s' at line %d.\n", v->value, v->lineno);
17385                return -1;
17386             }
17387          } else if (!strcasecmp(v->name, "msn")) {
17388             ast_copy_string(confp->pri.pri.msn_list, v->value,
17389                sizeof(confp->pri.pri.msn_list));
17390          } else if (!strcasecmp(v->name, "nsf")) {
17391             if (!strcasecmp(v->value, "sdn"))
17392                confp->pri.pri.nsf = PRI_NSF_SDN;
17393             else if (!strcasecmp(v->value, "megacom"))
17394                confp->pri.pri.nsf = PRI_NSF_MEGACOM;
17395             else if (!strcasecmp(v->value, "tollfreemegacom"))
17396                confp->pri.pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
17397             else if (!strcasecmp(v->value, "accunet"))
17398                confp->pri.pri.nsf = PRI_NSF_ACCUNET;
17399             else if (!strcasecmp(v->value, "none"))
17400                confp->pri.pri.nsf = PRI_NSF_NONE;
17401             else {
17402                ast_log(LOG_WARNING, "Unknown network-specific facility '%s' at line %d.\n", v->value, v->lineno);
17403                confp->pri.pri.nsf = PRI_NSF_NONE;
17404             }
17405          } else if (!strcasecmp(v->name, "priindication")) {
17406             if (!strcasecmp(v->value, "outofband"))
17407                confp->chan.priindication_oob = 1;
17408             else if (!strcasecmp(v->value, "inband"))
17409                confp->chan.priindication_oob = 0;
17410             else
17411                ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d.\n",
17412                   v->value, v->lineno);
17413          } else if (!strcasecmp(v->name, "priexclusive")) {
17414             confp->chan.priexclusive = ast_true(v->value);
17415          } else if (!strcasecmp(v->name, "internationalprefix")) {
17416             ast_copy_string(confp->pri.pri.internationalprefix, v->value, sizeof(confp->pri.pri.internationalprefix));
17417          } else if (!strcasecmp(v->name, "nationalprefix")) {
17418             ast_copy_string(confp->pri.pri.nationalprefix, v->value, sizeof(confp->pri.pri.nationalprefix));
17419          } else if (!strcasecmp(v->name, "localprefix")) {
17420             ast_copy_string(confp->pri.pri.localprefix, v->value, sizeof(confp->pri.pri.localprefix));
17421          } else if (!strcasecmp(v->name, "privateprefix")) {
17422             ast_copy_string(confp->pri.pri.privateprefix, v->value, sizeof(confp->pri.pri.privateprefix));
17423          } else if (!strcasecmp(v->name, "unknownprefix")) {
17424             ast_copy_string(confp->pri.pri.unknownprefix, v->value, sizeof(confp->pri.pri.unknownprefix));
17425          } else if (!strcasecmp(v->name, "resetinterval")) {
17426             if (!strcasecmp(v->value, "never"))
17427                confp->pri.pri.resetinterval = -1;
17428             else if (atoi(v->value) >= 60)
17429                confp->pri.pri.resetinterval = atoi(v->value);
17430             else
17431                ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d.\n",
17432                   v->value, v->lineno);
17433          } else if (!strcasecmp(v->name, "minunused")) {
17434             confp->pri.pri.minunused = atoi(v->value);
17435          } else if (!strcasecmp(v->name, "minidle")) {
17436             confp->pri.pri.minidle = atoi(v->value);
17437          } else if (!strcasecmp(v->name, "idleext")) {
17438             ast_copy_string(confp->pri.pri.idleext, v->value, sizeof(confp->pri.pri.idleext));
17439          } else if (!strcasecmp(v->name, "idledial")) {
17440             ast_copy_string(confp->pri.pri.idledial, v->value, sizeof(confp->pri.pri.idledial));
17441          } else if (!strcasecmp(v->name, "overlapdial")) {
17442             if (ast_true(v->value)) {
17443                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
17444             } else if (!strcasecmp(v->value, "incoming")) {
17445                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_INCOMING;
17446             } else if (!strcasecmp(v->value, "outgoing")) {
17447                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_OUTGOING;
17448             } else if (!strcasecmp(v->value, "both") || ast_true(v->value)) {
17449                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
17450             } else {
17451                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_NONE;
17452             }
17453 #ifdef HAVE_PRI_PROG_W_CAUSE
17454          } else if (!strcasecmp(v->name, "qsigchannelmapping")) {
17455             if (!strcasecmp(v->value, "logical")) {
17456                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_LOGICAL;
17457             } else if (!strcasecmp(v->value, "physical")) {
17458                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
17459             } else {
17460                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
17461             }
17462 #endif
17463          } else if (!strcasecmp(v->name, "discardremoteholdretrieval")) {
17464             confp->pri.pri.discardremoteholdretrieval = ast_true(v->value);
17465 #if defined(HAVE_PRI_SERVICE_MESSAGES)
17466          } else if (!strcasecmp(v->name, "service_message_support")) {
17467             /* assuming switchtype for this channel group has been configured already */
17468             if ((confp->pri.pri.switchtype == PRI_SWITCH_ATT4ESS 
17469                || confp->pri.pri.switchtype == PRI_SWITCH_LUCENT5E
17470                || confp->pri.pri.switchtype == PRI_SWITCH_NI2) && ast_true(v->value)) {
17471                confp->pri.pri.enable_service_message_support = 1;
17472             } else {
17473                confp->pri.pri.enable_service_message_support = 0;
17474             }
17475 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
17476 #ifdef HAVE_PRI_INBANDDISCONNECT
17477          } else if (!strcasecmp(v->name, "inbanddisconnect")) {
17478             confp->pri.pri.inbanddisconnect = ast_true(v->value);
17479 #endif
17480          } else if (!strcasecmp(v->name, "pritimer")) {
17481 #ifdef PRI_GETSET_TIMERS
17482             char tmp[20];
17483             char *timerc;
17484             char *c;
17485             int timer;
17486             int timeridx;
17487 
17488             ast_copy_string(tmp, v->value, sizeof(tmp));
17489             c = tmp;
17490             timerc = strsep(&c, ",");
17491             if (!ast_strlen_zero(timerc) && !ast_strlen_zero(c)) {
17492                timeridx = pri_timer2idx(timerc);
17493                timer = atoi(c);
17494                if (timeridx < 0 || PRI_MAX_TIMERS <= timeridx) {
17495                   ast_log(LOG_WARNING,
17496                      "'%s' is not a valid ISDN timer at line %d.\n", timerc,
17497                      v->lineno);
17498                } else if (!timer) {
17499                   ast_log(LOG_WARNING,
17500                      "'%s' is not a valid value for ISDN timer '%s' at line %d.\n",
17501                      c, timerc, v->lineno);
17502                } else {
17503                   confp->pri.pri.pritimers[timeridx] = timer;
17504                }
17505             } else {
17506                ast_log(LOG_WARNING,
17507                   "'%s' is not a valid ISDN timer configuration string at line %d.\n",
17508                   v->value, v->lineno);
17509             }
17510 #endif /* PRI_GETSET_TIMERS */
17511          } else if (!strcasecmp(v->name, "facilityenable")) {
17512             confp->pri.pri.facilityenable = ast_true(v->value);
17513 #if defined(HAVE_PRI_AOC_EVENTS)
17514          } else if (!strcasecmp(v->name, "aoc_enable")) {
17515             confp->pri.pri.aoc_passthrough_flag = 0;
17516             if (strchr(v->value, 's') || strchr(v->value, 'S')) {
17517                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_S;
17518             }
17519             if (strchr(v->value, 'd') || strchr(v->value, 'D')) {
17520                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_D;
17521             }
17522             if (strchr(v->value, 'e') || strchr(v->value, 'E')) {
17523                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_E;
17524             }
17525          } else if (!strcasecmp(v->name, "aoce_delayhangup")) {
17526             confp->pri.pri.aoce_delayhangup = ast_true(v->value);
17527 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
17528 #if defined(HAVE_PRI_CALL_HOLD)
17529          } else if (!strcasecmp(v->name, "hold_disconnect_transfer")) {
17530             confp->pri.pri.hold_disconnect_transfer = ast_true(v->value);
17531 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
17532 #if defined(HAVE_PRI_CCSS)
17533          } else if (!strcasecmp(v->name, "cc_ptmp_recall_mode")) {
17534             if (!strcasecmp(v->value, "global")) {
17535                confp->pri.pri.cc_ptmp_recall_mode = 0;/* globalRecall */
17536             } else if (!strcasecmp(v->value, "specific")) {
17537                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
17538             } else {
17539                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
17540             }
17541          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_req")) {
17542             if (!strcasecmp(v->value, "release")) {
17543                confp->pri.pri.cc_qsig_signaling_link_req = 0;/* release */
17544             } else if (!strcasecmp(v->value, "retain")) {
17545                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
17546             } else if (!strcasecmp(v->value, "do_not_care")) {
17547                confp->pri.pri.cc_qsig_signaling_link_req = 2;/* do-not-care */
17548             } else {
17549                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
17550             }
17551          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_rsp")) {
17552             if (!strcasecmp(v->value, "release")) {
17553                confp->pri.pri.cc_qsig_signaling_link_rsp = 0;/* release */
17554             } else if (!strcasecmp(v->value, "retain")) {
17555                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
17556             } else {
17557                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
17558             }
17559 #endif   /* defined(HAVE_PRI_CCSS) */
17560 #if defined(HAVE_PRI_CALL_WAITING)
17561          } else if (!strcasecmp(v->name, "max_call_waiting_calls")) {
17562             confp->pri.pri.max_call_waiting_calls = atoi(v->value);
17563             if (confp->pri.pri.max_call_waiting_calls < 0) {
17564                /* Negative values are not allowed. */
17565                confp->pri.pri.max_call_waiting_calls = 0;
17566             }
17567          } else if (!strcasecmp(v->name, "allow_call_waiting_calls")) {
17568             confp->pri.pri.allow_call_waiting_calls = ast_true(v->value);
17569 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
17570 #if defined(HAVE_PRI_MWI)
17571          } else if (!strcasecmp(v->name, "mwi_mailboxes")) {
17572             ast_copy_string(confp->pri.pri.mwi_mailboxes, v->value,
17573                sizeof(confp->pri.pri.mwi_mailboxes));
17574 #endif   /* defined(HAVE_PRI_MWI) */
17575          } else if (!strcasecmp(v->name, "append_msn_to_cid_tag")) {
17576             confp->pri.pri.append_msn_to_user_tag = ast_true(v->value);
17577 #if defined(HAVE_PRI_L2_PERSISTENCE)
17578          } else if (!strcasecmp(v->name, "layer2_persistence")) {
17579             if (!strcasecmp(v->value, "keep_up")) {
17580                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_KEEP_UP;
17581             } else if (!strcasecmp(v->value, "leave_down")) {
17582                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_LEAVE_DOWN;
17583             } else {
17584                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_DEFAULT;
17585             }
17586 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
17587 #endif /* HAVE_PRI */
17588 #if defined(HAVE_SS7)
17589          } else if (!strcasecmp(v->name, "ss7type")) {
17590             if (!strcasecmp(v->value, "itu")) {
17591                cur_ss7type = SS7_ITU;
17592             } else if (!strcasecmp(v->value, "ansi")) {
17593                cur_ss7type = SS7_ANSI;
17594             } else
17595                ast_log(LOG_WARNING, "'%s' is an unknown ss7 switch type at line %d.!\n", v->value, v->lineno);
17596          } else if (!strcasecmp(v->name, "linkset")) {
17597             cur_linkset = atoi(v->value);
17598          } else if (!strcasecmp(v->name, "pointcode")) {
17599             cur_pointcode = parse_pointcode(v->value);
17600          } else if (!strcasecmp(v->name, "adjpointcode")) {
17601             cur_adjpointcode = parse_pointcode(v->value);
17602          } else if (!strcasecmp(v->name, "defaultdpc")) {
17603             cur_defaultdpc = parse_pointcode(v->value);
17604          } else if (!strcasecmp(v->name, "cicbeginswith")) {
17605             cur_cicbeginswith = atoi(v->value);
17606          } else if (!strcasecmp(v->name, "networkindicator")) {
17607             if (!strcasecmp(v->value, "national"))
17608                cur_networkindicator = SS7_NI_NAT;
17609             else if (!strcasecmp(v->value, "national_spare"))
17610                cur_networkindicator = SS7_NI_NAT_SPARE;
17611             else if (!strcasecmp(v->value, "international"))
17612                cur_networkindicator = SS7_NI_INT;
17613             else if (!strcasecmp(v->value, "international_spare"))
17614                cur_networkindicator = SS7_NI_INT_SPARE;
17615             else
17616                cur_networkindicator = -1;
17617          } else if (!strcasecmp(v->name, "ss7_internationalprefix")) {
17618             ast_copy_string(confp->ss7.ss7.internationalprefix, v->value, sizeof(confp->ss7.ss7.internationalprefix));
17619          } else if (!strcasecmp(v->name, "ss7_nationalprefix")) {
17620             ast_copy_string(confp->ss7.ss7.nationalprefix, v->value, sizeof(confp->ss7.ss7.nationalprefix));
17621          } else if (!strcasecmp(v->name, "ss7_subscriberprefix")) {
17622             ast_copy_string(confp->ss7.ss7.subscriberprefix, v->value, sizeof(confp->ss7.ss7.subscriberprefix));
17623          } else if (!strcasecmp(v->name, "ss7_unknownprefix")) {
17624             ast_copy_string(confp->ss7.ss7.unknownprefix, v->value, sizeof(confp->ss7.ss7.unknownprefix));
17625          } else if (!strcasecmp(v->name, "ss7_called_nai")) {
17626             if (!strcasecmp(v->value, "national")) {
17627                confp->ss7.ss7.called_nai = SS7_NAI_NATIONAL;
17628             } else if (!strcasecmp(v->value, "international")) {
17629                confp->ss7.ss7.called_nai = SS7_NAI_INTERNATIONAL;
17630             } else if (!strcasecmp(v->value, "subscriber")) {
17631                confp->ss7.ss7.called_nai = SS7_NAI_SUBSCRIBER;
17632             } else if (!strcasecmp(v->value, "unknown")) {
17633                confp->ss7.ss7.called_nai = SS7_NAI_UNKNOWN;
17634             } else if (!strcasecmp(v->value, "dynamic")) {
17635                confp->ss7.ss7.called_nai = SS7_NAI_DYNAMIC;
17636             } else {
17637                ast_log(LOG_WARNING, "Unknown SS7 called_nai '%s' at line %d.\n", v->value, v->lineno);
17638             }
17639          } else if (!strcasecmp(v->name, "ss7_calling_nai")) {
17640             if (!strcasecmp(v->value, "national")) {
17641                confp->ss7.ss7.calling_nai = SS7_NAI_NATIONAL;
17642             } else if (!strcasecmp(v->value, "international")) {
17643                confp->ss7.ss7.calling_nai = SS7_NAI_INTERNATIONAL;
17644             } else if (!strcasecmp(v->value, "subscriber")) {
17645                confp->ss7.ss7.calling_nai = SS7_NAI_SUBSCRIBER;
17646             } else if (!strcasecmp(v->value, "unknown")) {
17647                confp->ss7.ss7.calling_nai = SS7_NAI_UNKNOWN;
17648             } else if (!strcasecmp(v->value, "dynamic")) {
17649                confp->ss7.ss7.calling_nai = SS7_NAI_DYNAMIC;
17650             } else {
17651                ast_log(LOG_WARNING, "Unknown SS7 calling_nai '%s' at line %d.\n", v->value, v->lineno);
17652             }
17653          } else if (!strcasecmp(v->name, "sigchan")) {
17654             int sigchan, res;
17655             sigchan = atoi(v->value);
17656             res = linkset_addsigchan(sigchan);
17657             if (res < 0)
17658                return -1;
17659 
17660          } else if (!strcasecmp(v->name, "ss7_explicitacm")) {
17661             struct dahdi_ss7 *link;
17662             link = ss7_resolve_linkset(cur_linkset);
17663             if (!link) {
17664                ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
17665                return -1;
17666             }
17667             if (ast_true(v->value))
17668                link->ss7.flags |= LINKSET_FLAG_EXPLICITACM;
17669 #endif   /* defined(HAVE_SS7) */
17670 #ifdef HAVE_OPENR2
17671          } else if (!strcasecmp(v->name, "mfcr2_advanced_protocol_file")) {
17672             ast_copy_string(confp->mfcr2.r2proto_file, v->value, sizeof(confp->mfcr2.r2proto_file));
17673             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);
17674          } else if (!strcasecmp(v->name, "mfcr2_logdir")) {
17675             ast_copy_string(confp->mfcr2.logdir, v->value, sizeof(confp->mfcr2.logdir));
17676          } else if (!strcasecmp(v->name, "mfcr2_variant")) {
17677             confp->mfcr2.variant = openr2_proto_get_variant(v->value);
17678             if (OR2_VAR_UNKNOWN == confp->mfcr2.variant) {
17679                ast_log(LOG_WARNING, "Unknown MFC/R2 variant '%s' at line %d, defaulting to ITU.\n", v->value, v->lineno);
17680                confp->mfcr2.variant = OR2_VAR_ITU;
17681             }
17682          } else if (!strcasecmp(v->name, "mfcr2_mfback_timeout")) {
17683             confp->mfcr2.mfback_timeout = atoi(v->value);
17684             if (!confp->mfcr2.mfback_timeout) {
17685                ast_log(LOG_WARNING, "MF timeout of 0? hum, I will protect you from your ignorance. Setting default.\n");
17686                confp->mfcr2.mfback_timeout = -1;
17687             } else if (confp->mfcr2.mfback_timeout > 0 && confp->mfcr2.mfback_timeout < 500) {
17688                ast_log(LOG_WARNING, "MF timeout less than 500ms is not recommended, you have been warned!\n");
17689             }
17690          } else if (!strcasecmp(v->name, "mfcr2_metering_pulse_timeout")) {
17691             confp->mfcr2.metering_pulse_timeout = atoi(v->value);
17692             if (confp->mfcr2.metering_pulse_timeout > 500) {
17693                ast_log(LOG_WARNING, "Metering pulse timeout greater than 500ms is not recommended, you have been warned!\n");
17694             }
17695          } else if (!strcasecmp(v->name, "mfcr2_get_ani_first")) {
17696             confp->mfcr2.get_ani_first = ast_true(v->value) ? 1 : 0;
17697          } else if (!strcasecmp(v->name, "mfcr2_double_answer")) {
17698             confp->mfcr2.double_answer = ast_true(v->value) ? 1 : 0;
17699          } else if (!strcasecmp(v->name, "mfcr2_charge_calls")) {
17700             confp->mfcr2.charge_calls = ast_true(v->value) ? 1 : 0;
17701          } else if (!strcasecmp(v->name, "mfcr2_accept_on_offer")) {
17702             confp->mfcr2.accept_on_offer = ast_true(v->value) ? 1 : 0;
17703          } else if (!strcasecmp(v->name, "mfcr2_allow_collect_calls")) {
17704             confp->mfcr2.allow_collect_calls = ast_true(v->value) ? 1 : 0;
17705          } else if (!strcasecmp(v->name, "mfcr2_forced_release")) {
17706             confp->mfcr2.forced_release = ast_true(v->value) ? 1 : 0;
17707          } else if (!strcasecmp(v->name, "mfcr2_immediate_accept")) {
17708             confp->mfcr2.immediate_accept = ast_true(v->value) ? 1 : 0;
17709 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
17710          } else if (!strcasecmp(v->name, "mfcr2_skip_category")) {
17711             confp->mfcr2.skip_category_request = ast_true(v->value) ? 1 : 0;
17712 #endif
17713          } else if (!strcasecmp(v->name, "mfcr2_call_files")) {
17714             confp->mfcr2.call_files = ast_true(v->value) ? 1 : 0;
17715          } else if (!strcasecmp(v->name, "mfcr2_max_ani")) {
17716             confp->mfcr2.max_ani = atoi(v->value);
17717             if (confp->mfcr2.max_ani >= AST_MAX_EXTENSION){
17718                confp->mfcr2.max_ani = AST_MAX_EXTENSION - 1;
17719             }
17720          } else if (!strcasecmp(v->name, "mfcr2_max_dnis")) {
17721             confp->mfcr2.max_dnis = atoi(v->value);
17722             if (confp->mfcr2.max_dnis >= AST_MAX_EXTENSION){
17723                confp->mfcr2.max_dnis = AST_MAX_EXTENSION - 1;
17724             }
17725          } else if (!strcasecmp(v->name, "mfcr2_category")) {
17726             confp->mfcr2.category = openr2_proto_get_category(v->value);
17727             if (OR2_CALLING_PARTY_CATEGORY_UNKNOWN == confp->mfcr2.category) {
17728                confp->mfcr2.category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER;
17729                ast_log(LOG_WARNING, "Invalid MFC/R2 caller category '%s' at line %d. Using national subscriber as default.\n",
17730                      v->value, v->lineno);
17731             }
17732          } else if (!strcasecmp(v->name, "mfcr2_logging")) {
17733             openr2_log_level_t tmplevel;
17734             char *clevel;
17735             char *logval = ast_strdupa(v->value);
17736             while (logval) {
17737                clevel = strsep(&logval,",");
17738                if (-1 == (tmplevel = openr2_log_get_level(clevel))) {
17739                   ast_log(LOG_WARNING, "Ignoring invalid logging level: '%s' at line %d.\n", clevel, v->lineno);
17740                   continue;
17741                }
17742                confp->mfcr2.loglevel |= tmplevel;
17743             }
17744 #endif /* HAVE_OPENR2 */
17745          } else if (!strcasecmp(v->name, "cadence")) {
17746             /* setup to scan our argument */
17747             int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
17748             int i;
17749             struct dahdi_ring_cadence new_cadence;
17750             int cid_location = -1;
17751             int firstcadencepos = 0;
17752             char original_args[80];
17753             int cadence_is_ok = 1;
17754 
17755             ast_copy_string(original_args, v->value, sizeof(original_args));
17756             /* 16 cadences allowed (8 pairs) */
17757             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]);
17758 
17759             /* Cadence must be even (on/off) */
17760             if (element_count % 2 == 1) {
17761                ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s at line %d.\n", original_args, v->lineno);
17762                cadence_is_ok = 0;
17763             }
17764 
17765             /* Ring cadences cannot be negative */
17766             for (i = 0; i < element_count; i++) {
17767                if (c[i] == 0) {
17768                   ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s at line %d.\n", original_args, v->lineno);
17769                   cadence_is_ok = 0;
17770                   break;
17771                } else if (c[i] < 0) {
17772                   if (i % 2 == 1) {
17773                      /* Silence duration, negative possibly okay */
17774                      if (cid_location == -1) {
17775                         cid_location = i;
17776                         c[i] *= -1;
17777                      } else {
17778                         ast_log(LOG_ERROR, "CID location specified twice: %s at line %d.\n", original_args, v->lineno);
17779                         cadence_is_ok = 0;
17780                         break;
17781                      }
17782                   } else {
17783                      if (firstcadencepos == 0) {
17784                         firstcadencepos = i; /* only recorded to avoid duplicate specification */
17785                                  /* duration will be passed negative to the DAHDI driver */
17786                      } else {
17787                          ast_log(LOG_ERROR, "First cadence position specified twice: %s at line %d.\n", original_args, v->lineno);
17788                         cadence_is_ok = 0;
17789                         break;
17790                      }
17791                   }
17792                }
17793             }
17794 
17795             /* Substitute our scanned cadence */
17796             for (i = 0; i < 16; i++) {
17797                new_cadence.ringcadence[i] = c[i];
17798             }
17799 
17800             if (cadence_is_ok) {
17801                /* ---we scanned it without getting annoyed; now some sanity checks--- */
17802                if (element_count < 2) {
17803                   ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s at line %d.\n", original_args, v->lineno);
17804                } else {
17805                   if (cid_location == -1) {
17806                      /* user didn't say; default to first pause */
17807                      cid_location = 1;
17808                   } else {
17809                      /* convert element_index to cidrings value */
17810                      cid_location = (cid_location + 1) / 2;
17811                   }
17812                   /* ---we like their cadence; try to install it--- */
17813                   if (!user_has_defined_cadences++)
17814                      /* this is the first user-defined cadence; clear the default user cadences */
17815                      num_cadence = 0;
17816                   if ((num_cadence+1) >= NUM_CADENCE_MAX)
17817                      ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s at line %d.\n", NUM_CADENCE_MAX, original_args, v->lineno);
17818                   else {
17819                      cadences[num_cadence] = new_cadence;
17820                      cidrings[num_cadence++] = cid_location;
17821                      ast_verb(3, "cadence 'r%d' added: %s\n",num_cadence,original_args);
17822                   }
17823                }
17824             }
17825          } else if (!strcasecmp(v->name, "ringtimeout")) {
17826             ringt_base = (atoi(v->value) * 8) / READ_SIZE;
17827          } else if (!strcasecmp(v->name, "prewink")) {
17828             confp->timing.prewinktime = atoi(v->value);
17829          } else if (!strcasecmp(v->name, "preflash")) {
17830             confp->timing.preflashtime = atoi(v->value);
17831          } else if (!strcasecmp(v->name, "wink")) {
17832             confp->timing.winktime = atoi(v->value);
17833          } else if (!strcasecmp(v->name, "flash")) {
17834             confp->timing.flashtime = atoi(v->value);
17835          } else if (!strcasecmp(v->name, "start")) {
17836             confp->timing.starttime = atoi(v->value);
17837          } else if (!strcasecmp(v->name, "rxwink")) {
17838             confp->timing.rxwinktime = atoi(v->value);
17839          } else if (!strcasecmp(v->name, "rxflash")) {
17840             confp->timing.rxflashtime = atoi(v->value);
17841          } else if (!strcasecmp(v->name, "debounce")) {
17842             confp->timing.debouncetime = atoi(v->value);
17843          } else if (!strcasecmp(v->name, "toneduration")) {
17844             int toneduration;
17845             int ctlfd;
17846             int res;
17847             struct dahdi_dialparams dps;
17848 
17849             ctlfd = open("/dev/dahdi/ctl", O_RDWR);
17850             if (ctlfd == -1) {
17851                ast_log(LOG_ERROR, "Unable to open /dev/dahdi/ctl to set toneduration at line %d.\n", v->lineno);
17852                return -1;
17853             }
17854 
17855             toneduration = atoi(v->value);
17856             if (toneduration > -1) {
17857                memset(&dps, 0, sizeof(dps));
17858 
17859                dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
17860                res = ioctl(ctlfd, DAHDI_SET_DIALPARAMS, &dps);
17861                if (res < 0) {
17862                   ast_log(LOG_ERROR, "Invalid tone duration: %d ms at line %d: %s\n", toneduration, v->lineno, strerror(errno));
17863                   close(ctlfd);
17864                   return -1;
17865                }
17866             }
17867             close(ctlfd);
17868          } else if (!strcasecmp(v->name, "defaultcic")) {
17869             ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
17870          } else if (!strcasecmp(v->name, "defaultozz")) {
17871             ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
17872          } else if (!strcasecmp(v->name, "mwilevel")) {
17873             mwilevel = atoi(v->value);
17874          } else if (!strcasecmp(v->name, "dtmfcidlevel")) {
17875             dtmfcid_level = atoi(v->value);
17876          } else if (!strcasecmp(v->name, "reportalarms")) {
17877             if (!strcasecmp(v->value, "all"))
17878                report_alarms = REPORT_CHANNEL_ALARMS | REPORT_SPAN_ALARMS;
17879             if (!strcasecmp(v->value, "none"))
17880                report_alarms = 0;
17881             else if (!strcasecmp(v->value, "channels"))
17882                report_alarms = REPORT_CHANNEL_ALARMS;
17883             else if (!strcasecmp(v->value, "spans"))
17884                report_alarms = REPORT_SPAN_ALARMS;
17885           }
17886       } else if (!(options & PROC_DAHDI_OPT_NOWARN) )
17887          ast_log(LOG_WARNING, "Ignoring any changes to '%s' (on reload) at line %d.\n", v->name, v->lineno);
17888    }
17889 
17890    /* Since confp has already filled invidual dahdi_pvt objects with channels at this point, clear the variables in confp's pvt. */
17891    if (confp->chan.vars) {
17892       ast_variables_destroy(confp->chan.vars);
17893       confp->chan.vars = NULL;
17894    }
17895 
17896    if (dahdichan) {
17897       /* Process the deferred dahdichan value. */
17898       if (build_channels(confp, dahdichan->value, reload, dahdichan->lineno,
17899          &found_pseudo)) {
17900          if (confp->ignore_failed_channels) {
17901             ast_log(LOG_WARNING,
17902                "Dahdichan '%s' failure ignored: ignore_failed_channels.\n",
17903                dahdichan->value);
17904          } else {
17905             return -1;
17906          }
17907       }
17908    }
17909 
17910    /* mark the first channels of each DAHDI span to watch for their span alarms */
17911    for (tmp = iflist, y=-1; tmp; tmp = tmp->next) {
17912       if (!tmp->destroy && tmp->span != y) {
17913          tmp->manages_span_alarms = 1;
17914          y = tmp->span; 
17915       } else {
17916          tmp->manages_span_alarms = 0;
17917       }
17918    }
17919 
17920    /*< \todo why check for the pseudo in the per-channel section.
17921     * Any actual use for manual setup of the pseudo channel? */
17922    if (!found_pseudo && reload != 1 && !(options & PROC_DAHDI_OPT_NOCHAN)) {
17923       /* use the default configuration for a channel, so
17924          that any settings from real configured channels
17925          don't "leak" into the pseudo channel config
17926       */
17927       struct dahdi_chan_conf conf = dahdi_chan_conf_default();
17928 
17929       if (conf.chan.cc_params) {
17930          tmp = mkintf(CHAN_PSEUDO, &conf, reload);
17931       } else {
17932          tmp = NULL;
17933       }
17934       if (tmp) {
17935          ast_verb(3, "Automatically generated pseudo channel\n");
17936       } else {
17937          ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
17938       }
17939       ast_cc_config_params_destroy(conf.chan.cc_params);
17940    }
17941    return 0;
17942 }
17943 
17944 /*!
17945  * \internal
17946  * \brief Deep copy struct dahdi_chan_conf.
17947  * \since 1.8
17948  *
17949  * \param dest Destination.
17950  * \param src Source.
17951  *
17952  * \return Nothing
17953  */
17954 static void deep_copy_dahdi_chan_conf(struct dahdi_chan_conf *dest, const struct dahdi_chan_conf *src)
17955 {
17956    struct ast_cc_config_params *cc_params;
17957 
17958    cc_params = dest->chan.cc_params;
17959    *dest = *src;
17960    dest->chan.cc_params = cc_params;
17961    ast_cc_copy_config_params(dest->chan.cc_params, src->chan.cc_params);
17962 }
17963 
17964 /*!
17965  * \internal
17966  * \brief Setup DAHDI channel driver.
17967  *
17968  * \param reload enum: load_module(0), reload(1), restart(2).
17969  * \param default_conf Default config parameters.  So cc_params can be properly destroyed.
17970  * \param base_conf Default config parameters per section.  So cc_params can be properly destroyed.
17971  * \param conf Local config parameters.  So cc_params can be properly destroyed.
17972  *
17973  * \retval 0 on success.
17974  * \retval -1 on error.
17975  */
17976 static int setup_dahdi_int(int reload, struct dahdi_chan_conf *default_conf, struct dahdi_chan_conf *base_conf, struct dahdi_chan_conf *conf)
17977 {
17978    struct ast_config *cfg;
17979    struct ast_config *ucfg;
17980    struct ast_variable *v;
17981    struct ast_flags config_flags = { reload == 1 ? CONFIG_FLAG_FILEUNCHANGED : 0 };
17982    const char *chans;
17983    const char *cat;
17984    int res;
17985 
17986 #ifdef HAVE_PRI
17987    char *c;
17988    int spanno;
17989    int i;
17990    int logicalspan;
17991    int trunkgroup;
17992    int dchannels[SIG_PRI_NUM_DCHANS];
17993 #endif
17994    int have_cfg_now;
17995    static int had_cfg_before = 1;/* So initial load will complain if we don't have cfg. */
17996 
17997    cfg = ast_config_load(config, config_flags);
17998    have_cfg_now = !!cfg;
17999    if (!cfg) {
18000       /* Error if we have no config file */
18001       if (had_cfg_before) {
18002          ast_log(LOG_ERROR, "Unable to load config %s\n", config);
18003          ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18004       }
18005       cfg = ast_config_new();/* Dummy config */
18006       if (!cfg) {
18007          return 0;
18008       }
18009       ucfg = ast_config_load("users.conf", config_flags);
18010       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
18011          ast_config_destroy(cfg);
18012          return 0;
18013       }
18014       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18015          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18016          ast_config_destroy(cfg);
18017          return 0;
18018       }
18019    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
18020       ucfg = ast_config_load("users.conf", config_flags);
18021       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
18022          return 0;
18023       }
18024       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18025          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18026          return 0;
18027       }
18028       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18029       cfg = ast_config_load(config, config_flags);
18030       have_cfg_now = !!cfg;
18031       if (!cfg) {
18032          if (had_cfg_before) {
18033             /* We should have been able to load the config. */
18034             ast_log(LOG_ERROR, "Bad. Unable to load config %s\n", config);
18035             ast_config_destroy(ucfg);
18036             return 0;
18037          }
18038          cfg = ast_config_new();/* Dummy config */
18039          if (!cfg) {
18040             ast_config_destroy(ucfg);
18041             return 0;
18042          }
18043       } else if (cfg == CONFIG_STATUS_FILEINVALID) {
18044          ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
18045          ast_config_destroy(ucfg);
18046          return 0;
18047       }
18048    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
18049       ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
18050       return 0;
18051    } else {
18052       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18053       ucfg = ast_config_load("users.conf", config_flags);
18054       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18055          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18056          ast_config_destroy(cfg);
18057          return 0;
18058       }
18059    }
18060    had_cfg_before = have_cfg_now;
18061 
18062    /* It's a little silly to lock it, but we might as well just to be sure */
18063    ast_mutex_lock(&iflock);
18064 #ifdef HAVE_PRI
18065    if (reload != 1) {
18066       /* Process trunkgroups first */
18067       v = ast_variable_browse(cfg, "trunkgroups");
18068       while (v) {
18069          if (!strcasecmp(v->name, "trunkgroup")) {
18070             trunkgroup = atoi(v->value);
18071             if (trunkgroup > 0) {
18072                if ((c = strchr(v->value, ','))) {
18073                   i = 0;
18074                   memset(dchannels, 0, sizeof(dchannels));
18075                   while (c && (i < SIG_PRI_NUM_DCHANS)) {
18076                      dchannels[i] = atoi(c + 1);
18077                      if (dchannels[i] < 0) {
18078                         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);
18079                      } else
18080                         i++;
18081                      c = strchr(c + 1, ',');
18082                   }
18083                   if (i) {
18084                      if (pri_create_trunkgroup(trunkgroup, dchannels)) {
18085                         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);
18086                   } else
18087                         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");
18088                   } else
18089                      ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18090                } else
18091                   ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18092             } else
18093                ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of chan_dahdi.conf\n", v->lineno);
18094          } else if (!strcasecmp(v->name, "spanmap")) {
18095             spanno = atoi(v->value);
18096             if (spanno > 0) {
18097                if ((c = strchr(v->value, ','))) {
18098                   trunkgroup = atoi(c + 1);
18099                   if (trunkgroup > 0) {
18100                      if ((c = strchr(c + 1, ',')))
18101                         logicalspan = atoi(c + 1);
18102                      else
18103                         logicalspan = 0;
18104                      if (logicalspan >= 0) {
18105                         if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
18106                            ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
18107                      } else
18108                            ast_verb(2, "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
18109                      } else
18110                         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);
18111                   } else
18112                      ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of chan_dahdi.conf\n", v->lineno);
18113                } else
18114                   ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of chan_dahdi.conf\n", v->lineno);
18115             } else
18116                ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of chan_dahdi.conf\n", v->lineno);
18117          } else {
18118             ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
18119          }
18120          v = v->next;
18121       }
18122    }
18123 #endif
18124 
18125    /* Copy the default jb config over global_jbconf */
18126    memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
18127 
18128    mwimonitornotify[0] = '\0';
18129 
18130    v = ast_variable_browse(cfg, "channels");
18131    if ((res = process_dahdi(base_conf,
18132       "" /* Must be empty for the channels category.  Silly voicemail mailbox. */,
18133       v, reload, 0))) {
18134       ast_mutex_unlock(&iflock);
18135       ast_config_destroy(cfg);
18136       if (ucfg) {
18137          ast_config_destroy(ucfg);
18138       }
18139       return res;
18140    }
18141 
18142    /* Now get configuration from all normal sections in chan_dahdi.conf: */
18143    for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
18144       /* [channels] and [trunkgroups] are used. Let's also reserve
18145        * [globals] and [general] for future use
18146        */
18147       if (!strcasecmp(cat, "general") ||
18148          !strcasecmp(cat, "trunkgroups") ||
18149          !strcasecmp(cat, "globals") ||
18150          !strcasecmp(cat, "channels")) {
18151          continue;
18152       }
18153 
18154       chans = ast_variable_retrieve(cfg, cat, "dahdichan");
18155       if (ast_strlen_zero(chans)) {
18156          /* Section is useless without a dahdichan value present. */
18157          continue;
18158       }
18159 
18160       /* Copy base_conf to conf. */
18161       deep_copy_dahdi_chan_conf(conf, base_conf);
18162 
18163       if ((res = process_dahdi(conf, cat, ast_variable_browse(cfg, cat), reload, PROC_DAHDI_OPT_NOCHAN))) {
18164          ast_mutex_unlock(&iflock);
18165          ast_config_destroy(cfg);
18166          if (ucfg) {
18167             ast_config_destroy(ucfg);
18168          }
18169          return res;
18170       }
18171    }
18172 
18173    ast_config_destroy(cfg);
18174 
18175    if (ucfg) {
18176       /* Reset base_conf, so things don't leak from chan_dahdi.conf */
18177       deep_copy_dahdi_chan_conf(base_conf, default_conf);
18178       process_dahdi(base_conf,
18179          "" /* Must be empty for the general category.  Silly voicemail mailbox. */,
18180          ast_variable_browse(ucfg, "general"), 1, 0);
18181 
18182       for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
18183          if (!strcasecmp(cat, "general")) {
18184             continue;
18185          }
18186 
18187          chans = ast_variable_retrieve(ucfg, cat, "dahdichan");
18188          if (ast_strlen_zero(chans)) {
18189             /* Section is useless without a dahdichan value present. */
18190             continue;
18191          }
18192 
18193          /* Copy base_conf to conf. */
18194          deep_copy_dahdi_chan_conf(conf, base_conf);
18195 
18196          if ((res = process_dahdi(conf, cat, ast_variable_browse(ucfg, cat), reload, PROC_DAHDI_OPT_NOCHAN | PROC_DAHDI_OPT_NOWARN))) {
18197             ast_config_destroy(ucfg);
18198             ast_mutex_unlock(&iflock);
18199             return res;
18200          }
18201       }
18202       ast_config_destroy(ucfg);
18203    }
18204    ast_mutex_unlock(&iflock);
18205 
18206 #ifdef HAVE_PRI
18207    if (reload != 1) {
18208       int x;
18209       for (x = 0; x < NUM_SPANS; x++) {
18210          if (pris[x].pri.pvts[0]) {
18211             prepare_pri(pris + x);
18212             if (sig_pri_start_pri(&pris[x].pri)) {
18213                ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
18214                return -1;
18215             } else
18216                ast_verb(2, "Starting D-Channel on span %d\n", x + 1);
18217          }
18218       }
18219    }
18220 #endif
18221 #if defined(HAVE_SS7)
18222    if (reload != 1) {
18223       int x;
18224       for (x = 0; x < NUM_SPANS; x++) {
18225          if (linksets[x].ss7.ss7) {
18226             linksets[x].ss7.calls = &dahdi_ss7_callbacks;
18227             if (ast_pthread_create(&linksets[x].ss7.master, NULL, ss7_linkset, &linksets[x].ss7)) {
18228                ast_log(LOG_ERROR, "Unable to start SS7 linkset on span %d\n", x + 1);
18229                return -1;
18230             } else
18231                ast_verb(2, "Starting SS7 linkset on span %d\n", x + 1);
18232          }
18233       }
18234    }
18235 #endif   /* defined(HAVE_SS7) */
18236 #ifdef HAVE_OPENR2
18237    if (reload != 1) {
18238       int x;
18239       for (x = 0; x < r2links_count; x++) {
18240          if (ast_pthread_create(&r2links[x]->r2master, NULL, mfcr2_monitor, r2links[x])) {
18241             ast_log(LOG_ERROR, "Unable to start R2 monitor on channel group %d\n", x + 1);
18242             return -1;
18243          } else {
18244             ast_verb(2, "Starting R2 monitor on channel group %d\n", x + 1);
18245          }
18246       }
18247    }
18248 #endif
18249    /* And start the monitor for the first time */
18250    restart_monitor();
18251    return 0;
18252 }
18253 
18254 /*!
18255  * \internal
18256  * \brief Setup DAHDI channel driver.
18257  *
18258  * \param reload enum: load_module(0), reload(1), restart(2).
18259  *
18260  * \retval 0 on success.
18261  * \retval -1 on error.
18262  */
18263 static int setup_dahdi(int reload)
18264 {
18265    int res;
18266    struct dahdi_chan_conf default_conf = dahdi_chan_conf_default();
18267    struct dahdi_chan_conf base_conf = dahdi_chan_conf_default();
18268    struct dahdi_chan_conf conf = dahdi_chan_conf_default();
18269 
18270    if (default_conf.chan.cc_params && base_conf.chan.cc_params && conf.chan.cc_params) {
18271       res = setup_dahdi_int(reload, &default_conf, &base_conf, &conf);
18272    } else {
18273       res = -1;
18274    }
18275    ast_cc_config_params_destroy(default_conf.chan.cc_params);
18276    ast_cc_config_params_destroy(base_conf.chan.cc_params);
18277    ast_cc_config_params_destroy(conf.chan.cc_params);
18278 
18279    return res;
18280 }
18281 
18282 /*!
18283  * \internal
18284  * \brief Callback used to generate the dahdi status tree.
18285  * \param[in] search The search pattern tree.
18286  * \retval NULL on error.
18287  * \retval non-NULL The generated tree.
18288  */
18289 static int dahdi_status_data_provider_get(const struct ast_data_search *search,
18290       struct ast_data *data_root)
18291 {
18292    int ctl, res, span;
18293    struct ast_data *data_span, *data_alarms;
18294    struct dahdi_spaninfo s;
18295 
18296    ctl = open("/dev/dahdi/ctl", O_RDWR);
18297    if (ctl < 0) {
18298       ast_log(LOG_ERROR, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
18299       return -1;
18300    }
18301    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
18302       s.spanno = span;
18303       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
18304       if (res) {
18305          continue;
18306       }
18307 
18308       data_span = ast_data_add_node(data_root, "span");
18309       if (!data_span) {
18310          continue;
18311       }
18312       ast_data_add_str(data_span, "description", s.desc);
18313 
18314       /* insert the alarms status */
18315       data_alarms = ast_data_add_node(data_span, "alarms");
18316       if (!data_alarms) {
18317          continue;
18318       }
18319 
18320       ast_data_add_bool(data_alarms, "BLUE", s.alarms & DAHDI_ALARM_BLUE);
18321       ast_data_add_bool(data_alarms, "YELLOW", s.alarms & DAHDI_ALARM_YELLOW);
18322       ast_data_add_bool(data_alarms, "RED", s.alarms & DAHDI_ALARM_RED);
18323       ast_data_add_bool(data_alarms, "LOOPBACK", s.alarms & DAHDI_ALARM_LOOPBACK);
18324       ast_data_add_bool(data_alarms, "RECOVER", s.alarms & DAHDI_ALARM_RECOVER);
18325       ast_data_add_bool(data_alarms, "NOTOPEN", s.alarms & DAHDI_ALARM_NOTOPEN);
18326 
18327       ast_data_add_int(data_span, "irqmisses", s.irqmisses);
18328       ast_data_add_int(data_span, "bpviol", s.bpvcount);
18329       ast_data_add_int(data_span, "crc4", s.crc4count);
18330       ast_data_add_str(data_span, "framing", s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
18331                      s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
18332                      s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
18333                      "CAS");
18334       ast_data_add_str(data_span, "coding",  s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
18335                      s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
18336                      s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
18337                      "Unknown");
18338       ast_data_add_str(data_span, "options", s.lineconfig & DAHDI_CONFIG_CRC4 ?
18339                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
18340                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "");
18341       ast_data_add_str(data_span, "lbo", lbostr[s.lbo]);
18342 
18343       /* if this span doesn't match remove it. */
18344       if (!ast_data_search_match(search, data_span)) {
18345          ast_data_remove_node(data_root, data_span);
18346       }
18347    }
18348    close(ctl);
18349 
18350    return 0;
18351 }
18352 
18353 /*!
18354  * \internal
18355  * \brief Callback used to generate the dahdi channels tree.
18356  * \param[in] search The search pattern tree.
18357  * \retval NULL on error.
18358  * \retval non-NULL The generated tree.
18359  */
18360 static int dahdi_channels_data_provider_get(const struct ast_data_search *search,
18361       struct ast_data *data_root)
18362 {
18363    struct dahdi_pvt *tmp;
18364    struct ast_data *data_channel;
18365 
18366    ast_mutex_lock(&iflock);
18367    for (tmp = iflist; tmp; tmp = tmp->next) {
18368       data_channel = ast_data_add_node(data_root, "channel");
18369       if (!data_channel) {
18370          continue;
18371       }
18372 
18373       ast_data_add_structure(dahdi_pvt, data_channel, tmp);
18374 
18375       /* if this channel doesn't match remove it. */
18376       if (!ast_data_search_match(search, data_channel)) {
18377          ast_data_remove_node(data_root, data_channel);
18378       }
18379    }
18380    ast_mutex_unlock(&iflock);
18381 
18382    return 0;
18383 }
18384 
18385 /*!
18386  * \internal
18387  * \brief Callback used to generate the dahdi channels tree.
18388  * \param[in] search The search pattern tree.
18389  * \retval NULL on error.
18390  * \retval non-NULL The generated tree.
18391  */
18392 static int dahdi_version_data_provider_get(const struct ast_data_search *search,
18393       struct ast_data *data_root)
18394 {
18395    int pseudo_fd = -1;
18396    struct dahdi_versioninfo vi = {
18397       .version = "Unknown",
18398       .echo_canceller = "Unknown"
18399    };
18400 
18401    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
18402       ast_log(LOG_ERROR, "Failed to open control file to get version.\n");
18403       return -1;
18404    }
18405 
18406    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi)) {
18407       ast_log(LOG_ERROR, "Failed to get DAHDI version: %s\n", strerror(errno));
18408    }
18409 
18410    close(pseudo_fd);
18411 
18412    ast_data_add_str(data_root, "value", vi.version);
18413    ast_data_add_str(data_root, "echocanceller", vi.echo_canceller);
18414 
18415    return 0;
18416 }
18417 
18418 static const struct ast_data_handler dahdi_status_data_provider = {
18419    .version = AST_DATA_HANDLER_VERSION,
18420    .get = dahdi_status_data_provider_get
18421 };
18422 
18423 static const struct ast_data_handler dahdi_channels_data_provider = {
18424    .version = AST_DATA_HANDLER_VERSION,
18425    .get = dahdi_channels_data_provider_get
18426 };
18427 
18428 static const struct ast_data_handler dahdi_version_data_provider = {
18429    .version = AST_DATA_HANDLER_VERSION,
18430    .get = dahdi_version_data_provider_get
18431 };
18432 
18433 static const struct ast_data_entry dahdi_data_providers[] = {
18434    AST_DATA_ENTRY("asterisk/channel/dahdi/status", &dahdi_status_data_provider),
18435    AST_DATA_ENTRY("asterisk/channel/dahdi/channels", &dahdi_channels_data_provider),
18436    AST_DATA_ENTRY("asterisk/channel/dahdi/version", &dahdi_version_data_provider)
18437 };
18438 
18439 static int load_module(void)
18440 {
18441    int res;
18442 #if defined(HAVE_PRI) || defined(HAVE_SS7)
18443    int y;
18444 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
18445 
18446 #ifdef HAVE_PRI
18447    memset(pris, 0, sizeof(pris));
18448    for (y = 0; y < NUM_SPANS; y++) {
18449       sig_pri_init_pri(&pris[y].pri);
18450    }
18451    pri_set_error(dahdi_pri_error);
18452    pri_set_message(dahdi_pri_message);
18453    ast_register_application_xml(dahdi_send_keypad_facility_app, dahdi_send_keypad_facility_exec);
18454 #ifdef HAVE_PRI_PROG_W_CAUSE
18455    ast_register_application_xml(dahdi_send_callrerouting_facility_app, dahdi_send_callrerouting_facility_exec);
18456 #endif
18457 #if defined(HAVE_PRI_CCSS)
18458    if (ast_cc_agent_register(&dahdi_pri_cc_agent_callbacks)
18459       || ast_cc_monitor_register(&dahdi_pri_cc_monitor_callbacks)) {
18460       __unload_module();
18461       return AST_MODULE_LOAD_FAILURE;
18462    }
18463 #endif   /* defined(HAVE_PRI_CCSS) */
18464    if (sig_pri_load(
18465 #if defined(HAVE_PRI_CCSS)
18466       dahdi_pri_cc_type
18467 #else
18468       NULL
18469 #endif   /* defined(HAVE_PRI_CCSS) */
18470       )) {
18471       __unload_module();
18472       return AST_MODULE_LOAD_FAILURE;
18473    }
18474 #endif
18475 #if defined(HAVE_SS7)
18476    memset(linksets, 0, sizeof(linksets));
18477    for (y = 0; y < NUM_SPANS; y++) {
18478       sig_ss7_init_linkset(&linksets[y].ss7);
18479    }
18480    ss7_set_error(dahdi_ss7_error);
18481    ss7_set_message(dahdi_ss7_message);
18482 #endif   /* defined(HAVE_SS7) */
18483    res = setup_dahdi(0);
18484    /* Make sure we can register our DAHDI channel type */
18485    if (res)
18486       return AST_MODULE_LOAD_DECLINE;
18487    if (ast_channel_register(&dahdi_tech)) {
18488       ast_log(LOG_ERROR, "Unable to register channel class 'DAHDI'\n");
18489       __unload_module();
18490       return AST_MODULE_LOAD_FAILURE;
18491    }
18492 #ifdef HAVE_PRI
18493    ast_cli_register_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
18494 #endif
18495 #if defined(HAVE_SS7)
18496    ast_cli_register_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
18497 #endif   /* defined(HAVE_SS7) */
18498 #ifdef HAVE_OPENR2
18499    ast_cli_register_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
18500    ast_register_application_xml(dahdi_accept_r2_call_app, dahdi_accept_r2_call_exec);
18501 #endif
18502 
18503    ast_cli_register_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
18504    /* register all the data providers */
18505    ast_data_register_multiple(dahdi_data_providers, ARRAY_LEN(dahdi_data_providers));
18506    memset(round_robin, 0, sizeof(round_robin));
18507    ast_manager_register_xml("DAHDITransfer", 0, action_transfer);
18508    ast_manager_register_xml("DAHDIHangup", 0, action_transferhangup);
18509    ast_manager_register_xml("DAHDIDialOffhook", 0, action_dahdidialoffhook);
18510    ast_manager_register_xml("DAHDIDNDon", 0, action_dahdidndon);
18511    ast_manager_register_xml("DAHDIDNDoff", 0, action_dahdidndoff);
18512    ast_manager_register_xml("DAHDIShowChannels", 0, action_dahdishowchannels);
18513    ast_manager_register_xml("DAHDIRestart", 0, action_dahdirestart);
18514 
18515    ast_cond_init(&ss_thread_complete, NULL);
18516 
18517    return res;
18518 }
18519 
18520 static int dahdi_sendtext(struct ast_channel *c, const char *text)
18521 {
18522 #define  END_SILENCE_LEN 400
18523 #define  HEADER_MS 50
18524 #define  TRAILER_MS 5
18525 #define  HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
18526 #define  ASCII_BYTES_PER_CHAR 80
18527 
18528    unsigned char *buf,*mybuf;
18529    struct dahdi_pvt *p = c->tech_pvt;
18530    struct pollfd fds[1];
18531    int size,res,fd,len,x;
18532    int bytes=0;
18533    /* Initial carrier (imaginary) */
18534    float cr = 1.0;
18535    float ci = 0.0;
18536    float scont = 0.0;
18537    int idx;
18538 
18539    idx = dahdi_get_index(c, p, 0);
18540    if (idx < 0) {
18541       ast_log(LOG_WARNING, "Huh?  I don't exist?\n");
18542       return -1;
18543    }
18544    if (!text[0]) return(0); /* if nothing to send, don't */
18545    if ((!p->tdd) && (!p->mate)) return(0);  /* if not in TDD mode, just return */
18546    if (p->mate)
18547       buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
18548    else
18549       buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
18550    if (!buf)
18551       return -1;
18552    mybuf = buf;
18553    if (p->mate) {
18554       int codec = AST_LAW(p);
18555       for (x = 0; x < HEADER_MS; x++) {   /* 50 ms of Mark */
18556          PUT_CLID_MARKMS;
18557       }
18558       /* Put actual message */
18559       for (x = 0; text[x]; x++) {
18560          PUT_CLID(text[x]);
18561       }
18562       for (x = 0; x < TRAILER_MS; x++) {  /* 5 ms of Mark */
18563          PUT_CLID_MARKMS;
18564       }
18565       len = bytes;
18566       buf = mybuf;
18567    } else {
18568       len = tdd_generate(p->tdd, buf, text);
18569       if (len < 1) {
18570          ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
18571          ast_free(mybuf);
18572          return -1;
18573       }
18574    }
18575    memset(buf + len, 0x7f, END_SILENCE_LEN);
18576    len += END_SILENCE_LEN;
18577    fd = p->subs[idx].dfd;
18578    while (len) {
18579       if (ast_check_hangup(c)) {
18580          ast_free(mybuf);
18581          return -1;
18582       }
18583       size = len;
18584       if (size > READ_SIZE)
18585          size = READ_SIZE;
18586       fds[0].fd = fd;
18587       fds[0].events = POLLOUT | POLLPRI;
18588       fds[0].revents = 0;
18589       res = poll(fds, 1, -1);
18590       if (!res) {
18591          ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
18592          continue;
18593       }
18594       /* if got exception */
18595       if (fds[0].revents & POLLPRI) {
18596          ast_free(mybuf);
18597          return -1;
18598       }
18599       if (!(fds[0].revents & POLLOUT)) {
18600          ast_debug(1, "write fd not ready on channel %d\n", p->channel);
18601          continue;
18602       }
18603       res = write(fd, buf, size);
18604       if (res != size) {
18605          if (res == -1) {
18606             ast_free(mybuf);
18607             return -1;
18608          }
18609          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
18610          break;
18611       }
18612       len -= size;
18613       buf += size;
18614    }
18615    ast_free(mybuf);
18616    return(0);
18617 }
18618 
18619 
18620 static int reload(void)
18621 {
18622    int res = 0;
18623 
18624    res = setup_dahdi(1);
18625    if (res) {
18626       ast_log(LOG_WARNING, "Reload of chan_dahdi.so is unsuccessful!\n");
18627       return -1;
18628    }
18629    return 0;
18630 }
18631 
18632 /* This is a workaround so that menuselect displays a proper description
18633  * AST_MODULE_INFO(, , "DAHDI Telephony"
18634  */
18635 
18636 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, tdesc,
18637    .load = load_module,
18638    .unload = unload_module,
18639    .reload = reload,
18640    .load_pri = AST_MODPRI_CHANNEL_DRIVER,
18641       .nonoptreq = "res_smdi",
18642    );