Fri Jan 18 19:57:07 2013

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: 378781 $")
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 #if defined(HAVE_PRI)
00075 #include "sig_pri.h"
00076 #ifndef PRI_RESTART
00077 #error "Upgrade your libpri"
00078 #endif
00079 #endif   /* defined(HAVE_PRI) */
00080 
00081 #if defined(HAVE_SS7)
00082 #include "sig_ss7.h"
00083 #if defined(LIBSS7_ABI_COMPATIBILITY)
00084 #error "Your installed libss7 is not compatible"
00085 #endif
00086 #endif   /* defined(HAVE_SS7) */
00087 
00088 #ifdef HAVE_OPENR2
00089 /* put this here until sig_mfcr2 comes along */
00090 #define SIG_MFCR2_MAX_CHANNELS   672      /*!< No more than a DS3 per trunk group */
00091 #include <openr2.h>
00092 #endif
00093 
00094 #include "asterisk/lock.h"
00095 #include "asterisk/channel.h"
00096 #include "asterisk/config.h"
00097 #include "asterisk/module.h"
00098 #include "asterisk/pbx.h"
00099 #include "asterisk/file.h"
00100 #include "asterisk/ulaw.h"
00101 #include "asterisk/alaw.h"
00102 #include "asterisk/callerid.h"
00103 #include "asterisk/adsi.h"
00104 #include "asterisk/cli.h"
00105 #include "asterisk/cdr.h"
00106 #include "asterisk/cel.h"
00107 #include "asterisk/features.h"
00108 #include "asterisk/musiconhold.h"
00109 #include "asterisk/say.h"
00110 #include "asterisk/tdd.h"
00111 #include "asterisk/app.h"
00112 #include "asterisk/dsp.h"
00113 #include "asterisk/astdb.h"
00114 #include "asterisk/manager.h"
00115 #include "asterisk/causes.h"
00116 #include "asterisk/term.h"
00117 #include "asterisk/utils.h"
00118 #include "asterisk/transcap.h"
00119 #include "asterisk/stringfields.h"
00120 #include "asterisk/abstract_jb.h"
00121 #include "asterisk/smdi.h"
00122 #include "asterisk/astobj.h"
00123 #include "asterisk/event.h"
00124 #include "asterisk/devicestate.h"
00125 #include "asterisk/paths.h"
00126 #include "asterisk/ccss.h"
00127 #include "asterisk/data.h"
00128 
00129 /*** DOCUMENTATION
00130    <application name="DAHDISendKeypadFacility" language="en_US">
00131       <synopsis>
00132          Send digits out of band over a PRI.
00133       </synopsis>
00134       <syntax>
00135          <parameter name="digits" required="true" />
00136       </syntax>
00137       <description>
00138          <para>This application will send the given string of digits in a Keypad
00139          Facility IE over the current channel.</para>
00140       </description>
00141    </application>
00142    <application name="DAHDISendCallreroutingFacility" language="en_US">
00143       <synopsis>
00144          Send an ISDN call rerouting/deflection facility message.
00145       </synopsis>
00146       <syntax argsep=",">
00147          <parameter name="destination" required="true">
00148             <para>Destination number.</para>
00149          </parameter>
00150          <parameter name="original">
00151             <para>Original called number.</para>
00152          </parameter>
00153          <parameter name="reason">
00154             <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
00155          </parameter>
00156       </syntax>
00157       <description>
00158          <para>This application will send an ISDN switch specific call
00159          rerouting/deflection facility message over the current channel.
00160          Supported switches depend upon the version of libpri in use.</para>
00161       </description>
00162    </application>
00163    <application name="DAHDIAcceptR2Call" language="en_US">
00164       <synopsis>
00165          Accept an R2 call if its not already accepted (you still need to answer it)
00166       </synopsis>
00167       <syntax>
00168          <parameter name="charge" required="true">
00169             <para>Yes or No.</para>
00170             <para>Whether you want to accept the call with charge or without charge.</para>
00171          </parameter>
00172       </syntax>
00173       <description>
00174          <para>This application will Accept the R2 call either with charge or no charge.</para>
00175       </description>
00176    </application>
00177    <manager name="DAHDITransfer" language="en_US">
00178       <synopsis>
00179          Transfer DAHDI Channel.
00180       </synopsis>
00181       <syntax>
00182          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00183          <parameter name="DAHDIChannel" required="true">
00184             <para>DAHDI channel number to transfer.</para>
00185          </parameter>
00186       </syntax>
00187       <description>
00188          <para>Simulate a flash hook event by the user connected to the channel.</para>
00189          <note><para>Valid only for analog channels.</para></note>
00190       </description>
00191    </manager>
00192    <manager name="DAHDIHangup" language="en_US">
00193       <synopsis>
00194          Hangup DAHDI Channel.
00195       </synopsis>
00196       <syntax>
00197          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00198          <parameter name="DAHDIChannel" required="true">
00199             <para>DAHDI channel number to hangup.</para>
00200          </parameter>
00201       </syntax>
00202       <description>
00203          <para>Simulate an on-hook event by the user connected to the channel.</para>
00204          <note><para>Valid only for analog channels.</para></note>
00205       </description>
00206    </manager>
00207    <manager name="DAHDIDialOffhook" language="en_US">
00208       <synopsis>
00209          Dial over DAHDI channel while offhook.
00210       </synopsis>
00211       <syntax>
00212          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00213          <parameter name="DAHDIChannel" required="true">
00214             <para>DAHDI channel number to dial digits.</para>
00215          </parameter>
00216          <parameter name="Number" required="true">
00217             <para>Digits to dial.</para>
00218          </parameter>
00219       </syntax>
00220       <description>
00221          <para>Generate DTMF control frames to the bridged peer.</para>
00222       </description>
00223    </manager>
00224    <manager name="DAHDIDNDon" language="en_US">
00225       <synopsis>
00226          Toggle DAHDI channel Do Not Disturb status ON.
00227       </synopsis>
00228       <syntax>
00229          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00230          <parameter name="DAHDIChannel" required="true">
00231             <para>DAHDI channel number to set DND on.</para>
00232          </parameter>
00233       </syntax>
00234       <description>
00235          <para>Equivalent to the CLI command "dahdi set dnd <variable>channel</variable> on".</para>
00236          <note><para>Feature only supported by analog channels.</para></note>
00237       </description>
00238    </manager>
00239    <manager name="DAHDIDNDoff" language="en_US">
00240       <synopsis>
00241          Toggle DAHDI channel Do Not Disturb status OFF.
00242       </synopsis>
00243       <syntax>
00244          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00245          <parameter name="DAHDIChannel" required="true">
00246             <para>DAHDI channel number to set DND off.</para>
00247          </parameter>
00248       </syntax>
00249       <description>
00250          <para>Equivalent to the CLI command "dahdi set dnd <variable>channel</variable> off".</para>
00251          <note><para>Feature only supported by analog channels.</para></note>
00252       </description>
00253    </manager>
00254    <manager name="DAHDIShowChannels" language="en_US">
00255       <synopsis>
00256          Show status of DAHDI channels.
00257       </synopsis>
00258       <syntax>
00259          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00260          <parameter name="DAHDIChannel">
00261             <para>Specify the specific channel number to show.  Show all channels if zero or not present.</para>
00262          </parameter>
00263       </syntax>
00264       <description>
00265          <para>Similar to the CLI command "dahdi show channels".</para>
00266       </description>
00267    </manager>
00268    <manager name="DAHDIRestart" language="en_US">
00269       <synopsis>
00270          Fully Restart DAHDI channels (terminates calls).
00271       </synopsis>
00272       <syntax>
00273          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00274       </syntax>
00275       <description>
00276          <para>Equivalent to the CLI command "dahdi restart".</para>
00277       </description>
00278    </manager>
00279  ***/
00280 
00281 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
00282 
00283 static const char * const lbostr[] = {
00284 "0 db (CSU)/0-133 feet (DSX-1)",
00285 "133-266 feet (DSX-1)",
00286 "266-399 feet (DSX-1)",
00287 "399-533 feet (DSX-1)",
00288 "533-655 feet (DSX-1)",
00289 "-7.5db (CSU)",
00290 "-15db (CSU)",
00291 "-22.5db (CSU)"
00292 };
00293 
00294 /*! Global jitterbuffer configuration - by default, jb is disabled
00295  *  \note Values shown here match the defaults shown in chan_dahdi.conf.sample */
00296 static struct ast_jb_conf default_jbconf =
00297 {
00298    .flags = 0,
00299    .max_size = 200,
00300    .resync_threshold = 1000,
00301    .impl = "fixed",
00302    .target_extra = 40,
00303 };
00304 static struct ast_jb_conf global_jbconf;
00305 
00306 /*!
00307  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
00308  * the user hangs up to reset the state machine so ring works properly.
00309  * This is used to be able to support kewlstart by putting the zhone in
00310  * groundstart mode since their forward disconnect supervision is entirely
00311  * broken even though their documentation says it isn't and their support
00312  * is entirely unwilling to provide any assistance with their channel banks
00313  * even though their web site says they support their products for life.
00314  */
00315 /* #define ZHONE_HACK */
00316 
00317 /*! \brief Typically, how many rings before we should send Caller*ID */
00318 #define DEFAULT_CIDRINGS 1
00319 
00320 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
00321 
00322 
00323 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
00324 #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))
00325 
00326 static const char tdesc[] = "DAHDI Telephony Driver"
00327 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
00328    " w/"
00329    #if defined(HAVE_PRI)
00330       "PRI"
00331    #endif   /* defined(HAVE_PRI) */
00332    #if defined(HAVE_SS7)
00333       #if defined(HAVE_PRI)
00334       " & "
00335       #endif   /* defined(HAVE_PRI) */
00336       "SS7"
00337    #endif   /* defined(HAVE_SS7) */
00338    #if defined(HAVE_OPENR2)
00339       #if defined(HAVE_PRI) || defined(HAVE_SS7)
00340       " & "
00341       #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
00342       "MFC/R2"
00343    #endif   /* defined(HAVE_OPENR2) */
00344 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2) */
00345 ;
00346 
00347 static const char config[] = "chan_dahdi.conf";
00348 
00349 #define SIG_EM    DAHDI_SIG_EM
00350 #define SIG_EMWINK   (0x0100000 | DAHDI_SIG_EM)
00351 #define SIG_FEATD (0x0200000 | DAHDI_SIG_EM)
00352 #define  SIG_FEATDMF (0x0400000 | DAHDI_SIG_EM)
00353 #define  SIG_FEATB   (0x0800000 | DAHDI_SIG_EM)
00354 #define  SIG_E911 (0x1000000 | DAHDI_SIG_EM)
00355 #define  SIG_FEATDMF_TA (0x2000000 | DAHDI_SIG_EM)
00356 #define  SIG_FGC_CAMA   (0x4000000 | DAHDI_SIG_EM)
00357 #define  SIG_FGC_CAMAMF (0x8000000 | DAHDI_SIG_EM)
00358 #define SIG_FXSLS DAHDI_SIG_FXSLS
00359 #define SIG_FXSGS DAHDI_SIG_FXSGS
00360 #define SIG_FXSKS DAHDI_SIG_FXSKS
00361 #define SIG_FXOLS DAHDI_SIG_FXOLS
00362 #define SIG_FXOGS DAHDI_SIG_FXOGS
00363 #define SIG_FXOKS DAHDI_SIG_FXOKS
00364 #define SIG_PRI      DAHDI_SIG_CLEAR
00365 #define SIG_BRI      (0x2000000 | DAHDI_SIG_CLEAR)
00366 #define SIG_BRI_PTMP (0X4000000 | DAHDI_SIG_CLEAR)
00367 #define SIG_SS7      (0x1000000 | DAHDI_SIG_CLEAR)
00368 #define SIG_MFCR2    DAHDI_SIG_CAS
00369 #define  SIG_SF      DAHDI_SIG_SF
00370 #define SIG_SFWINK   (0x0100000 | DAHDI_SIG_SF)
00371 #define SIG_SF_FEATD (0x0200000 | DAHDI_SIG_SF)
00372 #define  SIG_SF_FEATDMF (0x0400000 | DAHDI_SIG_SF)
00373 #define  SIG_SF_FEATB   (0x0800000 | DAHDI_SIG_SF)
00374 #define SIG_EM_E1 DAHDI_SIG_EM_E1
00375 
00376 #ifdef LOTS_OF_SPANS
00377 #define NUM_SPANS DAHDI_MAX_SPANS
00378 #else
00379 #define NUM_SPANS       32
00380 #endif
00381 
00382 #define CHAN_PSEUDO  -2
00383 
00384 #define CALLPROGRESS_PROGRESS    1
00385 #define CALLPROGRESS_FAX_OUTGOING   2
00386 #define CALLPROGRESS_FAX_INCOMING   4
00387 #define CALLPROGRESS_FAX      (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
00388 
00389 #define NUM_CADENCE_MAX 25
00390 static int num_cadence = 4;
00391 static int user_has_defined_cadences = 0;
00392 
00393 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
00394    { { 125, 125, 2000, 4000 } },       /*!< Quick chirp followed by normal ring */
00395    { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
00396    { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
00397    { { 1000, 500, 2500, 5000 } },   /*!< Long ring */
00398 };
00399 
00400 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
00401  * is 1, the second pause is 2 and so on.
00402  */
00403 
00404 static int cidrings[NUM_CADENCE_MAX] = {
00405    2,                            /*!< Right after first long ring */
00406    4,                            /*!< Right after long part */
00407    3,                            /*!< After third chirp */
00408    2,                            /*!< Second spell */
00409 };
00410 
00411 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
00412 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
00413 
00414 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
00415          (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
00416 
00417 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
00418 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
00419 
00420 static char defaultcic[64] = "";
00421 static char defaultozz[64] = "";
00422 
00423 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
00424 static char mwimonitornotify[PATH_MAX] = "";
00425 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
00426 static int  mwisend_rpas = 0;
00427 #endif
00428 
00429 static char progzone[10] = "";
00430 
00431 static int usedistinctiveringdetection = 0;
00432 static int distinctiveringaftercid = 0;
00433 
00434 static int numbufs = 4;
00435 
00436 static int mwilevel = 512;
00437 static int dtmfcid_level = 256;
00438 
00439 #define REPORT_CHANNEL_ALARMS 1
00440 #define REPORT_SPAN_ALARMS    2 
00441 static int report_alarms = REPORT_CHANNEL_ALARMS;
00442 
00443 #ifdef HAVE_PRI
00444 static int pridebugfd = -1;
00445 static char pridebugfilename[1024] = "";
00446 #endif
00447 
00448 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
00449 static int firstdigittimeout = 16000;
00450 
00451 /*! \brief How long to wait for following digits (FXO logic) */
00452 static int gendigittimeout = 8000;
00453 
00454 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
00455 static int matchdigittimeout = 3000;
00456 
00457 /*! \brief Protect the interface list (of dahdi_pvt's) */
00458 AST_MUTEX_DEFINE_STATIC(iflock);
00459 
00460 
00461 static int ifcount = 0;
00462 
00463 #ifdef HAVE_PRI
00464 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
00465 #endif
00466 
00467 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00468    when it's doing something critical. */
00469 AST_MUTEX_DEFINE_STATIC(monlock);
00470 
00471 /*! \brief This is the thread for the monitor which checks for input on the channels
00472    which are not currently in use. */
00473 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00474 static ast_cond_t ss_thread_complete;
00475 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
00476 AST_MUTEX_DEFINE_STATIC(restart_lock);
00477 static int ss_thread_count = 0;
00478 static int num_restart_pending = 0;
00479 
00480 static int restart_monitor(void);
00481 
00482 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);
00483 
00484 static int dahdi_sendtext(struct ast_channel *c, const char *text);
00485 
00486 static void mwi_event_cb(const struct ast_event *event, void *userdata)
00487 {
00488    /* This module does not handle MWI in an event-based manner.  However, it
00489     * subscribes to MWI for each mailbox that is configured so that the core
00490     * knows that we care about it.  Then, chan_dahdi will get the MWI from the
00491     * event cache instead of checking the mailbox directly. */
00492 }
00493 
00494 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
00495 static inline int dahdi_get_event(int fd)
00496 {
00497    int j;
00498    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00499       return -1;
00500    return j;
00501 }
00502 
00503 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
00504 static inline int dahdi_wait_event(int fd)
00505 {
00506    int i, j = 0;
00507    i = DAHDI_IOMUX_SIGEVENT;
00508    if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
00509       return -1;
00510    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00511       return -1;
00512    return j;
00513 }
00514 
00515 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
00516 #define READ_SIZE 160
00517 
00518 #define MASK_AVAIL      (1 << 0) /*!< Channel available for PRI use */
00519 #define MASK_INUSE      (1 << 1) /*!< Channel currently in use */
00520 
00521 #define CALLWAITING_SILENT_SAMPLES     ((300 * 8) / READ_SIZE) /*!< 300 ms */
00522 #define CALLWAITING_REPEAT_SAMPLES     ((10000 * 8) / READ_SIZE) /*!< 10,000 ms */
00523 #define CALLWAITING_SUPPRESS_SAMPLES   ((100 * 8) / READ_SIZE) /*!< 100 ms */
00524 #define CIDCW_EXPIRE_SAMPLES        ((500 * 8) / READ_SIZE) /*!< 500 ms */
00525 #define MIN_MS_SINCE_FLASH          ((2000) )   /*!< 2000 ms */
00526 #define DEFAULT_RINGT               ((8000 * 8) / READ_SIZE) /*!< 8,000 ms */
00527 
00528 struct dahdi_pvt;
00529 
00530 /*!
00531  * \brief Configured ring timeout base.
00532  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
00533  */
00534 static int ringt_base = DEFAULT_RINGT;
00535 
00536 #if defined(HAVE_SS7)
00537 
00538 struct dahdi_ss7 {
00539    struct sig_ss7_linkset ss7;
00540 };
00541 
00542 static struct dahdi_ss7 linksets[NUM_SPANS];
00543 
00544 static int cur_ss7type = -1;
00545 static int cur_linkset = -1;
00546 static int cur_pointcode = -1;
00547 static int cur_cicbeginswith = -1;
00548 static int cur_adjpointcode = -1;
00549 static int cur_networkindicator = -1;
00550 static int cur_defaultdpc = -1;
00551 #endif   /* defined(HAVE_SS7) */
00552 
00553 #ifdef HAVE_OPENR2
00554 struct dahdi_mfcr2 {
00555    pthread_t r2master;            /*!< Thread of master */
00556    openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
00557    struct dahdi_pvt *pvts[SIG_MFCR2_MAX_CHANNELS];     /*!< Member channel pvt structs */
00558    int numchans;                          /*!< Number of channels in this R2 block */
00559    int monitored_count;                   /*!< Number of channels being monitored */
00560 };
00561 
00562 struct dahdi_mfcr2_conf {
00563    openr2_variant_t variant;
00564    int mfback_timeout;
00565    int metering_pulse_timeout;
00566    int max_ani;
00567    int max_dnis;
00568    signed int get_ani_first:2;
00569 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
00570    signed int skip_category_request:2;
00571 #endif
00572    unsigned int call_files:1;
00573    unsigned int allow_collect_calls:1;
00574    unsigned int charge_calls:1;
00575    unsigned int accept_on_offer:1;
00576    unsigned int forced_release:1;
00577    unsigned int double_answer:1;
00578    signed int immediate_accept:2;
00579    char logdir[OR2_MAX_PATH];
00580    char r2proto_file[OR2_MAX_PATH];
00581    openr2_log_level_t loglevel;
00582    openr2_calling_party_category_t category;
00583 };
00584 
00585 /* malloc'd array of malloc'd r2links */
00586 static struct dahdi_mfcr2 **r2links;
00587 /* how many r2links have been malloc'd */
00588 static int r2links_count = 0;
00589 
00590 #endif /* HAVE_OPENR2 */
00591 
00592 #ifdef HAVE_PRI
00593 
00594 struct dahdi_pri {
00595    int dchannels[SIG_PRI_NUM_DCHANS];     /*!< What channel are the dchannels on */
00596    int mastertrunkgroup;               /*!< What trunk group is our master */
00597    int prilogicalspan;                 /*!< Logical span number within trunk group */
00598    struct sig_pri_span pri;
00599 };
00600 
00601 static struct dahdi_pri pris[NUM_SPANS];
00602 
00603 #if defined(HAVE_PRI_CCSS)
00604 /*! DAHDI PRI CCSS agent and monitor type name. */
00605 static const char dahdi_pri_cc_type[] = "DAHDI/PRI";
00606 #endif   /* defined(HAVE_PRI_CCSS) */
00607 
00608 #else
00609 /*! Shut up the compiler */
00610 struct dahdi_pri;
00611 #endif
00612 
00613 #define SUB_REAL  0        /*!< Active call */
00614 #define SUB_CALLWAIT 1        /*!< Call-Waiting call on hold */
00615 #define SUB_THREEWAY 2        /*!< Three-way call */
00616 
00617 /* Polarity states */
00618 #define POLARITY_IDLE   0
00619 #define POLARITY_REV    1
00620 
00621 
00622 struct distRingData {
00623    int ring[3];
00624    int range;
00625 };
00626 struct ringContextData {
00627    char contextData[AST_MAX_CONTEXT];
00628 };
00629 struct dahdi_distRings {
00630    struct distRingData ringnum[3];
00631    struct ringContextData ringContext[3];
00632 };
00633 
00634 static const char * const subnames[] = {
00635    "Real",
00636    "Callwait",
00637    "Threeway"
00638 };
00639 
00640 struct dahdi_subchannel {
00641    int dfd;
00642    struct ast_channel *owner;
00643    int chan;
00644    short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
00645    struct ast_frame f;     /*!< One frame for each channel.  How did this ever work before? */
00646    unsigned int needringing:1;
00647    unsigned int needbusy:1;
00648    unsigned int needcongestion:1;
00649    unsigned int needanswer:1;
00650    unsigned int needflash:1;
00651    unsigned int needhold:1;
00652    unsigned int needunhold:1;
00653    unsigned int linear:1;
00654    unsigned int inthreeway:1;
00655    struct dahdi_confinfo curconf;
00656 };
00657 
00658 #define CONF_USER_REAL     (1 << 0)
00659 #define CONF_USER_THIRDCALL   (1 << 1)
00660 
00661 #define MAX_SLAVES   4
00662 
00663 /* States for sending MWI message
00664  * First three states are required for send Ring Pulse Alert Signal
00665  */
00666 typedef enum {
00667    MWI_SEND_NULL = 0,
00668    MWI_SEND_SA,
00669    MWI_SEND_SA_WAIT,
00670    MWI_SEND_PAUSE,
00671    MWI_SEND_SPILL,
00672    MWI_SEND_CLEANUP,
00673    MWI_SEND_DONE,
00674 } mwisend_states;
00675 
00676 struct mwisend_info {
00677    struct   timeval  pause;
00678    mwisend_states    mwisend_current;
00679 };
00680 
00681 /*! Specify the lists dahdi_pvt can be put in. */
00682 enum DAHDI_IFLIST {
00683    DAHDI_IFLIST_NONE,   /*!< The dahdi_pvt is not in any list. */
00684    DAHDI_IFLIST_MAIN,   /*!< The dahdi_pvt is in the main interface list */
00685 #if defined(HAVE_PRI)
00686    DAHDI_IFLIST_NO_B_CHAN, /*!< The dahdi_pvt is in a no B channel interface list */
00687 #endif   /* defined(HAVE_PRI) */
00688 };
00689 
00690 struct dahdi_pvt {
00691    ast_mutex_t lock;             /*!< Channel private lock. */
00692    struct callerid_state *cs;
00693    struct ast_channel *owner;       /*!< Our current active owner (if applicable) */
00694                      /*!< Up to three channels can be associated with this call */
00695 
00696    struct dahdi_subchannel sub_unused;    /*!< Just a safety precaution */
00697    struct dahdi_subchannel subs[3];       /*!< Sub-channels */
00698    struct dahdi_confinfo saveconf;        /*!< Saved conference info */
00699 
00700    struct dahdi_pvt *slaves[MAX_SLAVES];     /*!< Slave to us (follows our conferencing) */
00701    struct dahdi_pvt *master;           /*!< Master to us (we follow their conferencing) */
00702    int inconference;          /*!< If our real should be in the conference */
00703 
00704    int bufsize;                /*!< Size of the buffers */
00705    int buf_no;             /*!< Number of buffers */
00706    int buf_policy;            /*!< Buffer policy */
00707    int faxbuf_no;              /*!< Number of Fax buffers */
00708    int faxbuf_policy;          /*!< Fax buffer policy */
00709    int sig;             /*!< Signalling style */
00710    /*!
00711     * \brief Nonzero if the signaling type is sent over a radio.
00712     * \note Set to a couple of nonzero values but it is only tested like a boolean.
00713     */
00714    int radio;
00715    int outsigmod;             /*!< Outbound Signalling style (modifier) */
00716    int oprmode;               /*!< "Operator Services" mode */
00717    struct dahdi_pvt *oprpeer;          /*!< "Operator Services" peer tech_pvt ptr */
00718    /*! \brief Amount of gain to increase during caller id */
00719    float cid_rxgain;
00720    /*! \brief Rx gain set by chan_dahdi.conf */
00721    float rxgain;
00722    /*! \brief Tx gain set by chan_dahdi.conf */
00723    float txgain;
00724 
00725    float txdrc; /*!< Dynamic Range Compression factor. a number between 1 and 6ish */
00726    float rxdrc;
00727    
00728    int tonezone;              /*!< tone zone for this chan, or -1 for default */
00729    enum DAHDI_IFLIST which_iflist;  /*!< Which interface list is this structure listed? */
00730    struct dahdi_pvt *next;          /*!< Next channel in list */
00731    struct dahdi_pvt *prev;          /*!< Prev channel in list */
00732 
00733    /* flags */
00734 
00735    /*!
00736     * \brief TRUE if ADSI (Analog Display Services Interface) available
00737     * \note Set from the "adsi" value read in from chan_dahdi.conf
00738     */
00739    unsigned int adsi:1;
00740    /*!
00741     * \brief TRUE if we can use a polarity reversal to mark when an outgoing
00742     * call is answered by the remote party.
00743     * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
00744     */
00745    unsigned int answeronpolarityswitch:1;
00746    /*!
00747     * \brief TRUE if busy detection is enabled.
00748     * (Listens for the beep-beep busy pattern.)
00749     * \note Set from the "busydetect" value read in from chan_dahdi.conf
00750     */
00751    unsigned int busydetect:1;
00752    /*!
00753     * \brief TRUE if call return is enabled.
00754     * (*69, if your dialplan doesn't catch this first)
00755     * \note Set from the "callreturn" value read in from chan_dahdi.conf
00756     */
00757    unsigned int callreturn:1;
00758    /*!
00759     * \brief TRUE if busy extensions will hear the call-waiting tone
00760     * and can use hook-flash to switch between callers.
00761     * \note Can be disabled by dialing *70.
00762     * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
00763     */
00764    unsigned int callwaiting:1;
00765    /*!
00766     * \brief TRUE if send caller ID for Call Waiting
00767     * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
00768     */
00769    unsigned int callwaitingcallerid:1;
00770    /*!
00771     * \brief TRUE if support for call forwarding enabled.
00772     * Dial *72 to enable call forwarding.
00773     * Dial *73 to disable call forwarding.
00774     * \note Set from the "cancallforward" value read in from chan_dahdi.conf
00775     */
00776    unsigned int cancallforward:1;
00777    /*!
00778     * \brief TRUE if support for call parking is enabled.
00779     * \note Set from the "canpark" value read in from chan_dahdi.conf
00780     */
00781    unsigned int canpark:1;
00782    /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
00783    unsigned int confirmanswer:1;
00784    /*!
00785     * \brief TRUE if the channel is to be destroyed on hangup.
00786     * (Used by pseudo channels.)
00787     */
00788    unsigned int destroy:1;
00789    unsigned int didtdd:1;           /*!< flag to say its done it once */
00790    /*! \brief TRUE if analog type line dialed no digits in Dial() */
00791    unsigned int dialednone:1;
00792    /*!
00793     * \brief TRUE if in the process of dialing digits or sending something.
00794     * \note This is used as a receive squelch for ISDN until connected.
00795     */
00796    unsigned int dialing:1;
00797    /*! \brief TRUE if the transfer capability of the call is digital. */
00798    unsigned int digital:1;
00799    /*! \brief TRUE if Do-Not-Disturb is enabled, present only for non sig_analog */
00800    unsigned int dnd:1;
00801    /*! \brief XXX BOOLEAN Purpose??? */
00802    unsigned int echobreak:1;
00803    /*!
00804     * \brief TRUE if echo cancellation enabled when bridged.
00805     * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
00806     * \note Disabled if the echo canceller is not setup.
00807     */
00808    unsigned int echocanbridged:1;
00809    /*! \brief TRUE if echo cancellation is turned on. */
00810    unsigned int echocanon:1;
00811    /*! \brief TRUE if a fax tone has already been handled. */
00812    unsigned int faxhandled:1;
00813    /*! TRUE if dynamic faxbuffers are configured for use, default is OFF */
00814    unsigned int usefaxbuffers:1;
00815    /*! TRUE while buffer configuration override is in use */
00816    unsigned int bufferoverrideinuse:1;
00817    /*! \brief TRUE if over a radio and dahdi_read() has been called. */
00818    unsigned int firstradio:1;
00819    /*!
00820     * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
00821     * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
00822     */
00823    unsigned int hanguponpolarityswitch:1;
00824    /*! \brief TRUE if DTMF detection needs to be done by hardware. */
00825    unsigned int hardwaredtmf:1;
00826    /*!
00827     * \brief TRUE if the outgoing caller ID is blocked/hidden.
00828     * \note Caller ID can be disabled by dialing *67.
00829     * \note Caller ID can be enabled by dialing *82.
00830     * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
00831     */
00832    unsigned int hidecallerid:1;
00833    /*!
00834     * \brief TRUE if hide just the name not the number for legacy PBX use.
00835     * \note Only applies to PRI channels.
00836     * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
00837     */
00838    unsigned int hidecalleridname:1;
00839    /*! \brief TRUE if DTMF detection is disabled. */
00840    unsigned int ignoredtmf:1;
00841    /*!
00842     * \brief TRUE if the channel should be answered immediately
00843     * without attempting to gather any digits.
00844     * \note Set from the "immediate" value read in from chan_dahdi.conf
00845     */
00846    unsigned int immediate:1;
00847    /*! \brief TRUE if in an alarm condition. */
00848    unsigned int inalarm:1;
00849    /*! \brief TRUE if TDD in MATE mode */
00850    unsigned int mate:1;
00851    /*! \brief TRUE if we originated the call leg. */
00852    unsigned int outgoing:1;
00853    /* unsigned int overlapdial:1;         unused and potentially confusing */
00854    /*!
00855     * \brief TRUE if busy extensions will hear the call-waiting tone
00856     * and can use hook-flash to switch between callers.
00857     * \note Set from the "callwaiting" value read in from chan_dahdi.conf
00858     */
00859    unsigned int permcallwaiting:1;
00860    /*!
00861     * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
00862     * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
00863     */
00864    unsigned int permhidecallerid:1;
00865    /*!
00866     * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
00867     * \note Set from the "priindication" value read in from chan_dahdi.conf
00868     */
00869    unsigned int priindication_oob:1;
00870    /*!
00871     * \brief TRUE if PRI B channels are always exclusively selected.
00872     * \note Set from the "priexclusive" value read in from chan_dahdi.conf
00873     */
00874    unsigned int priexclusive:1;
00875    /*!
00876     * \brief TRUE if we will pulse dial.
00877     * \note Set from the "pulsedial" value read in from chan_dahdi.conf
00878     */
00879    unsigned int pulse:1;
00880    /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
00881    unsigned int pulsedial:1;
00882    unsigned int restartpending:1;      /*!< flag to ensure counted only once for restart */
00883    /*!
00884     * \brief TRUE if caller ID is restricted.
00885     * \note Set but not used.  Should be deleted.  Redundant with permhidecallerid.
00886     * \note Set from the "restrictcid" value read in from chan_dahdi.conf
00887     */
00888    unsigned int restrictcid:1;
00889    /*!
00890     * \brief TRUE if three way calling is enabled
00891     * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
00892     */
00893    unsigned int threewaycalling:1;
00894    /*!
00895     * \brief TRUE if call transfer is enabled
00896     * \note For FXS ports (either direct analog or over T1/E1):
00897     *   Support flash-hook call transfer
00898     * \note For digital ports using ISDN PRI protocols:
00899     *   Support switch-side transfer (called 2BCT, RLT or other names)
00900     * \note Set from the "transfer" value read in from chan_dahdi.conf
00901     */
00902    unsigned int transfer:1;
00903    /*!
00904     * \brief TRUE if caller ID is used on this channel.
00905     * \note PRI and SS7 spans will save caller ID from the networking peer.
00906     * \note FXS ports will generate the caller ID spill.
00907     * \note FXO ports will listen for the caller ID spill.
00908     * \note Set from the "usecallerid" value read in from chan_dahdi.conf
00909     */
00910    unsigned int use_callerid:1;
00911    /*!
00912     * \brief TRUE if we will use the calling presentation setting
00913     * from the Asterisk channel for outgoing calls.
00914     * \note Only applies to PRI and SS7 channels.
00915     * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
00916     */
00917    unsigned int use_callingpres:1;
00918    /*!
00919     * \brief TRUE if distinctive rings are to be detected.
00920     * \note For FXO lines
00921     * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
00922     */
00923    unsigned int usedistinctiveringdetection:1;
00924    /*!
00925     * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
00926     * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
00927     */
00928    unsigned int dahditrcallerid:1;
00929    /*!
00930     * \brief TRUE if allowed to flash-transfer to busy channels.
00931     * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
00932     */
00933    unsigned int transfertobusy:1;
00934    /*!
00935     * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
00936     * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
00937     */
00938    unsigned int mwimonitor_neon:1;
00939    /*!
00940     * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
00941     * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
00942     */
00943    unsigned int mwimonitor_fsk:1;
00944    /*!
00945     * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
00946     * \note RPAS - Ring Pulse Alert Signal
00947     * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
00948     */
00949    unsigned int mwimonitor_rpas:1;
00950    /*! \brief TRUE if an MWI monitor thread is currently active */
00951    unsigned int mwimonitoractive:1;
00952    /*! \brief TRUE if a MWI message sending thread is active */
00953    unsigned int mwisendactive:1;
00954    /*!
00955     * \brief TRUE if channel is out of reset and ready
00956     * \note Set but not used.
00957     */
00958    unsigned int inservice:1;
00959    /*!
00960     * \brief TRUE if the channel is locally blocked.
00961     * \note Applies to SS7 and MFCR2 channels.
00962     */
00963    unsigned int locallyblocked:1;
00964    /*!
00965     * \brief TRUE if the channel is remotely blocked.
00966     * \note Applies to SS7 and MFCR2 channels.
00967     */
00968    unsigned int remotelyblocked:1;
00969    /*!
00970     * \brief TRUE if the channel alarms will be managed also as Span ones
00971     * \note Applies to all channels
00972     */
00973    unsigned int manages_span_alarms:1;
00974 
00975 #if defined(HAVE_PRI)
00976    struct sig_pri_span *pri;
00977    int logicalspan;
00978 #endif
00979    /*!
00980     * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
00981     * \note Set from the "usesmdi" value read in from chan_dahdi.conf
00982     */
00983    unsigned int use_smdi:1;
00984    struct mwisend_info mwisend_data;
00985    /*! \brief The SMDI interface to get SMDI messages from. */
00986    struct ast_smdi_interface *smdi_iface;
00987 
00988    /*! \brief Distinctive Ring data */
00989    struct dahdi_distRings drings;
00990 
00991    /*!
00992     * \brief The configured context for incoming calls.
00993     * \note The "context" string read in from chan_dahdi.conf
00994     */
00995    char context[AST_MAX_CONTEXT];
00996    /*!
00997     * \brief Saved context string.
00998     */
00999    char defcontext[AST_MAX_CONTEXT];
01000    /*! \brief Extension to use in the dialplan. */
01001    char exten[AST_MAX_EXTENSION];
01002    /*!
01003     * \brief Language configured for calls.
01004     * \note The "language" string read in from chan_dahdi.conf
01005     */
01006    char language[MAX_LANGUAGE];
01007    /*!
01008     * \brief The configured music-on-hold class to use for calls.
01009     * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
01010     */
01011    char mohinterpret[MAX_MUSICCLASS];
01012    /*!
01013     * \brief Suggested music-on-hold class for peer channel to use for calls.
01014     * \note The "mohsuggest" string read in from chan_dahdi.conf
01015     */
01016    char mohsuggest[MAX_MUSICCLASS];
01017    char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
01018 #if defined(HAVE_PRI) || defined(HAVE_SS7)
01019    /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
01020    char cid_ani[AST_MAX_EXTENSION];
01021 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
01022    /*! \brief Automatic Number Identification code from PRI */
01023    int cid_ani2;
01024    /*! \brief Caller ID number from an incoming call. */
01025    char cid_num[AST_MAX_EXTENSION];
01026    /*!
01027     * \brief Caller ID tag from incoming call
01028     * \note the "cid_tag" string read in from chan_dahdi.conf
01029     */
01030    char cid_tag[AST_MAX_EXTENSION];
01031    /*! \brief Caller ID Q.931 TON/NPI field values.  Set by PRI. Zero otherwise. */
01032    int cid_ton;
01033    /*! \brief Caller ID name from an incoming call. */
01034    char cid_name[AST_MAX_EXTENSION];
01035    /*! \brief Caller ID subaddress from an incoming call. */
01036    char cid_subaddr[AST_MAX_EXTENSION];
01037    char *origcid_num;            /*!< malloced original callerid */
01038    char *origcid_name;           /*!< malloced original callerid */
01039    /*! \brief Call waiting number. */
01040    char callwait_num[AST_MAX_EXTENSION];
01041    /*! \brief Call waiting name. */
01042    char callwait_name[AST_MAX_EXTENSION];
01043    /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
01044    char rdnis[AST_MAX_EXTENSION];
01045    /*! \brief Dialed Number Identifier */
01046    char dnid[AST_MAX_EXTENSION];
01047    /*!
01048     * \brief Bitmapped groups this belongs to.
01049     * \note The "group" bitmapped group string read in from chan_dahdi.conf
01050     */
01051    ast_group_t group;
01052    /*! \brief Default call PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW. */
01053    int law_default;
01054    /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
01055    int law;
01056    int confno;             /*!< Our conference */
01057    int confusers;             /*!< Who is using our conference */
01058    int propconfno;               /*!< Propagated conference number */
01059    /*!
01060     * \brief Bitmapped call groups this belongs to.
01061     * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
01062     */
01063    ast_group_t callgroup;
01064    /*!
01065     * \brief Bitmapped pickup groups this belongs to.
01066     * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
01067     */
01068    ast_group_t pickupgroup;
01069    /*!
01070     * \brief Channel variable list with associated values to set when a channel is created.
01071     * \note The "setvar" strings read in from chan_dahdi.conf
01072     */
01073    struct ast_variable *vars;
01074    int channel;               /*!< Channel Number */
01075    int span;               /*!< Span number */
01076    time_t guardtime;          /*!< Must wait this much time before using for new call */
01077    int cid_signalling;           /*!< CID signalling type bell202 or v23 */
01078    int cid_start;             /*!< CID start indicator, polarity or ring or DTMF without warning event */
01079    int dtmfcid_holdoff_state;    /*!< State indicator that allows for line to settle before checking for dtmf energy */
01080    struct timeval dtmfcid_delay;  /*!< Time value used for allow line to settle */
01081    int callingpres;           /*!< The value of calling presentation that we're going to use when placing a PRI call */
01082    int callwaitingrepeat;           /*!< How many samples to wait before repeating call waiting */
01083    int cidcwexpire;           /*!< When to stop waiting for CID/CW CAS response (In samples) */
01084    int cid_suppress_expire;      /*!< How many samples to suppress after a CID spill. */
01085    /*! \brief Analog caller ID waveform sample buffer */
01086    unsigned char *cidspill;
01087    /*! \brief Position in the cidspill buffer to send out next. */
01088    int cidpos;
01089    /*! \brief Length of the cidspill buffer containing samples. */
01090    int cidlen;
01091    /*! \brief Ring timeout timer?? */
01092    int ringt;
01093    /*!
01094     * \brief Ring timeout base.
01095     * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
01096     */
01097    int ringt_base;
01098    /*!
01099     * \brief Number of most significant digits/characters to strip from the dialed number.
01100     * \note Feature is deprecated.  Use dialplan logic.
01101     * \note The characters are stripped before the PRI TON/NPI prefix
01102     * characters are processed.
01103     */
01104    int stripmsd;
01105    /*!
01106     * \brief TRUE if Call Waiting (CW) CPE Alert Signal (CAS) is being sent.
01107     * \note
01108     * After CAS is sent, the call waiting caller id will be sent if the phone
01109     * gives a positive reply.
01110     */
01111    int callwaitcas;
01112    /*! \brief Number of call waiting rings. */
01113    int callwaitrings;
01114    /*! \brief Echo cancel parameters. */
01115    struct {
01116       struct dahdi_echocanparams head;
01117       struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
01118    } echocancel;
01119    /*!
01120     * \brief Echo training time. 0 = disabled
01121     * \note Set from the "echotraining" value read in from chan_dahdi.conf
01122     */
01123    int echotraining;
01124    /*! \brief Filled with 'w'.  XXX Purpose?? */
01125    char echorest[20];
01126    /*!
01127     * \brief Number of times to see "busy" tone before hanging up.
01128     * \note Set from the "busycount" value read in from chan_dahdi.conf
01129     */
01130    int busycount;
01131    /*!
01132     * \brief Length of "busy" tone on time.
01133     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01134     */
01135    int busy_tonelength;
01136    /*!
01137     * \brief Length of "busy" tone off time.
01138     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01139     */
01140    int busy_quietlength;
01141    /*!
01142     * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
01143     * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
01144     */
01145    int callprogress;
01146    /*!
01147     * \brief Number of milliseconds to wait for dialtone.
01148     * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
01149     */
01150    int waitfordialtone;
01151    struct timeval waitingfordt;        /*!< Time we started waiting for dialtone */
01152    struct timeval flashtime;        /*!< Last flash-hook time */
01153    /*! \brief Opaque DSP configuration structure. */
01154    struct ast_dsp *dsp;
01155    /*! \brief DAHDI dial operation command struct for ioctl() call. */
01156    struct dahdi_dialoperation dop;
01157    int whichwink;             /*!< SIG_FEATDMF_TA Which wink are we on? */
01158    /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
01159    char finaldial[64];
01160    char accountcode[AST_MAX_ACCOUNT_CODE];      /*!< Account code */
01161    int amaflags;              /*!< AMA Flags */
01162    struct tdd_state *tdd;           /*!< TDD flag */
01163    /*! \brief Accumulated call forwarding number. */
01164    char call_forward[AST_MAX_EXTENSION];
01165    /*!
01166     * \brief Voice mailbox location.
01167     * \note Set from the "mailbox" string read in from chan_dahdi.conf
01168     */
01169    char mailbox[AST_MAX_EXTENSION];
01170    /*! \brief Opaque event subscription parameters for message waiting indication support. */
01171    struct ast_event_sub *mwi_event_sub;
01172    /*! \brief Delayed dialing for E911.  Overlap digits for ISDN. */
01173    char dialdest[256];
01174 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01175    struct dahdi_vmwi_info mwisend_setting;            /*!< Which VMWI methods to use */
01176    unsigned int mwisend_fsk: 1;     /*! Variable for enabling FSK MWI handling in chan_dahdi */
01177    unsigned int mwisend_rpas:1;     /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
01178 #endif
01179    int distinctivering;          /*!< Which distinctivering to use */
01180    int dtmfrelax;             /*!< whether to run in relaxed DTMF mode */
01181    /*! \brief Holding place for event injected from outside normal operation. */
01182    int fake_event;
01183    /*!
01184     * \brief Minimal time period (ms) between the answer polarity
01185     * switch and hangup polarity switch.
01186     */
01187    int polarityonanswerdelay;
01188    /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
01189    struct timeval polaritydelaytv;
01190    /*!
01191     * \brief Send caller ID on FXS after this many rings. Set to 1 for US.
01192     * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
01193     */
01194    int sendcalleridafter;
01195    /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
01196    int polarity;
01197    /*! \brief DSP feature flags: DSP_FEATURE_xxx */
01198    int dsp_features;
01199 #if defined(HAVE_SS7)
01200    /*! \brief SS7 control parameters */
01201    struct sig_ss7_linkset *ss7;
01202 #endif   /* defined(HAVE_SS7) */
01203 #ifdef HAVE_OPENR2
01204    struct dahdi_mfcr2 *mfcr2;
01205    openr2_chan_t *r2chan;
01206    openr2_calling_party_category_t mfcr2_recvd_category;
01207    openr2_calling_party_category_t mfcr2_category;
01208    int mfcr2_dnis_index;
01209    int mfcr2_ani_index;
01210    int mfcr2call:1;
01211    int mfcr2_answer_pending:1;
01212    int mfcr2_charge_calls:1;
01213    int mfcr2_allow_collect_calls:1;
01214    int mfcr2_forced_release:1;
01215    int mfcr2_dnis_matched:1;
01216    int mfcr2_call_accepted:1;
01217    int mfcr2_progress:1;
01218    int mfcr2_accept_on_offer:1;
01219 #endif
01220    /*! \brief DTMF digit in progress.  0 when no digit in progress. */
01221    char begindigit;
01222    /*! \brief TRUE if confrence is muted. */
01223    int muting;
01224    void *sig_pvt;
01225    struct ast_cc_config_params *cc_params;
01226    /* DAHDI channel names may differ greatly from the
01227     * string that was provided to an app such as Dial. We
01228     * need to save the original string passed to dahdi_request
01229     * for call completion purposes. This way, we can replicate
01230     * the original dialed string later.
01231     */
01232    char dialstring[AST_CHANNEL_NAME];
01233 };
01234 
01235 #define DATA_EXPORT_DAHDI_PVT(MEMBER)              \
01236    MEMBER(dahdi_pvt, cid_rxgain, AST_DATA_DOUBLE)        \
01237    MEMBER(dahdi_pvt, rxgain, AST_DATA_DOUBLE)         \
01238    MEMBER(dahdi_pvt, txgain, AST_DATA_DOUBLE)         \
01239    MEMBER(dahdi_pvt, txdrc, AST_DATA_DOUBLE)       \
01240    MEMBER(dahdi_pvt, rxdrc, AST_DATA_DOUBLE)       \
01241    MEMBER(dahdi_pvt, adsi, AST_DATA_BOOLEAN)       \
01242    MEMBER(dahdi_pvt, answeronpolarityswitch, AST_DATA_BOOLEAN) \
01243    MEMBER(dahdi_pvt, busydetect, AST_DATA_BOOLEAN)       \
01244    MEMBER(dahdi_pvt, callreturn, AST_DATA_BOOLEAN)       \
01245    MEMBER(dahdi_pvt, callwaiting, AST_DATA_BOOLEAN)      \
01246    MEMBER(dahdi_pvt, callwaitingcallerid, AST_DATA_BOOLEAN) \
01247    MEMBER(dahdi_pvt, cancallforward, AST_DATA_BOOLEAN)      \
01248    MEMBER(dahdi_pvt, canpark, AST_DATA_BOOLEAN)       \
01249    MEMBER(dahdi_pvt, confirmanswer, AST_DATA_BOOLEAN)    \
01250    MEMBER(dahdi_pvt, destroy, AST_DATA_BOOLEAN)       \
01251    MEMBER(dahdi_pvt, didtdd, AST_DATA_BOOLEAN)        \
01252    MEMBER(dahdi_pvt, dialednone, AST_DATA_BOOLEAN)       \
01253    MEMBER(dahdi_pvt, dialing, AST_DATA_BOOLEAN)       \
01254    MEMBER(dahdi_pvt, digital, AST_DATA_BOOLEAN)       \
01255    MEMBER(dahdi_pvt, dnd, AST_DATA_BOOLEAN)        \
01256    MEMBER(dahdi_pvt, echobreak, AST_DATA_BOOLEAN)        \
01257    MEMBER(dahdi_pvt, echocanbridged, AST_DATA_BOOLEAN)      \
01258    MEMBER(dahdi_pvt, echocanon, AST_DATA_BOOLEAN)        \
01259    MEMBER(dahdi_pvt, faxhandled, AST_DATA_BOOLEAN)       \
01260    MEMBER(dahdi_pvt, usefaxbuffers, AST_DATA_BOOLEAN)    \
01261    MEMBER(dahdi_pvt, bufferoverrideinuse, AST_DATA_BOOLEAN) \
01262    MEMBER(dahdi_pvt, firstradio, AST_DATA_BOOLEAN)       \
01263    MEMBER(dahdi_pvt, hanguponpolarityswitch, AST_DATA_BOOLEAN) \
01264    MEMBER(dahdi_pvt, hardwaredtmf, AST_DATA_BOOLEAN)     \
01265    MEMBER(dahdi_pvt, hidecallerid, AST_DATA_BOOLEAN)     \
01266    MEMBER(dahdi_pvt, hidecalleridname, AST_DATA_BOOLEAN)    \
01267    MEMBER(dahdi_pvt, ignoredtmf, AST_DATA_BOOLEAN)       \
01268    MEMBER(dahdi_pvt, immediate, AST_DATA_BOOLEAN)        \
01269    MEMBER(dahdi_pvt, inalarm, AST_DATA_BOOLEAN)       \
01270    MEMBER(dahdi_pvt, mate, AST_DATA_BOOLEAN)       \
01271    MEMBER(dahdi_pvt, outgoing, AST_DATA_BOOLEAN)         \
01272    MEMBER(dahdi_pvt, permcallwaiting, AST_DATA_BOOLEAN)     \
01273    MEMBER(dahdi_pvt, priindication_oob, AST_DATA_BOOLEAN)      \
01274    MEMBER(dahdi_pvt, priexclusive, AST_DATA_BOOLEAN)     \
01275    MEMBER(dahdi_pvt, pulse, AST_DATA_BOOLEAN)         \
01276    MEMBER(dahdi_pvt, pulsedial, AST_DATA_BOOLEAN)        \
01277    MEMBER(dahdi_pvt, restartpending, AST_DATA_BOOLEAN)      \
01278    MEMBER(dahdi_pvt, restrictcid, AST_DATA_BOOLEAN)      \
01279    MEMBER(dahdi_pvt, threewaycalling, AST_DATA_BOOLEAN)     \
01280    MEMBER(dahdi_pvt, transfer, AST_DATA_BOOLEAN)         \
01281    MEMBER(dahdi_pvt, use_callerid, AST_DATA_BOOLEAN)     \
01282    MEMBER(dahdi_pvt, use_callingpres, AST_DATA_BOOLEAN)     \
01283    MEMBER(dahdi_pvt, usedistinctiveringdetection, AST_DATA_BOOLEAN)  \
01284    MEMBER(dahdi_pvt, dahditrcallerid, AST_DATA_BOOLEAN)        \
01285    MEMBER(dahdi_pvt, transfertobusy, AST_DATA_BOOLEAN)         \
01286    MEMBER(dahdi_pvt, mwimonitor_neon, AST_DATA_BOOLEAN)        \
01287    MEMBER(dahdi_pvt, mwimonitor_fsk, AST_DATA_BOOLEAN)         \
01288    MEMBER(dahdi_pvt, mwimonitor_rpas, AST_DATA_BOOLEAN)        \
01289    MEMBER(dahdi_pvt, mwimonitoractive, AST_DATA_BOOLEAN)       \
01290    MEMBER(dahdi_pvt, mwisendactive, AST_DATA_BOOLEAN)       \
01291    MEMBER(dahdi_pvt, inservice, AST_DATA_BOOLEAN)           \
01292    MEMBER(dahdi_pvt, locallyblocked, AST_DATA_BOOLEAN)         \
01293    MEMBER(dahdi_pvt, remotelyblocked, AST_DATA_BOOLEAN)        \
01294    MEMBER(dahdi_pvt, manages_span_alarms, AST_DATA_BOOLEAN)    \
01295    MEMBER(dahdi_pvt, use_smdi, AST_DATA_BOOLEAN)            \
01296    MEMBER(dahdi_pvt, context, AST_DATA_STRING)           \
01297    MEMBER(dahdi_pvt, defcontext, AST_DATA_STRING)           \
01298    MEMBER(dahdi_pvt, exten, AST_DATA_STRING)          \
01299    MEMBER(dahdi_pvt, language, AST_DATA_STRING)          \
01300    MEMBER(dahdi_pvt, mohinterpret, AST_DATA_STRING)         \
01301    MEMBER(dahdi_pvt, mohsuggest, AST_DATA_STRING)           \
01302    MEMBER(dahdi_pvt, parkinglot, AST_DATA_STRING)
01303 
01304 AST_DATA_STRUCTURE(dahdi_pvt, DATA_EXPORT_DAHDI_PVT);
01305 
01306 static struct dahdi_pvt *iflist = NULL;   /*!< Main interface list start */
01307 static struct dahdi_pvt *ifend = NULL; /*!< Main interface list end */
01308 
01309 #if defined(HAVE_PRI)
01310 static struct dahdi_parms_pseudo {
01311    int buf_no;             /*!< Number of buffers */
01312    int buf_policy;            /*!< Buffer policy */
01313    int faxbuf_no;              /*!< Number of Fax buffers */
01314    int faxbuf_policy;          /*!< Fax buffer policy */
01315 } dahdi_pseudo_parms;
01316 #endif   /* defined(HAVE_PRI) */
01317 
01318 /*! \brief Channel configuration from chan_dahdi.conf .
01319  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
01320  * Generally there is a field here for every possible configuration item.
01321  *
01322  * The state of fields is saved along the parsing and whenever a 'channel'
01323  * statement is reached, the current dahdi_chan_conf is used to configure the
01324  * channel (struct dahdi_pvt)
01325  *
01326  * \see dahdi_chan_init for the default values.
01327  */
01328 struct dahdi_chan_conf {
01329    struct dahdi_pvt chan;
01330 #ifdef HAVE_PRI
01331    struct dahdi_pri pri;
01332 #endif
01333 
01334 #if defined(HAVE_SS7)
01335    struct dahdi_ss7 ss7;
01336 #endif   /* defined(HAVE_SS7) */
01337 
01338 #ifdef HAVE_OPENR2
01339    struct dahdi_mfcr2_conf mfcr2;
01340 #endif
01341    struct dahdi_params timing;
01342    int is_sig_auto; /*!< Use channel signalling from DAHDI? */
01343    /*! Continue configuration even if a channel is not there. */
01344    int ignore_failed_channels;
01345 
01346    /*!
01347     * \brief The serial port to listen for SMDI data on
01348     * \note Set from the "smdiport" string read in from chan_dahdi.conf
01349     */
01350    char smdi_port[SMDI_MAX_FILENAME_LEN];
01351 };
01352 
01353 /*! returns a new dahdi_chan_conf with default values (by-value) */
01354 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
01355 {
01356    /* recall that if a field is not included here it is initialized
01357     * to 0 or equivalent
01358     */
01359    struct dahdi_chan_conf conf = {
01360 #ifdef HAVE_PRI
01361       .pri.pri = {
01362          .nsf = PRI_NSF_NONE,
01363          .switchtype = PRI_SWITCH_NI2,
01364          .dialplan = PRI_UNKNOWN + 1,
01365          .localdialplan = PRI_NATIONAL_ISDN + 1,
01366          .nodetype = PRI_CPE,
01367          .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
01368 
01369 #if defined(HAVE_PRI_CCSS)
01370          .cc_ptmp_recall_mode = 1,/* specificRecall */
01371          .cc_qsig_signaling_link_req = 1,/* retain */
01372          .cc_qsig_signaling_link_rsp = 1,/* retain */
01373 #endif   /* defined(HAVE_PRI_CCSS) */
01374 
01375          .minunused = 2,
01376          .idleext = "",
01377          .idledial = "",
01378          .internationalprefix = "",
01379          .nationalprefix = "",
01380          .localprefix = "",
01381          .privateprefix = "",
01382          .unknownprefix = "",
01383          .resetinterval = -1,
01384       },
01385 #endif
01386 #if defined(HAVE_SS7)
01387       .ss7.ss7 = {
01388          .called_nai = SS7_NAI_NATIONAL,
01389          .calling_nai = SS7_NAI_NATIONAL,
01390          .internationalprefix = "",
01391          .nationalprefix = "",
01392          .subscriberprefix = "",
01393          .unknownprefix = ""
01394       },
01395 #endif   /* defined(HAVE_SS7) */
01396 #ifdef HAVE_OPENR2
01397       .mfcr2 = {
01398          .variant = OR2_VAR_ITU,
01399          .mfback_timeout = -1,
01400          .metering_pulse_timeout = -1,
01401          .max_ani = 10,
01402          .max_dnis = 4,
01403          .get_ani_first = -1,
01404 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
01405          .skip_category_request = -1,
01406 #endif
01407          .call_files = 0,
01408          .allow_collect_calls = 0,
01409          .charge_calls = 1,
01410          .accept_on_offer = 1,
01411          .forced_release = 0,
01412          .double_answer = 0,
01413          .immediate_accept = -1,
01414          .logdir = "",
01415          .r2proto_file = "",
01416          .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
01417          .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
01418       },
01419 #endif
01420       .chan = {
01421          .context = "default",
01422          .cid_num = "",
01423          .cid_name = "",
01424          .cid_tag = "",
01425          .mohinterpret = "default",
01426          .mohsuggest = "",
01427          .parkinglot = "",
01428          .transfertobusy = 1,
01429 
01430          .cid_signalling = CID_SIG_BELL,
01431          .cid_start = CID_START_RING,
01432          .dahditrcallerid = 0,
01433          .use_callerid = 1,
01434          .sig = -1,
01435          .outsigmod = -1,
01436 
01437          .cid_rxgain = +5.0,
01438 
01439          .tonezone = -1,
01440 
01441          .echocancel.head.tap_length = 1,
01442 
01443          .busycount = 3,
01444 
01445          .accountcode = "",
01446 
01447          .mailbox = "",
01448 
01449 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01450          .mwisend_fsk = 1,
01451 #endif
01452          .polarityonanswerdelay = 600,
01453 
01454          .sendcalleridafter = DEFAULT_CIDRINGS,
01455 
01456          .buf_policy = DAHDI_POLICY_IMMEDIATE,
01457          .buf_no = numbufs,
01458          .usefaxbuffers = 0,
01459          .cc_params = ast_cc_config_params_init(),
01460       },
01461       .timing = {
01462          .prewinktime = -1,
01463          .preflashtime = -1,
01464          .winktime = -1,
01465          .flashtime = -1,
01466          .starttime = -1,
01467          .rxwinktime = -1,
01468          .rxflashtime = -1,
01469          .debouncetime = -1
01470       },
01471       .is_sig_auto = 1,
01472       .smdi_port = "/dev/ttyS0",
01473    };
01474 
01475    return conf;
01476 }
01477 
01478 
01479 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01480 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
01481 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
01482 static int dahdi_sendtext(struct ast_channel *c, const char *text);
01483 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
01484 static int dahdi_hangup(struct ast_channel *ast);
01485 static int dahdi_answer(struct ast_channel *ast);
01486 static struct ast_frame *dahdi_read(struct ast_channel *ast);
01487 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
01488 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
01489 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
01490 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01491 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01492 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01493 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
01494 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value);
01495 static int dahdi_devicestate(void *data);
01496 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback);
01497 
01498 static const struct ast_channel_tech dahdi_tech = {
01499    .type = "DAHDI",
01500    .description = tdesc,
01501    .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
01502    .requester = dahdi_request,
01503    .send_digit_begin = dahdi_digit_begin,
01504    .send_digit_end = dahdi_digit_end,
01505    .send_text = dahdi_sendtext,
01506    .call = dahdi_call,
01507    .hangup = dahdi_hangup,
01508    .answer = dahdi_answer,
01509    .read = dahdi_read,
01510    .write = dahdi_write,
01511    .bridge = dahdi_bridge,
01512    .exception = dahdi_exception,
01513    .indicate = dahdi_indicate,
01514    .fixup = dahdi_fixup,
01515    .setoption = dahdi_setoption,
01516    .queryoption = dahdi_queryoption,
01517    .func_channel_read = dahdi_func_read,
01518    .func_channel_write = dahdi_func_write,
01519    .devicestate = dahdi_devicestate,
01520    .cc_callback = dahdi_cc_callback,
01521 };
01522 
01523 #define GET_CHANNEL(p) ((p)->channel)
01524 
01525 #define SIG_PRI_LIB_HANDLE_CASES \
01526    SIG_PRI:                \
01527    case SIG_BRI:              \
01528    case SIG_BRI_PTMP
01529 
01530 /*!
01531  * \internal
01532  * \brief Determine if sig_pri handles the signaling.
01533  * \since 1.8
01534  *
01535  * \param signaling Signaling to determine if is for sig_pri.
01536  *
01537  * \return TRUE if the signaling is for sig_pri.
01538  */
01539 static inline int dahdi_sig_pri_lib_handles(int signaling)
01540 {
01541    int handles;
01542 
01543    switch (signaling) {
01544    case SIG_PRI_LIB_HANDLE_CASES:
01545       handles = 1;
01546       break;
01547    default:
01548       handles = 0;
01549       break;
01550    }
01551 
01552    return handles;
01553 }
01554 
01555 static int analog_lib_handles(int signalling, int radio, int oprmode)
01556 {
01557    switch (signalling) {
01558    case SIG_FXOLS:
01559    case SIG_FXOGS:
01560    case SIG_FXOKS:
01561    case SIG_FXSLS:
01562    case SIG_FXSGS:
01563    case SIG_FXSKS:
01564    case SIG_EMWINK:
01565    case SIG_EM:
01566    case SIG_EM_E1:
01567    case SIG_FEATD:
01568    case SIG_FEATDMF:
01569    case SIG_E911:
01570    case SIG_FGC_CAMA:
01571    case SIG_FGC_CAMAMF:
01572    case SIG_FEATB:
01573    case SIG_SFWINK:
01574    case SIG_SF:
01575    case SIG_SF_FEATD:
01576    case SIG_SF_FEATDMF:
01577    case SIG_FEATDMF_TA:
01578    case SIG_SF_FEATB:
01579       break;
01580    default:
01581       /* The rest of the function should cover the remainder of signalling types */
01582       return 0;
01583    }
01584 
01585    if (radio) {
01586       return 0;
01587    }
01588 
01589    if (oprmode) {
01590       return 0;
01591    }
01592 
01593    return 1;
01594 }
01595 
01596 static enum analog_sigtype dahdisig_to_analogsig(int sig)
01597 {
01598    switch (sig) {
01599    case SIG_FXOLS:
01600       return ANALOG_SIG_FXOLS;
01601    case SIG_FXOGS:
01602       return ANALOG_SIG_FXOGS;
01603    case SIG_FXOKS:
01604       return ANALOG_SIG_FXOKS;
01605    case SIG_FXSLS:
01606       return ANALOG_SIG_FXSLS;
01607    case SIG_FXSGS:
01608       return ANALOG_SIG_FXSGS;
01609    case SIG_FXSKS:
01610       return ANALOG_SIG_FXSKS;
01611    case SIG_EMWINK:
01612       return ANALOG_SIG_EMWINK;
01613    case SIG_EM:
01614       return ANALOG_SIG_EM;
01615    case SIG_EM_E1:
01616       return ANALOG_SIG_EM_E1;
01617    case SIG_FEATD:
01618       return ANALOG_SIG_FEATD;
01619    case SIG_FEATDMF:
01620       return ANALOG_SIG_FEATDMF;
01621    case SIG_E911:
01622       return SIG_E911;
01623    case SIG_FGC_CAMA:
01624       return ANALOG_SIG_FGC_CAMA;
01625    case SIG_FGC_CAMAMF:
01626       return ANALOG_SIG_FGC_CAMAMF;
01627    case SIG_FEATB:
01628       return ANALOG_SIG_FEATB;
01629    case SIG_SFWINK:
01630       return ANALOG_SIG_SFWINK;
01631    case SIG_SF:
01632       return ANALOG_SIG_SF;
01633    case SIG_SF_FEATD:
01634       return ANALOG_SIG_SF_FEATD;
01635    case SIG_SF_FEATDMF:
01636       return ANALOG_SIG_SF_FEATDMF;
01637    case SIG_FEATDMF_TA:
01638       return ANALOG_SIG_FEATDMF_TA;
01639    case SIG_SF_FEATB:
01640       return ANALOG_SIG_FEATB;
01641    default:
01642       return -1;
01643    }
01644 }
01645 
01646 
01647 static int analog_tone_to_dahditone(enum analog_tone tone)
01648 {
01649    switch (tone) {
01650    case ANALOG_TONE_RINGTONE:
01651       return DAHDI_TONE_RINGTONE;
01652    case ANALOG_TONE_STUTTER:
01653       return DAHDI_TONE_STUTTER;
01654    case ANALOG_TONE_CONGESTION:
01655       return DAHDI_TONE_CONGESTION;
01656    case ANALOG_TONE_DIALTONE:
01657       return DAHDI_TONE_DIALTONE;
01658    case ANALOG_TONE_DIALRECALL:
01659       return DAHDI_TONE_DIALRECALL;
01660    case ANALOG_TONE_INFO:
01661       return DAHDI_TONE_INFO;
01662    default:
01663       return -1;
01664    }
01665 }
01666 
01667 static int analogsub_to_dahdisub(enum analog_sub analogsub)
01668 {
01669    int index;
01670 
01671    switch (analogsub) {
01672    case ANALOG_SUB_REAL:
01673       index = SUB_REAL;
01674       break;
01675    case ANALOG_SUB_CALLWAIT:
01676       index = SUB_CALLWAIT;
01677       break;
01678    case ANALOG_SUB_THREEWAY:
01679       index = SUB_THREEWAY;
01680       break;
01681    default:
01682       ast_log(LOG_ERROR, "Unidentified sub!\n");
01683       index = SUB_REAL;
01684    }
01685 
01686    return index;
01687 }
01688 
01689 static enum analog_event dahdievent_to_analogevent(int event);
01690 static int bump_gains(struct dahdi_pvt *p);
01691 static int dahdi_setlinear(int dfd, int linear);
01692 
01693 static int my_start_cid_detect(void *pvt, int cid_signalling)
01694 {
01695    struct dahdi_pvt *p = pvt;
01696    int index = SUB_REAL;
01697    p->cs = callerid_new(cid_signalling);
01698    if (!p->cs) {
01699       ast_log(LOG_ERROR, "Unable to alloc callerid\n");
01700       return -1;
01701    }
01702    bump_gains(p);
01703    dahdi_setlinear(p->subs[index].dfd, 0);
01704 
01705    return 0;
01706 }
01707 
01708 static int my_stop_cid_detect(void *pvt)
01709 {
01710    struct dahdi_pvt *p = pvt;
01711    int index = SUB_REAL;
01712    if (p->cs)
01713       callerid_free(p->cs);
01714    dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
01715    return 0;
01716 }
01717 
01718 static int my_get_callerid(void *pvt, char *namebuf, char *numbuf, enum analog_event *ev, size_t timeout)
01719 {
01720    struct dahdi_pvt *p = pvt;
01721    struct analog_pvt *analog_p = p->sig_pvt;
01722    struct pollfd poller;
01723    char *name, *num;
01724    int index = SUB_REAL;
01725    int res;
01726    unsigned char buf[256];
01727    int flags;
01728 
01729    poller.fd = p->subs[SUB_REAL].dfd;
01730    poller.events = POLLPRI | POLLIN;
01731    poller.revents = 0;
01732 
01733    res = poll(&poller, 1, timeout);
01734 
01735    if (poller.revents & POLLPRI) {
01736       *ev = dahdievent_to_analogevent(dahdi_get_event(p->subs[SUB_REAL].dfd));
01737       return 1;
01738    }
01739 
01740    if (poller.revents & POLLIN) {
01741       /*** NOTES ***/
01742       /* Change API: remove cid_signalling from get_callerid, add a new start_cid_detect and stop_cid_detect function
01743        * to enable slin mode and allocate cid detector. get_callerid should be able to be called any number of times until
01744        * either a timeout occurs or CID is detected (returns 0). returning 1 should be event received, and -1 should be
01745        * a failure and die, and returning 2 means no event was received. */
01746       res = read(p->subs[index].dfd, buf, sizeof(buf));
01747       if (res < 0) {
01748          if (errno != ELAST) {
01749             ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
01750             callerid_free(p->cs);
01751             return -1;
01752          }
01753       }
01754 
01755       if (analog_p->ringt > 0) {
01756          if (!(--analog_p->ringt)) {
01757             /* only return if we timeout from a ring event */
01758             return -1;
01759          }
01760       }
01761 
01762       if (p->cid_signalling == CID_SIG_V23_JP) {
01763          res = callerid_feed_jp(p->cs, buf, res, AST_LAW(p));
01764       } else {
01765          res = callerid_feed(p->cs, buf, res, AST_LAW(p));
01766       }
01767       if (res < 0) {
01768          /*
01769           * The previous diagnostic message output likely
01770           * explains why it failed.
01771           */
01772          ast_log(LOG_WARNING, "Failed to decode CallerID\n");
01773          return -1;
01774       }
01775 
01776       if (res == 1) {
01777          callerid_get(p->cs, &name, &num, &flags);
01778          if (name)
01779             ast_copy_string(namebuf, name, ANALOG_MAX_CID);
01780          if (num)
01781             ast_copy_string(numbuf, num, ANALOG_MAX_CID);
01782 
01783          ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", num, name, flags);
01784          return 0;
01785       }
01786    }
01787 
01788    *ev = ANALOG_EVENT_NONE;
01789    return 2;
01790 }
01791 
01792 static const char *event2str(int event);
01793 static int restore_gains(struct dahdi_pvt *p);
01794 
01795 static int my_distinctive_ring(struct ast_channel *chan, void *pvt, int idx, int *ringdata)
01796 {
01797    unsigned char buf[256];
01798    int distMatches;
01799    int curRingData[RING_PATTERNS];
01800    int receivedRingT;
01801    int counter1;
01802    int counter;
01803    int i;
01804    int res;
01805    int checkaftercid = 0;
01806 
01807    struct dahdi_pvt *p = pvt;
01808    struct analog_pvt *analog_p = p->sig_pvt;
01809 
01810    if (ringdata == NULL) {
01811       ringdata = curRingData;
01812    } else {
01813       checkaftercid = 1;
01814    }
01815 
01816    /* We must have a ring by now, so, if configured, lets try to listen for
01817     * distinctive ringing */
01818    if ((checkaftercid && distinctiveringaftercid) || !checkaftercid) {
01819       /* Clear the current ring data array so we don't have old data in it. */
01820       for (receivedRingT = 0; receivedRingT < RING_PATTERNS; receivedRingT++)
01821          ringdata[receivedRingT] = 0;
01822       receivedRingT = 0;
01823       if (checkaftercid && distinctiveringaftercid)
01824          ast_verb(3, "Detecting post-CID distinctive ring\n");
01825       /* Check to see if context is what it should be, if not set to be. */
01826       else if (strcmp(p->context,p->defcontext) != 0) {
01827          ast_copy_string(p->context, p->defcontext, sizeof(p->context));
01828          ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
01829       }
01830 
01831       for (;;) {
01832          i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
01833          if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
01834             ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
01835             ast_hangup(chan);
01836             return 1;
01837          }
01838          if (i & DAHDI_IOMUX_SIGEVENT) {
01839             res = dahdi_get_event(p->subs[idx].dfd);
01840             if (res == DAHDI_EVENT_NOALARM) {
01841                p->inalarm = 0;
01842                analog_p->inalarm = 0;
01843             }
01844             ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
01845             res = 0;
01846             /* Let us detect distinctive ring */
01847 
01848             ringdata[receivedRingT] = analog_p->ringt;
01849 
01850             if (analog_p->ringt < analog_p->ringt_base/2)
01851                break;
01852             /* Increment the ringT counter so we can match it against
01853                values in chan_dahdi.conf for distinctive ring */
01854             if (++receivedRingT == RING_PATTERNS)
01855                break;
01856          } else if (i & DAHDI_IOMUX_READ) {
01857             res = read(p->subs[idx].dfd, buf, sizeof(buf));
01858             if (res < 0) {
01859                if (errno != ELAST) {
01860                   ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
01861                   ast_hangup(chan);
01862                   return 1;
01863                }
01864                break;
01865             }
01866             if (analog_p->ringt > 0) {
01867                if (!(--analog_p->ringt)) {
01868                   res = -1;
01869                   break;
01870                }
01871             }
01872          }
01873       }
01874    }
01875    if ((checkaftercid && usedistinctiveringdetection) || !checkaftercid) {
01876       /* this only shows up if you have n of the dring patterns filled in */
01877       ast_verb(3, "Detected ring pattern: %d,%d,%d\n",ringdata[0],ringdata[1],ringdata[2]);
01878       for (counter = 0; counter < 3; counter++) {
01879       /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this channel */
01880          distMatches = 0;
01881          /* this only shows up if you have n of the dring patterns filled in */
01882          ast_verb(3, "Checking %d,%d,%d\n",
01883                p->drings.ringnum[counter].ring[0],
01884                p->drings.ringnum[counter].ring[1],
01885                p->drings.ringnum[counter].ring[2]);
01886          for (counter1 = 0; counter1 < 3; counter1++) {
01887             ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
01888             if (p->drings.ringnum[counter].ring[counter1] == -1) {
01889                ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
01890                ringdata[counter1]);
01891                distMatches++;
01892             } else if (ringdata[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
01893                               ringdata[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
01894                ast_verb(3, "Ring pattern matched in range: %d to %d\n",
01895                (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
01896                (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
01897                distMatches++;
01898             }
01899          }
01900 
01901          if (distMatches == 3) {
01902             /* The ring matches, set the context to whatever is for distinctive ring.. */
01903             ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
01904             ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
01905             ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
01906             break;
01907          }
01908       }
01909    }
01910    /* Restore linear mode (if appropriate) for Caller*ID processing */
01911    dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
01912    restore_gains(p);
01913 
01914    return 0;
01915 }
01916 
01917 static int my_stop_callwait(void *pvt)
01918 {
01919    struct dahdi_pvt *p = pvt;
01920    p->callwaitingrepeat = 0;
01921    p->cidcwexpire = 0;
01922    p->cid_suppress_expire = 0;
01923 
01924    return 0;
01925 }
01926 
01927 static int send_callerid(struct dahdi_pvt *p);
01928 static int save_conference(struct dahdi_pvt *p);
01929 static int restore_conference(struct dahdi_pvt *p);
01930 
01931 static int my_callwait(void *pvt)
01932 {
01933    struct dahdi_pvt *p = pvt;
01934    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
01935    if (p->cidspill) {
01936       ast_log(LOG_WARNING, "Spill already exists?!?\n");
01937       ast_free(p->cidspill);
01938    }
01939 
01940    /*
01941     * SAS: Subscriber Alert Signal, 440Hz for 300ms
01942     * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
01943     */
01944    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
01945       return -1;
01946    save_conference(p);
01947    /* Silence */
01948    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
01949    if (!p->callwaitrings && p->callwaitingcallerid) {
01950       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
01951       p->callwaitcas = 1;
01952       p->cidlen = 2400 + 680 + READ_SIZE * 4;
01953    } else {
01954       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
01955       p->callwaitcas = 0;
01956       p->cidlen = 2400 + READ_SIZE * 4;
01957    }
01958    p->cidpos = 0;
01959    send_callerid(p);
01960 
01961    return 0;
01962 }
01963 
01964 static int my_send_callerid(void *pvt, int cwcid, struct ast_party_caller *caller)
01965 {
01966    struct dahdi_pvt *p = pvt;
01967 
01968    ast_debug(2, "Starting cid spill\n");
01969 
01970    if (p->cidspill) {
01971       ast_log(LOG_WARNING, "cidspill already exists??\n");
01972       ast_free(p->cidspill);
01973    }
01974 
01975    if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
01976       if (cwcid == 0) {
01977          p->cidlen = ast_callerid_generate(p->cidspill,
01978             caller->id.name.str,
01979             caller->id.number.str,
01980             AST_LAW(p));
01981       } else {
01982          ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n",
01983             caller->id.name.str, caller->id.number.str);
01984          p->callwaitcas = 0;
01985          p->cidcwexpire = 0;
01986          p->cidlen = ast_callerid_callwaiting_generate(p->cidspill,
01987             caller->id.name.str,
01988             caller->id.number.str,
01989             AST_LAW(p));
01990          p->cidlen += READ_SIZE * 4;
01991       }
01992       p->cidpos = 0;
01993       p->cid_suppress_expire = 0;
01994       send_callerid(p);
01995    }
01996    return 0;
01997 }
01998 
01999 static int my_dsp_reset_and_flush_digits(void *pvt)
02000 {
02001    struct dahdi_pvt *p = pvt;
02002    if (p->dsp)
02003       ast_dsp_digitreset(p->dsp);
02004 
02005    return 0;
02006 }
02007 
02008 static int my_dsp_set_digitmode(void *pvt, enum analog_dsp_digitmode mode)
02009 {
02010    struct dahdi_pvt *p = pvt;
02011 
02012    if (p->channel == CHAN_PSEUDO)
02013       ast_log(LOG_ERROR, "You have assumed incorrectly sir!\n");
02014 
02015    if (mode == ANALOG_DIGITMODE_DTMF) {
02016       /* If we do hardware dtmf, no need for a DSP */
02017       if (p->hardwaredtmf) {
02018          if (p->dsp) {
02019             ast_dsp_free(p->dsp);
02020             p->dsp = NULL;
02021          }
02022          return 0;
02023       }
02024 
02025       if (!p->dsp) {
02026          p->dsp = ast_dsp_new();
02027          if (!p->dsp) {
02028             ast_log(LOG_ERROR, "Unable to allocate DSP\n");
02029             return -1;
02030          }
02031       }
02032 
02033       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
02034    } else if (mode == ANALOG_DIGITMODE_MF) {
02035       if (!p->dsp) {
02036          p->dsp = ast_dsp_new();
02037          if (!p->dsp) {
02038             ast_log(LOG_ERROR, "Unable to allocate DSP\n");
02039             return -1;
02040          }
02041       }
02042       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
02043    }
02044    return 0;
02045 }
02046 
02047 static int dahdi_wink(struct dahdi_pvt *p, int index);
02048 
02049 static int my_wink(void *pvt, enum analog_sub sub)
02050 {
02051    struct dahdi_pvt *p = pvt;
02052    int index = analogsub_to_dahdisub(sub);
02053    if (index != SUB_REAL) {
02054       ast_log(LOG_ERROR, "We used a sub other than SUB_REAL (incorrect assumption sir)\n");
02055    }
02056    return dahdi_wink(p, index);
02057 }
02058 
02059 static void wakeup_sub(struct dahdi_pvt *p, int a);
02060 
02061 static int reset_conf(struct dahdi_pvt *p);
02062 
02063 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted);
02064 
02065 static void my_handle_dtmf(void *pvt, struct ast_channel *ast, enum analog_sub analog_index, struct ast_frame **dest)
02066 {
02067    struct ast_frame *f = *dest;
02068    struct dahdi_pvt *p = pvt;
02069    int idx = analogsub_to_dahdisub(analog_index);
02070 
02071    ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
02072       f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
02073       f->subclass.integer, f->subclass.integer, ast->name);
02074 
02075    if (f->subclass.integer == 'f') {
02076       if (f->frametype == AST_FRAME_DTMF_END) {
02077          /* Fax tone -- Handle and return NULL */
02078          if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
02079             /* If faxbuffers are configured, use them for the fax transmission */
02080             if (p->usefaxbuffers && !p->bufferoverrideinuse) {
02081                struct dahdi_bufferinfo bi = {
02082                   .txbufpolicy = p->faxbuf_policy,
02083                   .bufsize = p->bufsize,
02084                   .numbufs = p->faxbuf_no
02085                };
02086                int res;
02087 
02088                if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
02089                   ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
02090                } else {
02091                   p->bufferoverrideinuse = 1;
02092                }
02093             }
02094             p->faxhandled = 1;
02095             if (p->dsp) {
02096                p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
02097                ast_dsp_set_features(p->dsp, p->dsp_features);
02098                ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
02099             }
02100             if (strcmp(ast->exten, "fax")) {
02101                const char *target_context = S_OR(ast->macrocontext, ast->context);
02102 
02103                /* We need to unlock 'ast' here because ast_exists_extension has the
02104                 * potential to start autoservice on the channel. Such action is prone
02105                 * to deadlock.
02106                 */
02107                ast_mutex_unlock(&p->lock);
02108                ast_channel_unlock(ast);
02109                if (ast_exists_extension(ast, target_context, "fax", 1,
02110                   S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
02111                   ast_channel_lock(ast);
02112                   ast_mutex_lock(&p->lock);
02113                   ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
02114                   /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
02115                   pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
02116                   if (ast_async_goto(ast, target_context, "fax", 1))
02117                      ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
02118                } else {
02119                   ast_channel_lock(ast);
02120                   ast_mutex_lock(&p->lock);
02121                   ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
02122                }
02123             } else {
02124                ast_debug(1, "Already in a fax extension, not redirecting\n");
02125             }
02126          } else {
02127             ast_debug(1, "Fax already handled\n");
02128          }
02129          dahdi_confmute(p, 0);
02130       }
02131       p->subs[idx].f.frametype = AST_FRAME_NULL;
02132       p->subs[idx].f.subclass.integer = 0;
02133       *dest = &p->subs[idx].f;
02134    }
02135 }
02136 
02137 static void my_lock_private(void *pvt)
02138 {
02139    struct dahdi_pvt *p = pvt;
02140    ast_mutex_lock(&p->lock);
02141 }
02142 
02143 static void my_unlock_private(void *pvt)
02144 {
02145    struct dahdi_pvt *p = pvt;
02146    ast_mutex_unlock(&p->lock);
02147 }
02148 
02149 static void my_deadlock_avoidance_private(void *pvt)
02150 {
02151    struct dahdi_pvt *p = pvt;
02152 
02153    DEADLOCK_AVOIDANCE(&p->lock);
02154 }
02155 
02156 /*!
02157  * \internal
02158  * \brief Post an AMI DAHDI channel association event.
02159  * \since 1.8
02160  *
02161  * \param p DAHDI private pointer
02162  * \param chan Channel associated with the private pointer
02163  *
02164  * \return Nothing
02165  */
02166 static void dahdi_ami_channel_event(struct dahdi_pvt *p, struct ast_channel *chan)
02167 {
02168    char ch_name[20];
02169 
02170    if (p->channel < CHAN_PSEUDO) {
02171       /* No B channel */
02172       snprintf(ch_name, sizeof(ch_name), "no-media (%d)", p->channel);
02173    } else if (p->channel == CHAN_PSEUDO) {
02174       /* Pseudo channel */
02175       strcpy(ch_name, "pseudo");
02176    } else {
02177       /* Real channel */
02178       snprintf(ch_name, sizeof(ch_name), "%d", p->channel);
02179    }
02180    ast_manager_event(chan, EVENT_FLAG_CALL, "DAHDIChannel",
02181       "Channel: %s\r\n"
02182       "Uniqueid: %s\r\n"
02183       "DAHDISpan: %d\r\n"
02184       "DAHDIChannel: %s\r\n",
02185       chan->name,
02186       chan->uniqueid,
02187       p->span,
02188       ch_name);
02189 }
02190 
02191 #ifdef HAVE_PRI
02192 /*!
02193  * \internal
02194  * \brief Post an AMI DAHDI channel association event.
02195  * \since 1.8
02196  *
02197  * \param pvt DAHDI private pointer
02198  * \param chan Channel associated with the private pointer
02199  *
02200  * \return Nothing
02201  */
02202 static void my_ami_channel_event(void *pvt, struct ast_channel *chan)
02203 {
02204    struct dahdi_pvt *p = pvt;
02205 
02206    dahdi_ami_channel_event(p, chan);
02207 }
02208 #endif
02209 
02210 /* linear_mode = 0 - turn linear mode off, >0 - turn linear mode on
02211 *  returns the last value of the linear setting 
02212 */ 
02213 static int my_set_linear_mode(void *pvt, enum analog_sub sub, int linear_mode)
02214 {
02215    struct dahdi_pvt *p = pvt;
02216    int oldval;
02217    int idx = analogsub_to_dahdisub(sub);
02218    
02219    dahdi_setlinear(p->subs[idx].dfd, linear_mode);
02220    oldval = p->subs[idx].linear;
02221    p->subs[idx].linear = linear_mode ? 1 : 0;
02222    return oldval;
02223 }
02224 
02225 static void my_set_inthreeway(void *pvt, enum analog_sub sub, int inthreeway)
02226 {
02227    struct dahdi_pvt *p = pvt;
02228    int idx = analogsub_to_dahdisub(sub);
02229 
02230    p->subs[idx].inthreeway = inthreeway;
02231 }
02232 
02233 static int get_alarms(struct dahdi_pvt *p);
02234 static void handle_alarms(struct dahdi_pvt *p, int alms);
02235 static void my_get_and_handle_alarms(void *pvt)
02236 {
02237    int res;
02238    struct dahdi_pvt *p = pvt;
02239 
02240    res = get_alarms(p);
02241    handle_alarms(p, res);
02242 }
02243 
02244 static void *my_get_sigpvt_bridged_channel(struct ast_channel *chan)
02245 {
02246    struct ast_channel *bridged = ast_bridged_channel(chan);
02247 
02248    if (bridged && bridged->tech == &dahdi_tech) {
02249       struct dahdi_pvt *p = bridged->tech_pvt;
02250 
02251       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
02252          return p->sig_pvt;
02253       }
02254    }
02255    return NULL;
02256 }
02257 
02258 static int my_get_sub_fd(void *pvt, enum analog_sub sub)
02259 {
02260    struct dahdi_pvt *p = pvt;
02261    int dahdi_sub = analogsub_to_dahdisub(sub);
02262    return p->subs[dahdi_sub].dfd;
02263 }
02264 
02265 static void my_set_cadence(void *pvt, int *cid_rings, struct ast_channel *ast)
02266 {
02267    struct dahdi_pvt *p = pvt;
02268 
02269    /* Choose proper cadence */
02270    if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
02271       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
02272          ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast->name, strerror(errno));
02273       *cid_rings = cidrings[p->distinctivering - 1];
02274    } else {
02275       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
02276          ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast->name, strerror(errno));
02277       *cid_rings = p->sendcalleridafter;
02278    }
02279 }
02280 
02281 static void my_set_alarm(void *pvt, int in_alarm)
02282 {
02283    struct dahdi_pvt *p = pvt;
02284 
02285    p->inalarm = in_alarm;
02286 }
02287 
02288 static void my_set_dialing(void *pvt, int is_dialing)
02289 {
02290    struct dahdi_pvt *p = pvt;
02291 
02292    p->dialing = is_dialing;
02293 }
02294 
02295 static void my_set_outgoing(void *pvt, int is_outgoing)
02296 {
02297    struct dahdi_pvt *p = pvt;
02298 
02299    p->outgoing = is_outgoing;
02300 }
02301 
02302 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02303 static void my_set_digital(void *pvt, int is_digital)
02304 {
02305    struct dahdi_pvt *p = pvt;
02306 
02307    p->digital = is_digital;
02308 }
02309 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02310 
02311 #if defined(HAVE_SS7)
02312 static void my_set_inservice(void *pvt, int is_inservice)
02313 {
02314    struct dahdi_pvt *p = pvt;
02315 
02316    p->inservice = is_inservice;
02317 }
02318 #endif   /* defined(HAVE_SS7) */
02319 
02320 #if defined(HAVE_SS7)
02321 static void my_set_locallyblocked(void *pvt, int is_blocked)
02322 {
02323    struct dahdi_pvt *p = pvt;
02324 
02325    p->locallyblocked = is_blocked;
02326 }
02327 #endif   /* defined(HAVE_SS7) */
02328 
02329 #if defined(HAVE_SS7)
02330 static void my_set_remotelyblocked(void *pvt, int is_blocked)
02331 {
02332    struct dahdi_pvt *p = pvt;
02333 
02334    p->remotelyblocked = is_blocked;
02335 }
02336 #endif   /* defined(HAVE_SS7) */
02337 
02338 static void my_set_ringtimeout(void *pvt, int ringt)
02339 {
02340    struct dahdi_pvt *p = pvt;
02341    p->ringt = ringt;
02342 }
02343 
02344 static void my_set_waitingfordt(void *pvt, struct ast_channel *ast)
02345 {
02346    struct dahdi_pvt *p = pvt;
02347 
02348    if (p->waitfordialtone && CANPROGRESSDETECT(p) && p->dsp) {
02349       ast_log(LOG_DEBUG, "Defer dialing for %dms or dialtone\n", p->waitfordialtone);
02350       gettimeofday(&p->waitingfordt, NULL);
02351       ast_setstate(ast, AST_STATE_OFFHOOK);
02352    }
02353 }
02354 
02355 static int my_check_waitingfordt(void *pvt)
02356 {
02357    struct dahdi_pvt *p = pvt;
02358 
02359    if (p->waitingfordt.tv_usec) {
02360       return 1;
02361    }
02362 
02363    return 0;
02364 }
02365 
02366 static void my_set_confirmanswer(void *pvt, int flag)
02367 {
02368    struct dahdi_pvt *p = pvt;
02369    p->confirmanswer = flag;
02370 }
02371 
02372 static int my_check_confirmanswer(void *pvt)
02373 {
02374    struct dahdi_pvt *p = pvt;
02375    if (p->confirmanswer) {
02376       return 1;
02377    }
02378 
02379    return 0;
02380 }
02381 
02382 static void my_set_callwaiting(void *pvt, int callwaiting_enable)
02383 {
02384    struct dahdi_pvt *p = pvt;
02385 
02386    p->callwaiting = callwaiting_enable;
02387 }
02388 
02389 static void my_cancel_cidspill(void *pvt)
02390 {
02391    struct dahdi_pvt *p = pvt;
02392 
02393    ast_free(p->cidspill);
02394    p->cidspill = NULL;
02395    restore_conference(p);
02396 }
02397 
02398 static int my_confmute(void *pvt, int mute)
02399 {
02400    struct dahdi_pvt *p = pvt;
02401    return dahdi_confmute(p, mute);
02402 }
02403 
02404 static void my_set_pulsedial(void *pvt, int flag)
02405 {
02406    struct dahdi_pvt *p = pvt;
02407    p->pulsedial = flag;
02408 }
02409 
02410 static void my_set_new_owner(void *pvt, struct ast_channel *new_owner)
02411 {
02412    struct dahdi_pvt *p = pvt;
02413 
02414    p->owner = new_owner;
02415 }
02416 
02417 static const char *my_get_orig_dialstring(void *pvt)
02418 {
02419    struct dahdi_pvt *p = pvt;
02420 
02421    return p->dialstring;
02422 }
02423 
02424 static void my_increase_ss_count(void)
02425 {
02426    ast_mutex_lock(&ss_thread_lock);
02427    ss_thread_count++;
02428    ast_mutex_unlock(&ss_thread_lock);
02429 }
02430 
02431 static void my_decrease_ss_count(void)
02432 {
02433    ast_mutex_lock(&ss_thread_lock);
02434    ss_thread_count--;
02435    ast_cond_signal(&ss_thread_complete);
02436    ast_mutex_unlock(&ss_thread_lock);
02437 }
02438 
02439 static void my_all_subchannels_hungup(void *pvt)
02440 {
02441    struct dahdi_pvt *p = pvt;
02442    int res, law;
02443 
02444    p->faxhandled = 0;
02445    p->didtdd = 0;
02446 
02447    if (p->dsp) {
02448       ast_dsp_free(p->dsp);
02449       p->dsp = NULL;
02450    }
02451 
02452    p->law = p->law_default;
02453    law = p->law_default;
02454    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
02455    if (res < 0)
02456       ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
02457 
02458    dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
02459 
02460 #if 1
02461    {
02462    int i;
02463    p->owner = NULL;
02464    /* Cleanup owners here */
02465    for (i = 0; i < 3; i++) {
02466       p->subs[i].owner = NULL;
02467    }
02468    }
02469 #endif
02470 
02471    reset_conf(p);
02472    if (num_restart_pending == 0) {
02473       restart_monitor();
02474    }
02475 }
02476 
02477 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index);
02478 
02479 static int my_conf_del(void *pvt, enum analog_sub sub)
02480 {
02481    struct dahdi_pvt *p = pvt;
02482    int x = analogsub_to_dahdisub(sub);
02483 
02484    return conf_del(p, &p->subs[x], x);
02485 }
02486 
02487 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index, int slavechannel);
02488 
02489 static int my_conf_add(void *pvt, enum analog_sub sub)
02490 {
02491    struct dahdi_pvt *p = pvt;
02492    int x = analogsub_to_dahdisub(sub);
02493 
02494    return conf_add(p, &p->subs[x], x, 0);
02495 }
02496 
02497 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out);
02498 
02499 static int my_complete_conference_update(void *pvt, int needconference)
02500 {
02501    struct dahdi_pvt *p = pvt;
02502    int needconf = needconference;
02503    int x;
02504    int useslavenative;
02505    struct dahdi_pvt *slave = NULL;
02506 
02507    useslavenative = isslavenative(p, &slave);
02508 
02509    /* If we have a slave, add him to our conference now. or DAX
02510       if this is slave native */
02511    for (x = 0; x < MAX_SLAVES; x++) {
02512       if (p->slaves[x]) {
02513          if (useslavenative)
02514             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
02515          else {
02516             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
02517             needconf++;
02518          }
02519       }
02520    }
02521    /* If we're supposed to be in there, do so now */
02522    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
02523       if (useslavenative)
02524          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
02525       else {
02526          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
02527          needconf++;
02528       }
02529    }
02530    /* If we have a master, add ourselves to his conference */
02531    if (p->master) {
02532       if (isslavenative(p->master, NULL)) {
02533          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
02534       } else {
02535          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
02536       }
02537    }
02538    if (!needconf) {
02539       /* Nobody is left (or should be left) in our conference.
02540          Kill it. */
02541       p->confno = -1;
02542    }
02543 
02544    return 0;
02545 }
02546 
02547 static int check_for_conference(struct dahdi_pvt *p);
02548 
02549 static int my_check_for_conference(void *pvt)
02550 {
02551    struct dahdi_pvt *p = pvt;
02552    return check_for_conference(p);
02553 }
02554 
02555 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)
02556 {
02557    struct dahdi_pvt *p = pvt;
02558    int da, db;
02559    int tchan;
02560    int tinthreeway;
02561 
02562    da = analogsub_to_dahdisub(a);
02563    db = analogsub_to_dahdisub(b);
02564 
02565    tchan = p->subs[da].chan;
02566    p->subs[da].chan = p->subs[db].chan;
02567    p->subs[db].chan = tchan;
02568 
02569    tinthreeway = p->subs[da].inthreeway;
02570    p->subs[da].inthreeway = p->subs[db].inthreeway;
02571    p->subs[db].inthreeway = tinthreeway;
02572 
02573    p->subs[da].owner = ast_a;
02574    p->subs[db].owner = ast_b;
02575 
02576    if (ast_a)
02577       ast_channel_set_fd(ast_a, 0, p->subs[da].dfd);
02578    if (ast_b)
02579       ast_channel_set_fd(ast_b, 0, p->subs[db].dfd);
02580 
02581    wakeup_sub(p, a);
02582    wakeup_sub(p, b);
02583 
02584    return;
02585 }
02586 
02587 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid);
02588 
02589 static struct ast_channel *my_new_analog_ast_channel(void *pvt, int state, int startpbx, enum analog_sub sub, const struct ast_channel *requestor)
02590 {
02591    struct dahdi_pvt *p = pvt;
02592    int dsub = analogsub_to_dahdisub(sub);
02593 
02594    return dahdi_new(p, state, startpbx, dsub, 0, requestor ? requestor->linkedid : "");
02595 }
02596 
02597 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02598 static int dahdi_setlaw(int dfd, int law)
02599 {
02600    int res;
02601    res = ioctl(dfd, DAHDI_SETLAW, &law);
02602    if (res)
02603       return res;
02604    return 0;
02605 }
02606 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02607 
02608 #if defined(HAVE_PRI)
02609 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)
02610 {
02611    struct dahdi_pvt *p = pvt;
02612    int audio;
02613    int newlaw = -1;
02614 
02615    switch (p->sig) {
02616    case SIG_PRI_LIB_HANDLE_CASES:
02617       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
02618          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
02619          break;
02620       }
02621       /* Fall through */
02622    default:
02623       /* Set to audio mode at this point */
02624       audio = 1;
02625       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1) {
02626          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
02627             p->channel, audio, strerror(errno));
02628       }
02629       break;
02630    }
02631 
02632    if (law != SIG_PRI_DEFLAW) {
02633       dahdi_setlaw(p->subs[SUB_REAL].dfd, (law == SIG_PRI_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
02634    }
02635 
02636    ast_copy_string(p->exten, exten, sizeof(p->exten));
02637 
02638    switch (law) {
02639       case SIG_PRI_DEFLAW:
02640          newlaw = 0;
02641          break;
02642       case SIG_PRI_ALAW:
02643          newlaw = DAHDI_LAW_ALAW;
02644          break;
02645       case SIG_PRI_ULAW:
02646          newlaw = DAHDI_LAW_MULAW;
02647          break;
02648    }
02649    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
02650 }
02651 #endif   /* defined(HAVE_PRI) */
02652 
02653 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law);
02654 
02655 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02656 /*!
02657  * \internal
02658  * \brief Open the PRI/SS7 channel media path.
02659  * \since 1.8
02660  *
02661  * \param p Channel private control structure.
02662  *
02663  * \return Nothing
02664  */
02665 static void my_pri_ss7_open_media(void *p)
02666 {
02667    struct dahdi_pvt *pvt = p;
02668    int res;
02669    int dfd;
02670    int set_val;
02671 
02672    dfd = pvt->subs[SUB_REAL].dfd;
02673 
02674    /* Open the media path. */
02675    set_val = 1;
02676    res = ioctl(dfd, DAHDI_AUDIOMODE, &set_val);
02677    if (res < 0) {
02678       ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n",
02679          pvt->channel, strerror(errno));
02680    }
02681 
02682    /* Set correct companding law for this call. */
02683    res = dahdi_setlaw(dfd, pvt->law);
02684    if (res < 0) {
02685       ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pvt->channel);
02686    }
02687 
02688    /* Set correct gain for this call. */
02689    if (pvt->digital) {
02690       res = set_actual_gain(dfd, 0, 0, pvt->rxdrc, pvt->txdrc, pvt->law);
02691    } else {
02692       res = set_actual_gain(dfd, pvt->rxgain, pvt->txgain, pvt->rxdrc, pvt->txdrc,
02693          pvt->law);
02694    }
02695    if (res < 0) {
02696       ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pvt->channel);
02697    }
02698 
02699    if (pvt->dsp_features && pvt->dsp) {
02700       ast_dsp_set_features(pvt->dsp, pvt->dsp_features);
02701       pvt->dsp_features = 0;
02702    }
02703 }
02704 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02705 
02706 #if defined(HAVE_PRI)
02707 /*!
02708  * \internal
02709  * \brief Ask DAHDI to dial the given dial string.
02710  * \since 1.8.11
02711  *
02712  * \param p Channel private control structure.
02713  * \param dial_string String to pass to DAHDI to dial.
02714  *
02715  * \note The channel private lock needs to be held when calling.
02716  *
02717  * \return Nothing
02718  */
02719 static void my_pri_dial_digits(void *p, const char *dial_string)
02720 {
02721    struct dahdi_dialoperation zo = {
02722       .op = DAHDI_DIAL_OP_APPEND,
02723    };
02724    struct dahdi_pvt *pvt = p;
02725    int res;
02726 
02727    snprintf(zo.dialstr, sizeof(zo.dialstr), "T%s", dial_string);
02728    ast_debug(1, "Channel %d: Sending '%s' to DAHDI_DIAL.\n", pvt->channel, zo.dialstr);
02729    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo);
02730    if (res) {
02731       ast_log(LOG_WARNING, "Channel %d: Couldn't dial '%s': %s\n",
02732          pvt->channel, dial_string, strerror(errno));
02733    } else {
02734       pvt->dialing = 1;
02735    }
02736 }
02737 #endif   /* defined(HAVE_PRI) */
02738 
02739 static int unalloc_sub(struct dahdi_pvt *p, int x);
02740 
02741 static int my_unallocate_sub(void *pvt, enum analog_sub analogsub)
02742 {
02743    struct dahdi_pvt *p = pvt;
02744 
02745    return unalloc_sub(p, analogsub_to_dahdisub(analogsub));
02746 }
02747 
02748 static int alloc_sub(struct dahdi_pvt *p, int x);
02749 
02750 static int my_allocate_sub(void *pvt, enum analog_sub analogsub)
02751 {
02752    struct dahdi_pvt *p = pvt;
02753 
02754    return alloc_sub(p, analogsub_to_dahdisub(analogsub));
02755 }
02756 
02757 static int has_voicemail(struct dahdi_pvt *p);
02758 
02759 static int my_has_voicemail(void *pvt)
02760 {
02761    struct dahdi_pvt *p = pvt;
02762 
02763    return has_voicemail(p);
02764 }
02765 
02766 static int my_play_tone(void *pvt, enum analog_sub sub, enum analog_tone tone)
02767 {
02768    struct dahdi_pvt *p = pvt;
02769    int index;
02770 
02771    index = analogsub_to_dahdisub(sub);
02772 
02773    return tone_zone_play_tone(p->subs[index].dfd, analog_tone_to_dahditone(tone));
02774 }
02775 
02776 static enum analog_event dahdievent_to_analogevent(int event)
02777 {
02778    enum analog_event res;
02779 
02780    switch (event) {
02781    case DAHDI_EVENT_ONHOOK:
02782       res = ANALOG_EVENT_ONHOOK;
02783       break;
02784    case DAHDI_EVENT_RINGOFFHOOK:
02785       res = ANALOG_EVENT_RINGOFFHOOK;
02786       break;
02787    case DAHDI_EVENT_WINKFLASH:
02788       res = ANALOG_EVENT_WINKFLASH;
02789       break;
02790    case DAHDI_EVENT_ALARM:
02791       res = ANALOG_EVENT_ALARM;
02792       break;
02793    case DAHDI_EVENT_NOALARM:
02794       res = ANALOG_EVENT_NOALARM;
02795       break;
02796    case DAHDI_EVENT_DIALCOMPLETE:
02797       res = ANALOG_EVENT_DIALCOMPLETE;
02798       break;
02799    case DAHDI_EVENT_RINGERON:
02800       res = ANALOG_EVENT_RINGERON;
02801       break;
02802    case DAHDI_EVENT_RINGEROFF:
02803       res = ANALOG_EVENT_RINGEROFF;
02804       break;
02805    case DAHDI_EVENT_HOOKCOMPLETE:
02806       res = ANALOG_EVENT_HOOKCOMPLETE;
02807       break;
02808    case DAHDI_EVENT_PULSE_START:
02809       res = ANALOG_EVENT_PULSE_START;
02810       break;
02811    case DAHDI_EVENT_POLARITY:
02812       res = ANALOG_EVENT_POLARITY;
02813       break;
02814    case DAHDI_EVENT_RINGBEGIN:
02815       res = ANALOG_EVENT_RINGBEGIN;
02816       break;
02817    case DAHDI_EVENT_EC_DISABLED:
02818       res = ANALOG_EVENT_EC_DISABLED;
02819       break;
02820    case DAHDI_EVENT_REMOVED:
02821       res = ANALOG_EVENT_REMOVED;
02822       break;
02823    case DAHDI_EVENT_NEONMWI_ACTIVE:
02824       res = ANALOG_EVENT_NEONMWI_ACTIVE;
02825       break;
02826    case DAHDI_EVENT_NEONMWI_INACTIVE:
02827       res = ANALOG_EVENT_NEONMWI_INACTIVE;
02828       break;
02829 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
02830    case DAHDI_EVENT_TX_CED_DETECTED:
02831       res = ANALOG_EVENT_TX_CED_DETECTED;
02832       break;
02833    case DAHDI_EVENT_RX_CED_DETECTED:
02834       res = ANALOG_EVENT_RX_CED_DETECTED;
02835       break;
02836    case DAHDI_EVENT_EC_NLP_DISABLED:
02837       res = ANALOG_EVENT_EC_NLP_DISABLED;
02838       break;
02839    case DAHDI_EVENT_EC_NLP_ENABLED:
02840       res = ANALOG_EVENT_EC_NLP_ENABLED;
02841       break;
02842 #endif
02843    case DAHDI_EVENT_PULSEDIGIT:
02844       res = ANALOG_EVENT_PULSEDIGIT;
02845       break;
02846    case DAHDI_EVENT_DTMFDOWN:
02847       res = ANALOG_EVENT_DTMFDOWN;
02848       break;
02849    case DAHDI_EVENT_DTMFUP:
02850       res = ANALOG_EVENT_DTMFUP;
02851       break;
02852    default:
02853       switch(event & 0xFFFF0000) {
02854       case DAHDI_EVENT_PULSEDIGIT:
02855       case DAHDI_EVENT_DTMFDOWN:
02856       case DAHDI_EVENT_DTMFUP:
02857          /* The event includes a digit number in the low word.
02858           * Converting it to a 'enum analog_event' would remove
02859           * that information. Thus it is returned as-is.
02860           */
02861          return event;
02862       }
02863 
02864       res = ANALOG_EVENT_ERROR;
02865       break;
02866    }
02867 
02868    return res;
02869 }
02870 
02871 static inline int dahdi_wait_event(int fd);
02872 
02873 static int my_wait_event(void *pvt)
02874 {
02875    struct dahdi_pvt *p = pvt;
02876 
02877    return dahdi_wait_event(p->subs[SUB_REAL].dfd);
02878 }
02879 
02880 static int my_get_event(void *pvt)
02881 {
02882    struct dahdi_pvt *p = pvt;
02883    int res;
02884 
02885    if (p->fake_event) {
02886       res = p->fake_event;
02887       p->fake_event = 0;
02888    } else
02889       res = dahdi_get_event(p->subs[SUB_REAL].dfd);
02890 
02891    return dahdievent_to_analogevent(res);
02892 }
02893 
02894 static int my_is_off_hook(void *pvt)
02895 {
02896    struct dahdi_pvt *p = pvt;
02897    int res;
02898    struct dahdi_params par;
02899 
02900    memset(&par, 0, sizeof(par));
02901 
02902    if (p->subs[SUB_REAL].dfd > -1)
02903       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
02904    else {
02905       /* Assume not off hook on CVRS */
02906       res = 0;
02907       par.rxisoffhook = 0;
02908    }
02909    if (res) {
02910       ast_log(LOG_WARNING, "Unable to check hook state on channel %d: %s\n", p->channel, strerror(errno));
02911    }
02912 
02913    if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
02914       /* When "onhook" that means no battery on the line, and thus
02915       it is out of service..., if it's on a TDM card... If it's a channel
02916       bank, there is no telling... */
02917       return (par.rxbits > -1) || par.rxisoffhook;
02918    }
02919 
02920    return par.rxisoffhook;
02921 }
02922 
02923 static void dahdi_enable_ec(struct dahdi_pvt *p);
02924 static void dahdi_disable_ec(struct dahdi_pvt *p);
02925 
02926 static int my_set_echocanceller(void *pvt, int enable)
02927 {
02928    struct dahdi_pvt *p = pvt;
02929 
02930    if (enable)
02931       dahdi_enable_ec(p);
02932    else
02933       dahdi_disable_ec(p);
02934 
02935    return 0;
02936 }
02937 
02938 static int dahdi_ring_phone(struct dahdi_pvt *p);
02939 
02940 static int my_ring(void *pvt)
02941 {
02942    struct dahdi_pvt *p = pvt;
02943 
02944    return dahdi_ring_phone(p);
02945 }
02946 
02947 static int my_flash(void *pvt)
02948 {
02949    struct dahdi_pvt *p = pvt;
02950    int func = DAHDI_FLASH;
02951    return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &func);
02952 }
02953 
02954 static inline int dahdi_set_hook(int fd, int hs);
02955 
02956 static int my_off_hook(void *pvt)
02957 {
02958    struct dahdi_pvt *p = pvt;
02959    return dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
02960 }
02961 
02962 static void my_set_needringing(void *pvt, int value)
02963 {
02964    struct dahdi_pvt *p = pvt;
02965    p->subs[SUB_REAL].needringing = value;
02966 }
02967 
02968 static void my_set_polarity(void *pvt, int value)
02969 {
02970    struct dahdi_pvt *p = pvt;
02971 
02972    if (p->channel == CHAN_PSEUDO) {
02973       return;
02974    }
02975    p->polarity = value;
02976    ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETPOLARITY, &value);
02977 }
02978 
02979 static void my_start_polarityswitch(void *pvt)
02980 {
02981    struct dahdi_pvt *p = pvt;
02982 
02983    if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
02984       my_set_polarity(pvt, 0);
02985    }
02986 }
02987 
02988 static void my_answer_polarityswitch(void *pvt)
02989 {
02990    struct dahdi_pvt *p = pvt;
02991 
02992    if (!p->answeronpolarityswitch) {
02993       return;
02994    }
02995 
02996    my_set_polarity(pvt, 1);
02997 }
02998 
02999 static void my_hangup_polarityswitch(void *pvt)
03000 {
03001    struct dahdi_pvt *p = pvt;
03002 
03003    if (!p->hanguponpolarityswitch) {
03004       return;
03005    }
03006 
03007    if (p->answeronpolarityswitch) {
03008       my_set_polarity(pvt, 0);
03009    } else {
03010       my_set_polarity(pvt, 1);
03011    }
03012 }
03013 
03014 static int my_start(void *pvt)
03015 {
03016    struct dahdi_pvt *p = pvt;
03017    int x = DAHDI_START;
03018 
03019    return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
03020 }
03021 
03022 static int my_dial_digits(void *pvt, enum analog_sub sub, struct analog_dialoperation *dop)
03023 {
03024    int index = analogsub_to_dahdisub(sub);
03025    int res;
03026    struct dahdi_pvt *p = pvt;
03027    struct dahdi_dialoperation ddop;
03028 
03029    if (dop->op != ANALOG_DIAL_OP_REPLACE) {
03030       ast_log(LOG_ERROR, "Fix the dial_digits callback!\n");
03031       return -1;
03032    }
03033 
03034    if (sub != ANALOG_SUB_REAL) {
03035       ast_log(LOG_ERROR, "Trying to dial_digits '%s' on channel %d subchannel %d\n",
03036          dop->dialstr, p->channel, sub);
03037       return -1;
03038    }
03039 
03040    ddop.op = DAHDI_DIAL_OP_REPLACE;
03041    ast_copy_string(ddop.dialstr, dop->dialstr, sizeof(ddop.dialstr));
03042 
03043    ast_debug(1, "Channel %d: Sending '%s' to DAHDI_DIAL.\n", p->channel, ddop.dialstr);
03044 
03045    res = ioctl(p->subs[index].dfd, DAHDI_DIAL, &ddop);
03046    if (res == -1) {
03047       ast_debug(1, "DAHDI_DIAL ioctl failed on %s: %s\n", p->owner->name, strerror(errno));
03048    }
03049 
03050    return res;
03051 }
03052 
03053 static void dahdi_train_ec(struct dahdi_pvt *p);
03054 
03055 static int my_train_echocanceller(void *pvt)
03056 {
03057    struct dahdi_pvt *p = pvt;
03058 
03059    dahdi_train_ec(p);
03060 
03061    return 0;
03062 }
03063 
03064 static int my_is_dialing(void *pvt, enum analog_sub sub)
03065 {
03066    struct dahdi_pvt *p = pvt;
03067    int index;
03068    int x;
03069 
03070    index = analogsub_to_dahdisub(sub);
03071 
03072    if (ioctl(p->subs[index].dfd, DAHDI_DIALING, &x)) {
03073       ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed!\n");
03074       return -1;
03075    }
03076 
03077    return x;
03078 }
03079 
03080 static int my_on_hook(void *pvt)
03081 {
03082    struct dahdi_pvt *p = pvt;
03083    return dahdi_set_hook(p->subs[ANALOG_SUB_REAL].dfd, DAHDI_ONHOOK);
03084 }
03085 
03086 #if defined(HAVE_PRI)
03087 static void my_pri_fixup_chans(void *chan_old, void *chan_new)
03088 {
03089    struct dahdi_pvt *old_chan = chan_old;
03090    struct dahdi_pvt *new_chan = chan_new;
03091 
03092    new_chan->owner = old_chan->owner;
03093    old_chan->owner = NULL;
03094    if (new_chan->owner) {
03095       new_chan->owner->tech_pvt = new_chan;
03096       new_chan->owner->fds[0] = new_chan->subs[SUB_REAL].dfd;
03097       new_chan->subs[SUB_REAL].owner = old_chan->subs[SUB_REAL].owner;
03098       old_chan->subs[SUB_REAL].owner = NULL;
03099    }
03100    /* Copy any DSP that may be present */
03101    new_chan->dsp = old_chan->dsp;
03102    new_chan->dsp_features = old_chan->dsp_features;
03103    old_chan->dsp = NULL;
03104    old_chan->dsp_features = 0;
03105 
03106    /* Transfer flags from the old channel. */
03107    new_chan->dialing = old_chan->dialing;
03108    new_chan->digital = old_chan->digital;
03109    new_chan->outgoing = old_chan->outgoing;
03110    old_chan->dialing = 0;
03111    old_chan->digital = 0;
03112    old_chan->outgoing = 0;
03113 
03114    /* More stuff to transfer to the new channel. */
03115    new_chan->law = old_chan->law;
03116    strcpy(new_chan->dialstring, old_chan->dialstring);
03117 }
03118 #endif   /* defined(HAVE_PRI) */
03119 
03120 #if defined(HAVE_PRI)
03121 static int sig_pri_tone_to_dahditone(enum sig_pri_tone tone)
03122 {
03123    switch (tone) {
03124    case SIG_PRI_TONE_RINGTONE:
03125       return DAHDI_TONE_RINGTONE;
03126    case SIG_PRI_TONE_STUTTER:
03127       return DAHDI_TONE_STUTTER;
03128    case SIG_PRI_TONE_CONGESTION:
03129       return DAHDI_TONE_CONGESTION;
03130    case SIG_PRI_TONE_DIALTONE:
03131       return DAHDI_TONE_DIALTONE;
03132    case SIG_PRI_TONE_DIALRECALL:
03133       return DAHDI_TONE_DIALRECALL;
03134    case SIG_PRI_TONE_INFO:
03135       return DAHDI_TONE_INFO;
03136    case SIG_PRI_TONE_BUSY:
03137       return DAHDI_TONE_BUSY;
03138    default:
03139       return -1;
03140    }
03141 }
03142 #endif   /* defined(HAVE_PRI) */
03143 
03144 #if defined(HAVE_PRI)
03145 static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
03146 {
03147    int x;
03148 
03149    ioctl(pri->fds[index], DAHDI_GETEVENT, &x);
03150    switch (x) {
03151    case DAHDI_EVENT_NONE:
03152       break;
03153    case DAHDI_EVENT_ALARM:
03154    case DAHDI_EVENT_NOALARM:
03155       if (sig_pri_is_alarm_ignored(pri)) {
03156          break;
03157       }
03158       /* Fall through */
03159    default:
03160       ast_log(LOG_NOTICE, "PRI got event: %s (%d) on D-channel of span %d\n",
03161          event2str(x), x, pri->span);
03162       break;
03163    }
03164    /* Keep track of alarm state */
03165    switch (x) {
03166    case DAHDI_EVENT_ALARM:
03167       pri_event_alarm(pri, index, 0);
03168       break;
03169    case DAHDI_EVENT_NOALARM:
03170       pri_event_noalarm(pri, index, 0);
03171       break;
03172    default:
03173       break;
03174    }
03175 }
03176 #endif   /* defined(HAVE_PRI) */
03177 
03178 #if defined(HAVE_PRI)
03179 static int my_pri_play_tone(void *pvt, enum sig_pri_tone tone)
03180 {
03181    struct dahdi_pvt *p = pvt;
03182 
03183    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_pri_tone_to_dahditone(tone));
03184 }
03185 #endif   /* defined(HAVE_PRI) */
03186 
03187 #if defined(HAVE_PRI) || defined(HAVE_SS7)
03188 /*!
03189  * \internal
03190  * \brief Set the caller id information.
03191  * \since 1.8
03192  *
03193  * \param pvt DAHDI private structure
03194  * \param caller Caller-id information to set.
03195  *
03196  * \return Nothing
03197  */
03198 static void my_set_callerid(void *pvt, const struct ast_party_caller *caller)
03199 {
03200    struct dahdi_pvt *p = pvt;
03201 
03202    ast_copy_string(p->cid_num,
03203       S_COR(caller->id.number.valid, caller->id.number.str, ""),
03204       sizeof(p->cid_num));
03205    ast_copy_string(p->cid_name,
03206       S_COR(caller->id.name.valid, caller->id.name.str, ""),
03207       sizeof(p->cid_name));
03208    ast_copy_string(p->cid_subaddr,
03209       S_COR(caller->id.subaddress.valid, caller->id.subaddress.str, ""),
03210       sizeof(p->cid_subaddr));
03211    p->cid_ton = caller->id.number.plan;
03212    p->callingpres = ast_party_id_presentation(&caller->id);
03213    if (caller->id.tag) {
03214       ast_copy_string(p->cid_tag, caller->id.tag, sizeof(p->cid_tag));
03215    }
03216    ast_copy_string(p->cid_ani,
03217       S_COR(caller->ani.number.valid, caller->ani.number.str, ""),
03218       sizeof(p->cid_ani));
03219    p->cid_ani2 = caller->ani2;
03220 }
03221 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03222 
03223 #if defined(HAVE_PRI) || defined(HAVE_SS7)
03224 /*!
03225  * \internal
03226  * \brief Set the Dialed Number Identifier.
03227  * \since 1.8
03228  *
03229  * \param pvt DAHDI private structure
03230  * \param dnid Dialed Number Identifier string.
03231  *
03232  * \return Nothing
03233  */
03234 static void my_set_dnid(void *pvt, const char *dnid)
03235 {
03236    struct dahdi_pvt *p = pvt;
03237 
03238    ast_copy_string(p->dnid, dnid, sizeof(p->dnid));
03239 }
03240 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03241 
03242 #if defined(HAVE_PRI)
03243 /*!
03244  * \internal
03245  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
03246  * \since 1.8
03247  *
03248  * \param pvt DAHDI private structure
03249  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
03250  *
03251  * \return Nothing
03252  */
03253 static void my_set_rdnis(void *pvt, const char *rdnis)
03254 {
03255    struct dahdi_pvt *p = pvt;
03256 
03257    ast_copy_string(p->rdnis, rdnis, sizeof(p->rdnis));
03258 }
03259 #endif   /* defined(HAVE_PRI) */
03260 
03261 #if defined(HAVE_PRI)
03262 /*!
03263  * \internal
03264  * \brief Make a dialstring for native ISDN CC to recall properly.
03265  * \since 1.8
03266  *
03267  * \param priv Channel private control structure.
03268  * \param buf Where to put the modified dialstring.
03269  * \param buf_size Size of modified dialstring buffer.
03270  *
03271  * \details
03272  * original dialstring:
03273  * DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03274  *
03275  * The modified dialstring will have prefixed the channel-group section
03276  * with the ISDN channel restriction.
03277  *
03278  * buf:
03279  * DAHDI/i<span>-(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03280  *
03281  * The routine will check to see if the ISDN channel restriction is already
03282  * in the original dialstring.
03283  *
03284  * \return Nothing
03285  */
03286 static void my_pri_make_cc_dialstring(void *priv, char *buf, size_t buf_size)
03287 {
03288    char *dial;
03289    struct dahdi_pvt *pvt;
03290    AST_DECLARE_APP_ARGS(args,
03291       AST_APP_ARG(tech);   /* channel technology token */
03292       AST_APP_ARG(group);  /* channel/group token */
03293       //AST_APP_ARG(ext);  /* extension token */
03294       //AST_APP_ARG(opts); /* options token */
03295       //AST_APP_ARG(other);   /* Any remining unused arguments */
03296    );
03297 
03298    pvt = priv;
03299    dial = ast_strdupa(pvt->dialstring);
03300    AST_NONSTANDARD_APP_ARGS(args, dial, '/');
03301    if (!args.tech) {
03302       ast_copy_string(buf, pvt->dialstring, buf_size);
03303       return;
03304    }
03305    if (!args.group) {
03306       /* Append the ISDN span channel restriction to the dialstring. */
03307       snprintf(buf, buf_size, "%s/i%d-", args.tech, pvt->pri->span);
03308       return;
03309    }
03310    if (isdigit(args.group[0]) || args.group[0] == 'i' || strchr(args.group, '!')) {
03311       /* The ISDN span channel restriction is not needed or already
03312        * in the dialstring. */
03313       ast_copy_string(buf, pvt->dialstring, buf_size);
03314       return;
03315    }
03316    /* Insert the ISDN span channel restriction into the dialstring. */
03317    snprintf(buf, buf_size, "%s/i%d-%s", args.tech, pvt->pri->span, args.group);
03318 }
03319 #endif   /* defined(HAVE_PRI) */
03320 
03321 #if defined(HAVE_PRI)
03322 /*!
03323  * \internal
03324  * \brief Reevaluate the PRI span device state.
03325  * \since 1.8
03326  *
03327  * \param pri Asterisk D channel control structure.
03328  *
03329  * \return Nothing
03330  *
03331  * \note Assumes the pri->lock is already obtained.
03332  */
03333 static void dahdi_pri_update_span_devstate(struct sig_pri_span *pri)
03334 {
03335    unsigned idx;
03336    unsigned num_b_chans;   /* Number of B channels provisioned on the span. */
03337    unsigned in_use;     /* Number of B channels in use on the span. */
03338    unsigned in_alarm;      /* TRUE if the span is in alarm condition. */
03339    enum ast_device_state new_state;
03340 
03341    /* Count the number of B channels and the number of B channels in use. */
03342    num_b_chans = 0;
03343    in_use = 0;
03344    in_alarm = 1;
03345    for (idx = pri->numchans; idx--;) {
03346       if (pri->pvts[idx] && !pri->pvts[idx]->no_b_channel) {
03347          /* This is a B channel interface. */
03348          ++num_b_chans;
03349          if (!sig_pri_is_chan_available(pri->pvts[idx])) {
03350             ++in_use;
03351          }
03352          if (!pri->pvts[idx]->inalarm) {
03353             /* There is a channel that is not in alarm. */
03354             in_alarm = 0;
03355          }
03356       }
03357    }
03358 
03359    /* Update the span congestion device state and report any change. */
03360    if (in_alarm) {
03361       new_state = AST_DEVICE_UNAVAILABLE;
03362    } else {
03363       new_state = num_b_chans == in_use ? AST_DEVICE_BUSY : AST_DEVICE_NOT_INUSE;
03364    }
03365    if (pri->congestion_devstate != new_state) {
03366       pri->congestion_devstate = new_state;
03367       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_NOT_CACHABLE, "DAHDI/I%d/congestion", pri->span);
03368    }
03369 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
03370    /* Update the span threshold device state and report any change. */
03371    if (in_alarm) {
03372       new_state = AST_DEVICE_UNAVAILABLE;
03373    } else if (!in_use) {
03374       new_state = AST_DEVICE_NOT_INUSE;
03375    } else if (!pri->user_busy_threshold) {
03376       new_state = in_use < num_b_chans ? AST_DEVICE_INUSE : AST_DEVICE_BUSY;
03377    } else {
03378       new_state = in_use < pri->user_busy_threshold ? AST_DEVICE_INUSE
03379          : AST_DEVICE_BUSY;
03380    }
03381    if (pri->threshold_devstate != new_state) {
03382       pri->threshold_devstate = new_state;
03383       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_NOT_CACHABLE, "DAHDI/I%d/threshold", pri->span);
03384    }
03385 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
03386 }
03387 #endif   /* defined(HAVE_PRI) */
03388 
03389 #if defined(HAVE_PRI)
03390 /*!
03391  * \internal
03392  * \brief Reference this module.
03393  * \since 1.8
03394  *
03395  * \return Nothing
03396  */
03397 static void my_module_ref(void)
03398 {
03399    ast_module_ref(ast_module_info->self);
03400 }
03401 #endif   /* defined(HAVE_PRI) */
03402 
03403 #if defined(HAVE_PRI)
03404 /*!
03405  * \internal
03406  * \brief Unreference this module.
03407  * \since 1.8
03408  *
03409  * \return Nothing
03410  */
03411 static void my_module_unref(void)
03412 {
03413    ast_module_unref(ast_module_info->self);
03414 }
03415 #endif   /* defined(HAVE_PRI) */
03416 
03417 #if defined(HAVE_PRI)
03418 #if defined(HAVE_PRI_CALL_WAITING)
03419 static void my_pri_init_config(void *priv, struct sig_pri_span *pri);
03420 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03421 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri);
03422 
03423 static struct sig_pri_callback dahdi_pri_callbacks =
03424 {
03425    .handle_dchan_exception = my_handle_dchan_exception,
03426    .play_tone = my_pri_play_tone,
03427    .set_echocanceller = my_set_echocanceller,
03428    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03429    .lock_private = my_lock_private,
03430    .unlock_private = my_unlock_private,
03431    .new_ast_channel = my_new_pri_ast_channel,
03432    .fixup_chans = my_pri_fixup_chans,
03433    .set_alarm = my_set_alarm,
03434    .set_dialing = my_set_dialing,
03435    .set_outgoing = my_set_outgoing,
03436    .set_digital = my_set_digital,
03437    .set_callerid = my_set_callerid,
03438    .set_dnid = my_set_dnid,
03439    .set_rdnis = my_set_rdnis,
03440    .new_nobch_intf = dahdi_new_pri_nobch_channel,
03441 #if defined(HAVE_PRI_CALL_WAITING)
03442    .init_config = my_pri_init_config,
03443 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03444    .get_orig_dialstring = my_get_orig_dialstring,
03445    .make_cc_dialstring = my_pri_make_cc_dialstring,
03446    .update_span_devstate = dahdi_pri_update_span_devstate,
03447    .module_ref = my_module_ref,
03448    .module_unref = my_module_unref,
03449    .dial_digits = my_pri_dial_digits,
03450    .open_media = my_pri_ss7_open_media,
03451    .ami_channel_event = my_ami_channel_event,
03452 };
03453 #endif   /* defined(HAVE_PRI) */
03454 
03455 #if defined(HAVE_SS7)
03456 /*!
03457  * \internal
03458  * \brief Handle the SS7 link exception.
03459  * \since 1.8
03460  *
03461  * \param linkset Controlling linkset for the channel.
03462  * \param which Link index of the signaling channel.
03463  *
03464  * \return Nothing
03465  */
03466 static void my_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
03467 {
03468    int event;
03469 
03470    if (ioctl(linkset->fds[which], DAHDI_GETEVENT, &event)) {
03471       ast_log(LOG_ERROR, "SS7: Error in exception retrieval on span %d/%d!\n",
03472          linkset->span, which);
03473       return;
03474    }
03475    switch (event) {
03476    case DAHDI_EVENT_NONE:
03477       break;
03478    case DAHDI_EVENT_ALARM:
03479       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03480          event2str(event), event, linkset->span, which);
03481       sig_ss7_link_alarm(linkset, which);
03482       break;
03483    case DAHDI_EVENT_NOALARM:
03484       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03485          event2str(event), event, linkset->span, which);
03486       sig_ss7_link_noalarm(linkset, which);
03487       break;
03488    default:
03489       ast_log(LOG_NOTICE, "SS7 got event: %s(%d) on span %d/%d\n",
03490          event2str(event), event, linkset->span, which);
03491       break;
03492    }
03493 }
03494 #endif   /* defined(HAVE_SS7) */
03495 
03496 #if defined(HAVE_SS7)
03497 static void my_ss7_set_loopback(void *pvt, int enable)
03498 {
03499    struct dahdi_pvt *p = pvt;
03500 
03501    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
03502       ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel,
03503          strerror(errno));
03504    }
03505 }
03506 #endif   /* defined(HAVE_SS7) */
03507 
03508 #if defined(HAVE_SS7)
03509 /*!
03510  * \internal
03511  * \brief Create a new asterisk channel structure for SS7.
03512  * \since 1.8
03513  *
03514  * \param pvt Private channel structure.
03515  * \param state Initial state of new channel.
03516  * \param law Combanding law to use.
03517  * \param exten Dialplan extension for incoming call.
03518  * \param requestor Channel requesting this new channel.
03519  *
03520  * \retval ast_channel on success.
03521  * \retval NULL on error.
03522  */
03523 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)
03524 {
03525    struct dahdi_pvt *p = pvt;
03526    int audio;
03527    int newlaw;
03528 
03529    /* Set to audio mode at this point */
03530    audio = 1;
03531    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1)
03532       ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
03533          p->channel, audio, strerror(errno));
03534 
03535    if (law != SIG_SS7_DEFLAW) {
03536       dahdi_setlaw(p->subs[SUB_REAL].dfd,
03537          (law == SIG_SS7_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
03538    }
03539 
03540    ast_copy_string(p->exten, exten, sizeof(p->exten));
03541 
03542    newlaw = -1;
03543    switch (law) {
03544    case SIG_SS7_DEFLAW:
03545       newlaw = 0;
03546       break;
03547    case SIG_SS7_ALAW:
03548       newlaw = DAHDI_LAW_ALAW;
03549       break;
03550    case SIG_SS7_ULAW:
03551       newlaw = DAHDI_LAW_MULAW;
03552       break;
03553    }
03554    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
03555 }
03556 #endif   /* defined(HAVE_SS7) */
03557 
03558 #if defined(HAVE_SS7)
03559 static int sig_ss7_tone_to_dahditone(enum sig_ss7_tone tone)
03560 {
03561    switch (tone) {
03562    case SIG_SS7_TONE_RINGTONE:
03563       return DAHDI_TONE_RINGTONE;
03564    case SIG_SS7_TONE_STUTTER:
03565       return DAHDI_TONE_STUTTER;
03566    case SIG_SS7_TONE_CONGESTION:
03567       return DAHDI_TONE_CONGESTION;
03568    case SIG_SS7_TONE_DIALTONE:
03569       return DAHDI_TONE_DIALTONE;
03570    case SIG_SS7_TONE_DIALRECALL:
03571       return DAHDI_TONE_DIALRECALL;
03572    case SIG_SS7_TONE_INFO:
03573       return DAHDI_TONE_INFO;
03574    case SIG_SS7_TONE_BUSY:
03575       return DAHDI_TONE_BUSY;
03576    default:
03577       return -1;
03578    }
03579 }
03580 #endif   /* defined(HAVE_SS7) */
03581 
03582 #if defined(HAVE_SS7)
03583 static int my_ss7_play_tone(void *pvt, enum sig_ss7_tone tone)
03584 {
03585    struct dahdi_pvt *p = pvt;
03586 
03587    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_ss7_tone_to_dahditone(tone));
03588 }
03589 #endif   /* defined(HAVE_SS7) */
03590 
03591 #if defined(HAVE_SS7)
03592 static struct sig_ss7_callback dahdi_ss7_callbacks =
03593 {
03594    .lock_private = my_lock_private,
03595    .unlock_private = my_unlock_private,
03596 
03597    .set_echocanceller = my_set_echocanceller,
03598    .set_loopback = my_ss7_set_loopback,
03599 
03600    .new_ast_channel = my_new_ss7_ast_channel,
03601    .play_tone = my_ss7_play_tone,
03602 
03603    .handle_link_exception = my_handle_link_exception,
03604    .set_alarm = my_set_alarm,
03605    .set_dialing = my_set_dialing,
03606    .set_outgoing = my_set_outgoing,
03607    .set_digital = my_set_digital,
03608    .set_inservice = my_set_inservice,
03609    .set_locallyblocked = my_set_locallyblocked,
03610    .set_remotelyblocked = my_set_remotelyblocked,
03611    .set_callerid = my_set_callerid,
03612    .set_dnid = my_set_dnid,
03613    .open_media = my_pri_ss7_open_media,
03614 };
03615 #endif   /* defined(HAVE_SS7) */
03616 
03617 /*!
03618  * \brief Send MWI state change
03619  *
03620  * \arg mailbox_full This is the mailbox associated with the FXO line that the
03621  *      MWI state has changed on.
03622  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
03623  *      whether there are messages waiting or not.
03624  *
03625  *  \return nothing
03626  *
03627  * This function does two things:
03628  *
03629  * 1) It generates an internal Asterisk event notifying any other module that
03630  *    cares about MWI that the state of a mailbox has changed.
03631  *
03632  * 2) It runs the script specified by the mwimonitornotify option to allow
03633  *    some custom handling of the state change.
03634  */
03635 static void notify_message(char *mailbox_full, int thereornot)
03636 {
03637    char s[sizeof(mwimonitornotify) + 80];
03638    struct ast_event *event;
03639    char *mailbox, *context;
03640 
03641    /* Strip off @default */
03642    context = mailbox = ast_strdupa(mailbox_full);
03643    strsep(&context, "@");
03644    if (ast_strlen_zero(context))
03645       context = "default";
03646 
03647    if (!(event = ast_event_new(AST_EVENT_MWI,
03648          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
03649          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
03650          AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03651          AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03652          AST_EVENT_IE_END))) {
03653       return;
03654    }
03655 
03656    ast_event_queue_and_cache(event);
03657 
03658    if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
03659       snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
03660       ast_safe_system(s);
03661    }
03662 }
03663 
03664 static void my_handle_notify_message(struct ast_channel *chan, void *pvt, int cid_flags, int neon_mwievent)
03665 {
03666    struct dahdi_pvt *p = pvt;
03667 
03668    if (neon_mwievent > -1 && !p->mwimonitor_neon)
03669       return;
03670 
03671    if (neon_mwievent == ANALOG_EVENT_NEONMWI_ACTIVE || cid_flags & CID_MSGWAITING) {
03672       ast_log(LOG_NOTICE, "MWI: Channel %d message waiting, mailbox %s\n", p->channel, p->mailbox);
03673       notify_message(p->mailbox, 1);
03674    } else if (neon_mwievent == ANALOG_EVENT_NEONMWI_INACTIVE || cid_flags & CID_NOMSGWAITING) {
03675       ast_log(LOG_NOTICE, "MWI: Channel %d no message waiting, mailbox %s\n", p->channel, p->mailbox);
03676       notify_message(p->mailbox, 0);
03677    }
03678    /* If the CID had Message waiting payload, assume that this for MWI only and hangup the call */
03679    /* If generated using Ring Pulse Alert, then ring has been answered as a call and needs to be hungup */
03680    if (neon_mwievent == -1 && p->mwimonitor_rpas) {
03681       ast_hangup(chan);
03682       return;
03683    }
03684 }
03685 
03686 static int my_have_progressdetect(void *pvt)
03687 {
03688    struct dahdi_pvt *p = pvt;
03689 
03690    if ((p->callprogress & CALLPROGRESS_PROGRESS)
03691       && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
03692       return 1;
03693    } else {
03694       /* Don't have progress detection. */
03695       return 0;
03696    }
03697 }
03698 
03699 static struct analog_callback dahdi_analog_callbacks =
03700 {
03701    .play_tone = my_play_tone,
03702    .get_event = my_get_event,
03703    .wait_event = my_wait_event,
03704    .is_off_hook = my_is_off_hook,
03705    .set_echocanceller = my_set_echocanceller,
03706    .ring = my_ring,
03707    .flash = my_flash,
03708    .off_hook = my_off_hook,
03709    .dial_digits = my_dial_digits,
03710    .train_echocanceller = my_train_echocanceller,
03711    .on_hook = my_on_hook,
03712    .is_dialing = my_is_dialing,
03713    .allocate_sub = my_allocate_sub,
03714    .unallocate_sub = my_unallocate_sub,
03715    .swap_subs = my_swap_subchannels,
03716    .has_voicemail = my_has_voicemail,
03717    .check_for_conference = my_check_for_conference,
03718    .conf_add = my_conf_add,
03719    .conf_del = my_conf_del,
03720    .complete_conference_update = my_complete_conference_update,
03721    .start = my_start,
03722    .all_subchannels_hungup = my_all_subchannels_hungup,
03723    .lock_private = my_lock_private,
03724    .unlock_private = my_unlock_private,
03725    .deadlock_avoidance_private = my_deadlock_avoidance_private,
03726    .handle_dtmf = my_handle_dtmf,
03727    .wink = my_wink,
03728    .new_ast_channel = my_new_analog_ast_channel,
03729    .dsp_set_digitmode = my_dsp_set_digitmode,
03730    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03731    .send_callerid = my_send_callerid,
03732    .callwait = my_callwait,
03733    .stop_callwait = my_stop_callwait,
03734    .get_callerid = my_get_callerid,
03735    .start_cid_detect = my_start_cid_detect,
03736    .stop_cid_detect = my_stop_cid_detect,
03737    .handle_notify_message = my_handle_notify_message,
03738    .increase_ss_count = my_increase_ss_count,
03739    .decrease_ss_count = my_decrease_ss_count,
03740    .distinctive_ring = my_distinctive_ring,
03741    .set_linear_mode = my_set_linear_mode,
03742    .set_inthreeway = my_set_inthreeway,
03743    .get_and_handle_alarms = my_get_and_handle_alarms,
03744    .get_sigpvt_bridged_channel = my_get_sigpvt_bridged_channel,
03745    .get_sub_fd = my_get_sub_fd,
03746    .set_cadence = my_set_cadence,
03747    .set_alarm = my_set_alarm,
03748    .set_dialing = my_set_dialing,
03749    .set_outgoing = my_set_outgoing,
03750    .set_ringtimeout = my_set_ringtimeout,
03751    .set_waitingfordt = my_set_waitingfordt,
03752    .check_waitingfordt = my_check_waitingfordt,
03753    .set_confirmanswer = my_set_confirmanswer,
03754    .check_confirmanswer = my_check_confirmanswer,
03755    .set_callwaiting = my_set_callwaiting,
03756    .cancel_cidspill = my_cancel_cidspill,
03757    .confmute = my_confmute,
03758    .set_pulsedial = my_set_pulsedial,
03759    .set_new_owner = my_set_new_owner,
03760    .get_orig_dialstring = my_get_orig_dialstring,
03761    .set_needringing = my_set_needringing,
03762    .set_polarity = my_set_polarity,
03763    .start_polarityswitch = my_start_polarityswitch,
03764    .answer_polarityswitch = my_answer_polarityswitch,
03765    .hangup_polarityswitch = my_hangup_polarityswitch,
03766    .have_progressdetect = my_have_progressdetect,
03767 };
03768 
03769 /*! Round robin search locations. */
03770 static struct dahdi_pvt *round_robin[32];
03771 
03772 #define dahdi_get_index(ast, p, nullok)   _dahdi_get_index(ast, p, nullok, __PRETTY_FUNCTION__, __LINE__)
03773 static int _dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok, const char *fname, unsigned long line)
03774 {
03775    int res;
03776    if (p->subs[SUB_REAL].owner == ast)
03777       res = 0;
03778    else if (p->subs[SUB_CALLWAIT].owner == ast)
03779       res = 1;
03780    else if (p->subs[SUB_THREEWAY].owner == ast)
03781       res = 2;
03782    else {
03783       res = -1;
03784       if (!nullok)
03785          ast_log(LOG_WARNING,
03786             "Unable to get index for '%s' on channel %d (%s(), line %lu)\n",
03787             ast ? ast->name : "", p->channel, fname, line);
03788    }
03789    return res;
03790 }
03791 
03792 /*!
03793  * \internal
03794  * \brief Obtain the specified subchannel owner lock if the owner exists.
03795  *
03796  * \param pvt Channel private struct.
03797  * \param sub_idx Subchannel owner to lock.
03798  *
03799  * \note Assumes the pvt->lock is already obtained.
03800  *
03801  * \note
03802  * Because deadlock avoidance may have been necessary, you need to confirm
03803  * the state of things before continuing.
03804  *
03805  * \return Nothing
03806  */
03807 static void dahdi_lock_sub_owner(struct dahdi_pvt *pvt, int sub_idx)
03808 {
03809    for (;;) {
03810       if (!pvt->subs[sub_idx].owner) {
03811          /* No subchannel owner pointer */
03812          break;
03813       }
03814       if (!ast_channel_trylock(pvt->subs[sub_idx].owner)) {
03815          /* Got subchannel owner lock */
03816          break;
03817       }
03818       /* We must unlock the private to avoid the possibility of a deadlock */
03819       DEADLOCK_AVOIDANCE(&pvt->lock);
03820    }
03821 }
03822 
03823 static void wakeup_sub(struct dahdi_pvt *p, int a)
03824 {
03825    dahdi_lock_sub_owner(p, a);
03826    if (p->subs[a].owner) {
03827       ast_queue_frame(p->subs[a].owner, &ast_null_frame);
03828       ast_channel_unlock(p->subs[a].owner);
03829    }
03830 }
03831 
03832 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f)
03833 {
03834    for (;;) {
03835       if (p->owner) {
03836          if (ast_channel_trylock(p->owner)) {
03837             DEADLOCK_AVOIDANCE(&p->lock);
03838          } else {
03839             ast_queue_frame(p->owner, f);
03840             ast_channel_unlock(p->owner);
03841             break;
03842          }
03843       } else
03844          break;
03845    }
03846 }
03847 
03848 static void handle_clear_alarms(struct dahdi_pvt *p)
03849 {
03850 #if defined(HAVE_PRI)
03851    if (dahdi_sig_pri_lib_handles(p->sig) && sig_pri_is_alarm_ignored(p->pri)) {
03852       return;
03853    }
03854 #endif   /* defined(HAVE_PRI) */
03855 
03856    if (report_alarms & REPORT_CHANNEL_ALARMS) {
03857       ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
03858       manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
03859    }
03860    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
03861       ast_log(LOG_NOTICE, "Alarm cleared on span %d\n", p->span);
03862       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarmClear", "Span: %d\r\n", p->span);
03863    }
03864 }
03865 
03866 #ifdef HAVE_OPENR2
03867 
03868 static int dahdi_r2_answer(struct dahdi_pvt *p)
03869 {
03870    int res = 0;
03871    /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
03872    * and does not has support for openr2_chan_answer_call_with_mode
03873    *  */
03874 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
03875    const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
03876    int wants_double_answer = ast_true(double_answer) ? 1 : 0;
03877    if (!double_answer) {
03878       /* this still can result in double answer if the channel context
03879       * was configured that way */
03880       res = openr2_chan_answer_call(p->r2chan);
03881    } else if (wants_double_answer) {
03882       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
03883    } else {
03884       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
03885    }
03886 #else
03887    res = openr2_chan_answer_call(p->r2chan);
03888 #endif
03889    return res;
03890 }
03891 
03892 
03893 
03894 /* should be called with the ast_channel locked */
03895 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
03896 {
03897    openr2_calling_party_category_t cat;
03898    const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
03899    struct dahdi_pvt *p = c->tech_pvt;
03900    if (ast_strlen_zero(catstr)) {
03901       ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
03902             c->name, openr2_proto_get_category_string(p->mfcr2_category));
03903       return p->mfcr2_category;
03904    }
03905    if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
03906       ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
03907             catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
03908       return p->mfcr2_category;
03909    }
03910    ast_debug(1, "Using category %s\n", catstr);
03911    return cat;
03912 }
03913 
03914 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
03915 {
03916    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03917    ast_mutex_lock(&p->lock);
03918    if (p->mfcr2call) {
03919       ast_mutex_unlock(&p->lock);
03920       /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
03921          interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
03922          can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
03923          the other end will see our seize as a forced release and drop the call, we will see an invalid
03924          pattern that will be seen and treated as protocol error. */
03925       ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
03926       return;
03927    }
03928    p->mfcr2call = 1;
03929    /* better safe than sorry ... */
03930    p->cid_name[0] = '\0';
03931    p->cid_num[0] = '\0';
03932    p->cid_subaddr[0] = '\0';
03933    p->rdnis[0] = '\0';
03934    p->exten[0] = '\0';
03935    p->mfcr2_ani_index = '\0';
03936    p->mfcr2_dnis_index = '\0';
03937    p->mfcr2_dnis_matched = 0;
03938    p->mfcr2_answer_pending = 0;
03939    p->mfcr2_call_accepted = 0;
03940    ast_mutex_unlock(&p->lock);
03941    ast_verbose("New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
03942 }
03943 
03944 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
03945 {
03946    int res;
03947    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03948    ast_mutex_lock(&p->lock);
03949    p->inalarm = alarm ? 1 : 0;
03950    if (p->inalarm) {
03951       res = get_alarms(p);
03952       handle_alarms(p, res);
03953    } else {
03954       handle_clear_alarms(p);
03955    }
03956    ast_mutex_unlock(&p->lock);
03957 }
03958 
03959 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
03960 {
03961    ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
03962 }
03963 
03964 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
03965 {
03966    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03967    ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
03968    if (p->owner) {
03969       p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
03970       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03971    }
03972    ast_mutex_lock(&p->lock);
03973    p->mfcr2call = 0;
03974    ast_mutex_unlock(&p->lock);
03975 }
03976 
03977 static void dahdi_r2_disconnect_call(struct dahdi_pvt *p, openr2_call_disconnect_cause_t cause)
03978 {
03979    if (openr2_chan_disconnect_call(p->r2chan, cause)) {
03980       ast_log(LOG_NOTICE, "Bad! failed to disconnect call on channel %d with reason %s, hope for the best!\n",
03981          p->channel, openr2_proto_get_disconnect_string(cause));
03982       /* force the chan to idle and release the call flag now since we will not see a clean on_call_end */
03983       openr2_chan_set_idle(p->r2chan);
03984       ast_mutex_lock(&p->lock);
03985       p->mfcr2call = 0;
03986       ast_mutex_unlock(&p->lock);
03987    }
03988 }
03989 
03990 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
03991 {
03992    struct dahdi_pvt *p;
03993    struct ast_channel *c;
03994    ast_verbose("MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
03995          openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
03996          openr2_proto_get_category_string(category));
03997    p = openr2_chan_get_client_data(r2chan);
03998    /* if collect calls are not allowed and this is a collect call, reject it! */
03999    if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
04000       ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
04001       dahdi_r2_disconnect_call(p, OR2_CAUSE_COLLECT_CALL_REJECTED);
04002       return;
04003    }
04004    ast_mutex_lock(&p->lock);
04005    p->mfcr2_recvd_category = category;
04006    /* if we're not supposed to use CID, clear whatever we have */
04007    if (!p->use_callerid) {
04008       ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
04009       p->cid_num[0] = 0;
04010       p->cid_name[0] = 0;
04011    }
04012    /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
04013    if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
04014       ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
04015       p->exten[0] = 's';
04016       p->exten[1] = 0;
04017    }
04018    ast_mutex_unlock(&p->lock);
04019    if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
04020       ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
04021             p->channel, p->exten, p->context);
04022       dahdi_r2_disconnect_call(p, OR2_CAUSE_UNALLOCATED_NUMBER);
04023       return;
04024    }
04025    if (!p->mfcr2_accept_on_offer) {
04026       /* The user wants us to start the PBX thread right away without accepting the call first */
04027       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
04028       if (c) {
04029          /* Done here, don't disable reading now since we still need to generate MF tones to accept
04030             the call or reject it and detect the tone off condition of the other end, all of this
04031             will be done in the PBX thread now */
04032          return;
04033       }
04034       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
04035       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
04036    } else if (p->mfcr2_charge_calls) {
04037       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
04038       openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
04039    } else {
04040       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
04041       openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
04042    }
04043 }
04044 
04045 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
04046 {
04047    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04048    ast_verbose("MFC/R2 call end on channel %d\n", p->channel);
04049    ast_mutex_lock(&p->lock);
04050    p->mfcr2call = 0;
04051    ast_mutex_unlock(&p->lock);
04052 }
04053 
04054 static void dahdi_enable_ec(struct dahdi_pvt *p);
04055 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
04056 {
04057    struct dahdi_pvt *p = NULL;
04058    struct ast_channel *c = NULL;
04059    p = openr2_chan_get_client_data(r2chan);
04060    dahdi_enable_ec(p);
04061    p->mfcr2_call_accepted = 1;
04062    /* if it's an incoming call ... */
04063    if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
04064       ast_verbose("MFC/R2 call has been accepted on backward channel %d\n", openr2_chan_get_number(r2chan));
04065       /* If accept on offer is not set, it means at this point the PBX thread is already
04066          launched (was launched in the 'on call offered' handler) and therefore this callback
04067          is being executed already in the PBX thread rather than the monitor thread, don't launch
04068          any other thread, just disable the openr2 reading and answer the call if needed */
04069       if (!p->mfcr2_accept_on_offer) {
04070          openr2_chan_disable_read(r2chan);
04071          if (p->mfcr2_answer_pending) {
04072             ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
04073             dahdi_r2_answer(p);
04074          }
04075          return;
04076       }
04077       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
04078       if (c) {
04079          /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
04080             library to forget about it */
04081          openr2_chan_disable_read(r2chan);
04082          return;
04083       }
04084       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
04085       /* failed to create the channel, bail out and report it as an out of order line */
04086       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
04087       return;
04088    }
04089    /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
04090    ast_verbose("MFC/R2 call has been accepted on forward channel %d\n", p->channel);
04091    p->subs[SUB_REAL].needringing = 1;
04092    p->dialing = 0;
04093    /* chan_dahdi will take care of reading from now on in the PBX thread, tell the library to forget about it */
04094    openr2_chan_disable_read(r2chan);
04095 }
04096 
04097 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
04098 {
04099    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04100    ast_verbose("MFC/R2 call has been answered on channel %d\n", openr2_chan_get_number(r2chan));
04101    p->subs[SUB_REAL].needanswer = 1;
04102 }
04103 
04104 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
04105 {
04106    /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
04107 }
04108 
04109 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
04110 {
04111    switch (cause) {
04112    case OR2_CAUSE_BUSY_NUMBER:
04113       return AST_CAUSE_BUSY;
04114    case OR2_CAUSE_NETWORK_CONGESTION:
04115       return AST_CAUSE_CONGESTION;
04116    case OR2_CAUSE_OUT_OF_ORDER:
04117       return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
04118    case OR2_CAUSE_UNALLOCATED_NUMBER:
04119       return AST_CAUSE_UNREGISTERED;
04120    case OR2_CAUSE_NO_ANSWER:
04121       return AST_CAUSE_NO_ANSWER;
04122    case OR2_CAUSE_NORMAL_CLEARING:
04123       return AST_CAUSE_NORMAL_CLEARING;
04124    case OR2_CAUSE_UNSPECIFIED:
04125    default:
04126       return AST_CAUSE_NOTDEFINED;
04127    }
04128 }
04129 
04130 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
04131 {
04132    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04133    ast_verbose("MFC/R2 call disconnected on channel %d\n", openr2_chan_get_number(r2chan));
04134    ast_mutex_lock(&p->lock);
04135    if (!p->owner) {
04136       ast_mutex_unlock(&p->lock);
04137       /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
04138       dahdi_r2_disconnect_call(p, OR2_CAUSE_NORMAL_CLEARING);
04139       return;
04140    }
04141    /* when we have an owner we don't call dahdi_r2_disconnect_call here, that will
04142       be done in dahdi_hangup */
04143    if (p->owner->_state == AST_STATE_UP) {
04144       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04145       ast_mutex_unlock(&p->lock);
04146    } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
04147       /* being the forward side we must report what happened to the call to whoever requested it */
04148       switch (cause) {
04149       case OR2_CAUSE_BUSY_NUMBER:
04150          p->subs[SUB_REAL].needbusy = 1;
04151          break;
04152       case OR2_CAUSE_NETWORK_CONGESTION:
04153       case OR2_CAUSE_OUT_OF_ORDER:
04154       case OR2_CAUSE_UNALLOCATED_NUMBER:
04155       case OR2_CAUSE_NO_ANSWER:
04156       case OR2_CAUSE_UNSPECIFIED:
04157       case OR2_CAUSE_NORMAL_CLEARING:
04158          p->subs[SUB_REAL].needcongestion = 1;
04159          break;
04160       default:
04161          p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
04162       }
04163       ast_mutex_unlock(&p->lock);
04164    } else {
04165       ast_mutex_unlock(&p->lock);
04166       /* being the backward side and not UP yet, we only need to request hangup */
04167       /* TODO: what about doing this same thing when were AST_STATE_UP? */
04168       ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
04169    }
04170 }
04171 
04172 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
04173 {
04174    switch (level) {
04175    case OR2_LOG_NOTICE:
04176       ast_verbose("%s", logmessage);
04177       break;
04178    case OR2_LOG_WARNING:
04179       ast_log(LOG_WARNING, "%s", logmessage);
04180       break;
04181    case OR2_LOG_ERROR:
04182       ast_log(LOG_ERROR, "%s", logmessage);
04183       break;
04184    case OR2_LOG_STACK_TRACE:
04185    case OR2_LOG_MF_TRACE:
04186    case OR2_LOG_CAS_TRACE:
04187    case OR2_LOG_DEBUG:
04188    case OR2_LOG_EX_DEBUG:
04189       ast_log(LOG_DEBUG, "%s", logmessage);
04190       break;
04191    default:
04192       ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
04193       ast_log(LOG_DEBUG, "%s", logmessage);
04194       break;
04195    }
04196 }
04197 
04198 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
04199 {
04200    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04201    ast_mutex_lock(&p->lock);
04202    p->remotelyblocked = 1;
04203    ast_mutex_unlock(&p->lock);
04204    ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
04205 }
04206 
04207 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
04208 {
04209    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04210    ast_mutex_lock(&p->lock);
04211    p->remotelyblocked = 0;
04212    ast_mutex_unlock(&p->lock);
04213    ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
04214 }
04215 
04216 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
04217    __attribute__((format (printf, 3, 0)));
04218 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
04219 {
04220 #define CONTEXT_TAG "Context - "
04221    char logmsg[256];
04222    char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
04223    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
04224    snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
04225    dahdi_r2_write_log(level, completemsg);
04226 #undef CONTEXT_TAG
04227 }
04228 
04229 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
04230    __attribute__((format (printf, 3, 0)));
04231 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
04232 {
04233 #define CHAN_TAG "Chan "
04234    char logmsg[256];
04235    char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
04236    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
04237    snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
04238    dahdi_r2_write_log(level, completemsg);
04239 }
04240 
04241 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
04242 {
04243    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04244    /* if 'immediate' is set, let's stop requesting DNIS */
04245    if (p->immediate) {
04246       return 0;
04247    }
04248    p->exten[p->mfcr2_dnis_index] = digit;
04249    p->rdnis[p->mfcr2_dnis_index] = digit;
04250    p->mfcr2_dnis_index++;
04251    p->exten[p->mfcr2_dnis_index] = 0;
04252    p->rdnis[p->mfcr2_dnis_index] = 0;
04253    /* if the DNIS is a match and cannot match more, stop requesting DNIS */
04254    if ((p->mfcr2_dnis_matched ||
04255        (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
04256        !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
04257       return 0;
04258    }
04259    /* otherwise keep going */
04260    return 1;
04261 }
04262 
04263 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
04264 {
04265    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04266    p->cid_num[p->mfcr2_ani_index] = digit;
04267    p->cid_name[p->mfcr2_ani_index] = digit;
04268    p->mfcr2_ani_index++;
04269    p->cid_num[p->mfcr2_ani_index] = 0;
04270    p->cid_name[p->mfcr2_ani_index] = 0;
04271 }
04272 
04273 static void dahdi_r2_on_billing_pulse_received(openr2_chan_t *r2chan)
04274 {
04275    ast_verbose("MFC/R2 billing pulse received on channel %d\n", openr2_chan_get_number(r2chan));
04276 }
04277 
04278 static openr2_event_interface_t dahdi_r2_event_iface = {
04279    .on_call_init = dahdi_r2_on_call_init,
04280    .on_call_offered = dahdi_r2_on_call_offered,
04281    .on_call_accepted = dahdi_r2_on_call_accepted,
04282    .on_call_answered = dahdi_r2_on_call_answered,
04283    .on_call_disconnect = dahdi_r2_on_call_disconnect,
04284    .on_call_end = dahdi_r2_on_call_end,
04285    .on_call_read = dahdi_r2_on_call_read,
04286    .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
04287    .on_os_error = dahdi_r2_on_os_error,
04288    .on_protocol_error = dahdi_r2_on_protocol_error,
04289    .on_line_blocked = dahdi_r2_on_line_blocked,
04290    .on_line_idle = dahdi_r2_on_line_idle,
04291    /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
04292    .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
04293    .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
04294    .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
04295    /* so far we do nothing with billing pulses */
04296    .on_billing_pulse_received = dahdi_r2_on_billing_pulse_received
04297 };
04298 
04299 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
04300 {
04301    return AST_ALAW(sample);
04302 }
04303 
04304 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
04305 {
04306    return AST_LIN2A(sample);
04307 }
04308 
04309 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
04310    dahdi_r2_alaw_to_linear,
04311    dahdi_r2_linear_to_alaw
04312 };
04313 
04314 #endif /* HAVE_OPENR2 */
04315 
04316 static void swap_subs(struct dahdi_pvt *p, int a, int b)
04317 {
04318    int tchan;
04319    int tinthreeway;
04320    struct ast_channel *towner;
04321 
04322    ast_debug(1, "Swapping %d and %d\n", a, b);
04323 
04324    tchan = p->subs[a].chan;
04325    towner = p->subs[a].owner;
04326    tinthreeway = p->subs[a].inthreeway;
04327 
04328    p->subs[a].chan = p->subs[b].chan;
04329    p->subs[a].owner = p->subs[b].owner;
04330    p->subs[a].inthreeway = p->subs[b].inthreeway;
04331 
04332    p->subs[b].chan = tchan;
04333    p->subs[b].owner = towner;
04334    p->subs[b].inthreeway = tinthreeway;
04335 
04336    if (p->subs[a].owner)
04337       ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
04338    if (p->subs[b].owner)
04339       ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
04340    wakeup_sub(p, a);
04341    wakeup_sub(p, b);
04342 }
04343 
04344 static int dahdi_open(char *fn)
04345 {
04346    int fd;
04347    int isnum;
04348    int chan = 0;
04349    int bs;
04350    int x;
04351    isnum = 1;
04352    for (x = 0; x < strlen(fn); x++) {
04353       if (!isdigit(fn[x])) {
04354          isnum = 0;
04355          break;
04356       }
04357    }
04358    if (isnum) {
04359       chan = atoi(fn);
04360       if (chan < 1) {
04361          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
04362          return -1;
04363       }
04364       fn = "/dev/dahdi/channel";
04365    }
04366    fd = open(fn, O_RDWR | O_NONBLOCK);
04367    if (fd < 0) {
04368       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
04369       return -1;
04370    }
04371    if (chan) {
04372       if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
04373          x = errno;
04374          close(fd);
04375          errno = x;
04376          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
04377          return -1;
04378       }
04379    }
04380    bs = READ_SIZE;
04381    if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
04382       ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
04383       x = errno;
04384       close(fd);
04385       errno = x;
04386       return -1;
04387    }
04388    return fd;
04389 }
04390 
04391 static void dahdi_close(int fd)
04392 {
04393    if (fd > 0)
04394       close(fd);
04395 }
04396 
04397 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
04398 {
04399    dahdi_close(chan_pvt->subs[sub_num].dfd);
04400    chan_pvt->subs[sub_num].dfd = -1;
04401 }
04402 
04403 #if defined(HAVE_PRI)
04404 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
04405 {
04406    dahdi_close(pri->pri.fds[fd_num]);
04407    pri->pri.fds[fd_num] = -1;
04408 }
04409 #endif   /* defined(HAVE_PRI) */
04410 
04411 #if defined(HAVE_SS7)
04412 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
04413 {
04414    dahdi_close(ss7->ss7.fds[fd_num]);
04415    ss7->ss7.fds[fd_num] = -1;
04416 }
04417 #endif   /* defined(HAVE_SS7) */
04418 
04419 static int dahdi_setlinear(int dfd, int linear)
04420 {
04421    return ioctl(dfd, DAHDI_SETLINEAR, &linear);
04422 }
04423 
04424 
04425 static int alloc_sub(struct dahdi_pvt *p, int x)
04426 {
04427    struct dahdi_bufferinfo bi;
04428    int res;
04429    if (p->subs[x].dfd >= 0) {
04430       ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
04431       return -1;
04432    }
04433 
04434    p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
04435    if (p->subs[x].dfd <= -1) {
04436       ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
04437       return -1;
04438    }
04439 
04440    res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
04441    if (!res) {
04442       bi.txbufpolicy = p->buf_policy;
04443       bi.rxbufpolicy = p->buf_policy;
04444       bi.numbufs = p->buf_no;
04445       res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
04446       if (res < 0) {
04447          ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
04448       }
04449    } else
04450       ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
04451 
04452    if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
04453       ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
04454       dahdi_close_sub(p, x);
04455       p->subs[x].dfd = -1;
04456       return -1;
04457    }
04458    ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
04459    return 0;
04460 }
04461 
04462 static int unalloc_sub(struct dahdi_pvt *p, int x)
04463 {
04464    if (!x) {
04465       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
04466       return -1;
04467    }
04468    ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
04469    dahdi_close_sub(p, x);
04470    p->subs[x].linear = 0;
04471    p->subs[x].chan = 0;
04472    p->subs[x].owner = NULL;
04473    p->subs[x].inthreeway = 0;
04474    p->polarity = POLARITY_IDLE;
04475    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
04476    return 0;
04477 }
04478 
04479 static int digit_to_dtmfindex(char digit)
04480 {
04481    if (isdigit(digit))
04482       return DAHDI_TONE_DTMF_BASE + (digit - '0');
04483    else if (digit >= 'A' && digit <= 'D')
04484       return DAHDI_TONE_DTMF_A + (digit - 'A');
04485    else if (digit >= 'a' && digit <= 'd')
04486       return DAHDI_TONE_DTMF_A + (digit - 'a');
04487    else if (digit == '*')
04488       return DAHDI_TONE_DTMF_s;
04489    else if (digit == '#')
04490       return DAHDI_TONE_DTMF_p;
04491    else
04492       return -1;
04493 }
04494 
04495 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
04496 {
04497    struct dahdi_pvt *pvt;
04498    int idx;
04499    int dtmf = -1;
04500    int res;
04501 
04502    pvt = chan->tech_pvt;
04503 
04504    ast_mutex_lock(&pvt->lock);
04505 
04506    idx = dahdi_get_index(chan, pvt, 0);
04507 
04508    if ((idx != SUB_REAL) || !pvt->owner)
04509       goto out;
04510 
04511 #ifdef HAVE_PRI
04512    switch (pvt->sig) {
04513    case SIG_PRI_LIB_HANDLE_CASES:
04514       res = sig_pri_digit_begin(pvt->sig_pvt, chan, digit);
04515       if (!res)
04516          goto out;
04517       break;
04518    default:
04519       break;
04520    }
04521 #endif
04522    if ((dtmf = digit_to_dtmfindex(digit)) == -1)
04523       goto out;
04524 
04525    if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
04526       struct dahdi_dialoperation zo = {
04527          .op = DAHDI_DIAL_OP_APPEND,
04528       };
04529 
04530       zo.dialstr[0] = 'T';
04531       zo.dialstr[1] = digit;
04532       zo.dialstr[2] = '\0';
04533       if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
04534          ast_log(LOG_WARNING, "Channel %s couldn't dial digit %c: %s\n",
04535             chan->name, digit, strerror(errno));
04536       else
04537          pvt->dialing = 1;
04538    } else {
04539       ast_debug(1, "Channel %s started VLDTMF digit '%c'\n",
04540          chan->name, digit);
04541       pvt->dialing = 1;
04542       pvt->begindigit = digit;
04543    }
04544 
04545 out:
04546    ast_mutex_unlock(&pvt->lock);
04547 
04548    return 0;
04549 }
04550 
04551 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
04552 {
04553    struct dahdi_pvt *pvt;
04554    int res = 0;
04555    int idx;
04556    int x;
04557 
04558    pvt = chan->tech_pvt;
04559 
04560    ast_mutex_lock(&pvt->lock);
04561 
04562    idx = dahdi_get_index(chan, pvt, 0);
04563 
04564    if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
04565       goto out;
04566 
04567 #ifdef HAVE_PRI
04568    /* This means that the digit was already sent via PRI signalling */
04569    if (dahdi_sig_pri_lib_handles(pvt->sig) && !pvt->begindigit) {
04570       goto out;
04571    }
04572 #endif
04573 
04574    if (pvt->begindigit) {
04575       x = -1;
04576       ast_debug(1, "Channel %s ending VLDTMF digit '%c'\n",
04577          chan->name, digit);
04578       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
04579       pvt->dialing = 0;
04580       pvt->begindigit = 0;
04581    }
04582 
04583 out:
04584    ast_mutex_unlock(&pvt->lock);
04585 
04586    return res;
04587 }
04588 
04589 static const char * const events[] = {
04590    "No event",
04591    "On hook",
04592    "Ring/Answered",
04593    "Wink/Flash",
04594    "Alarm",
04595    "No more alarm",
04596    "HDLC Abort",
04597    "HDLC Overrun",
04598    "HDLC Bad FCS",
04599    "Dial Complete",
04600    "Ringer On",
04601    "Ringer Off",
04602    "Hook Transition Complete",
04603    "Bits Changed",
04604    "Pulse Start",
04605    "Timer Expired",
04606    "Timer Ping",
04607    "Polarity Reversal",
04608    "Ring Begin",
04609 };
04610 
04611 static struct {
04612    int alarm;
04613    char *name;
04614 } alarms[] = {
04615    { DAHDI_ALARM_RED, "Red Alarm" },
04616    { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
04617    { DAHDI_ALARM_BLUE, "Blue Alarm" },
04618    { DAHDI_ALARM_RECOVER, "Recovering" },
04619    { DAHDI_ALARM_LOOPBACK, "Loopback" },
04620    { DAHDI_ALARM_NOTOPEN, "Not Open" },
04621    { DAHDI_ALARM_NONE, "None" },
04622 };
04623 
04624 static char *alarm2str(int alm)
04625 {
04626    int x;
04627    for (x = 0; x < ARRAY_LEN(alarms); x++) {
04628       if (alarms[x].alarm & alm)
04629          return alarms[x].name;
04630    }
04631    return alm ? "Unknown Alarm" : "No Alarm";
04632 }
04633 
04634 static const char *event2str(int event)
04635 {
04636    static char buf[256];
04637    if ((event < (ARRAY_LEN(events))) && (event > -1))
04638       return events[event];
04639    sprintf(buf, "Event %d", event); /* safe */
04640    return buf;
04641 }
04642 
04643 static char *dahdi_sig2str(int sig)
04644 {
04645    static char buf[256];
04646    switch (sig) {
04647    case SIG_EM:
04648       return "E & M Immediate";
04649    case SIG_EMWINK:
04650       return "E & M Wink";
04651    case SIG_EM_E1:
04652       return "E & M E1";
04653    case SIG_FEATD:
04654       return "Feature Group D (DTMF)";
04655    case SIG_FEATDMF:
04656       return "Feature Group D (MF)";
04657    case SIG_FEATDMF_TA:
04658       return "Feature Groud D (MF) Tandem Access";
04659    case SIG_FEATB:
04660       return "Feature Group B (MF)";
04661    case SIG_E911:
04662       return "E911 (MF)";
04663    case SIG_FGC_CAMA:
04664       return "FGC/CAMA (Dialpulse)";
04665    case SIG_FGC_CAMAMF:
04666       return "FGC/CAMA (MF)";
04667    case SIG_FXSLS:
04668       return "FXS Loopstart";
04669    case SIG_FXSGS:
04670       return "FXS Groundstart";
04671    case SIG_FXSKS:
04672       return "FXS Kewlstart";
04673    case SIG_FXOLS:
04674       return "FXO Loopstart";
04675    case SIG_FXOGS:
04676       return "FXO Groundstart";
04677    case SIG_FXOKS:
04678       return "FXO Kewlstart";
04679    case SIG_PRI:
04680       return "ISDN PRI";
04681    case SIG_BRI:
04682       return "ISDN BRI Point to Point";
04683    case SIG_BRI_PTMP:
04684       return "ISDN BRI Point to MultiPoint";
04685    case SIG_SS7:
04686       return "SS7";
04687    case SIG_MFCR2:
04688       return "MFC/R2";
04689    case SIG_SF:
04690       return "SF (Tone) Immediate";
04691    case SIG_SFWINK:
04692       return "SF (Tone) Wink";
04693    case SIG_SF_FEATD:
04694       return "SF (Tone) with Feature Group D (DTMF)";
04695    case SIG_SF_FEATDMF:
04696       return "SF (Tone) with Feature Group D (MF)";
04697    case SIG_SF_FEATB:
04698       return "SF (Tone) with Feature Group B (MF)";
04699    case 0:
04700       return "Pseudo";
04701    default:
04702       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
04703       return buf;
04704    }
04705 }
04706 
04707 #define sig2str dahdi_sig2str
04708 
04709 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
04710 {
04711    /* If the conference already exists, and we're already in it
04712       don't bother doing anything */
04713    struct dahdi_confinfo zi;
04714 
04715    memset(&zi, 0, sizeof(zi));
04716    zi.chan = 0;
04717 
04718    if (slavechannel > 0) {
04719       /* If we have only one slave, do a digital mon */
04720       zi.confmode = DAHDI_CONF_DIGITALMON;
04721       zi.confno = slavechannel;
04722    } else {
04723       if (!idx) {
04724          /* Real-side and pseudo-side both participate in conference */
04725          zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
04726             DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
04727       } else
04728          zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
04729       zi.confno = p->confno;
04730    }
04731    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
04732       return 0;
04733    if (c->dfd < 0)
04734       return 0;
04735    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04736       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
04737       return -1;
04738    }
04739    if (slavechannel < 1) {
04740       p->confno = zi.confno;
04741    }
04742    c->curconf = zi;
04743    ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04744    return 0;
04745 }
04746 
04747 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
04748 {
04749    /* If they're listening to our channel, they're ours */
04750    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
04751       return 1;
04752    /* If they're a talker on our (allocated) conference, they're ours */
04753    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
04754       return 1;
04755    return 0;
04756 }
04757 
04758 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
04759 {
04760    struct dahdi_confinfo zi;
04761    if (/* Can't delete if there's no dfd */
04762       (c->dfd < 0) ||
04763       /* Don't delete from the conference if it's not our conference */
04764       !isourconf(p, c)
04765       /* Don't delete if we don't think it's conferenced at all (implied) */
04766       ) return 0;
04767    memset(&zi, 0, sizeof(zi));
04768    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04769       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
04770       return -1;
04771    }
04772    ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04773    memcpy(&c->curconf, &zi, sizeof(c->curconf));
04774    return 0;
04775 }
04776 
04777 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
04778 {
04779    int x;
04780    int useslavenative;
04781    struct dahdi_pvt *slave = NULL;
04782    /* Start out optimistic */
04783    useslavenative = 1;
04784    /* Update conference state in a stateless fashion */
04785    for (x = 0; x < 3; x++) {
04786       /* Any three-way calling makes slave native mode *definitely* out
04787          of the question */
04788       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
04789          useslavenative = 0;
04790    }
04791    /* If we don't have any 3-way calls, check to see if we have
04792       precisely one slave */
04793    if (useslavenative) {
04794       for (x = 0; x < MAX_SLAVES; x++) {
04795          if (p->slaves[x]) {
04796             if (slave) {
04797                /* Whoops already have a slave!  No
04798                   slave native and stop right away */
04799                slave = NULL;
04800                useslavenative = 0;
04801                break;
04802             } else {
04803                /* We have one slave so far */
04804                slave = p->slaves[x];
04805             }
04806          }
04807       }
04808    }
04809    /* If no slave, slave native definitely out */
04810    if (!slave)
04811       useslavenative = 0;
04812    else if (slave->law != p->law) {
04813       useslavenative = 0;
04814       slave = NULL;
04815    }
04816    if (out)
04817       *out = slave;
04818    return useslavenative;
04819 }
04820 
04821 static int reset_conf(struct dahdi_pvt *p)
04822 {
04823    p->confno = -1;
04824    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
04825    if (p->subs[SUB_REAL].dfd > -1) {
04826       struct dahdi_confinfo zi;
04827 
04828       memset(&zi, 0, sizeof(zi));
04829       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
04830          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
04831    }
04832    return 0;
04833 }
04834 
04835 static int update_conf(struct dahdi_pvt *p)
04836 {
04837    int needconf = 0;
04838    int x;
04839    int useslavenative;
04840    struct dahdi_pvt *slave = NULL;
04841 
04842    useslavenative = isslavenative(p, &slave);
04843    /* Start with the obvious, general stuff */
04844    for (x = 0; x < 3; x++) {
04845       /* Look for three way calls */
04846       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
04847          conf_add(p, &p->subs[x], x, 0);
04848          needconf++;
04849       } else {
04850          conf_del(p, &p->subs[x], x);
04851       }
04852    }
04853    /* If we have a slave, add him to our conference now. or DAX
04854       if this is slave native */
04855    for (x = 0; x < MAX_SLAVES; x++) {
04856       if (p->slaves[x]) {
04857          if (useslavenative)
04858             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
04859          else {
04860             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
04861             needconf++;
04862          }
04863       }
04864    }
04865    /* If we're supposed to be in there, do so now */
04866    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
04867       if (useslavenative)
04868          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
04869       else {
04870          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
04871          needconf++;
04872       }
04873    }
04874    /* If we have a master, add ourselves to his conference */
04875    if (p->master) {
04876       if (isslavenative(p->master, NULL)) {
04877          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
04878       } else {
04879          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
04880       }
04881    }
04882    if (!needconf) {
04883       /* Nobody is left (or should be left) in our conference.
04884          Kill it. */
04885       p->confno = -1;
04886    }
04887    ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
04888    return 0;
04889 }
04890 
04891 static void dahdi_enable_ec(struct dahdi_pvt *p)
04892 {
04893    int res;
04894    if (!p)
04895       return;
04896    if (p->echocanon) {
04897       ast_debug(1, "Echo cancellation already on\n");
04898       return;
04899    }
04900    if (p->digital) {
04901       ast_debug(1, "Echo cancellation isn't required on digital connection\n");
04902       return;
04903    }
04904    if (p->echocancel.head.tap_length) {
04905 #if defined(HAVE_PRI) || defined(HAVE_SS7)
04906       switch (p->sig) {
04907 #if defined(HAVE_PRI)
04908       case SIG_PRI_LIB_HANDLE_CASES:
04909          if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
04910             /*
04911              * PRI nobch pseudo channel.  Does not need ec anyway.
04912              * Does not handle ioctl(DAHDI_AUDIOMODE)
04913              */
04914             return;
04915          }
04916          /* Fall through */
04917 #endif   /* defined(HAVE_PRI) */
04918 #if defined(HAVE_SS7)
04919       case SIG_SS7:
04920 #endif   /* defined(HAVE_SS7) */
04921          {
04922             int x = 1;
04923 
04924             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
04925             if (res)
04926                ast_log(LOG_WARNING,
04927                   "Unable to enable audio mode on channel %d (%s)\n",
04928                   p->channel, strerror(errno));
04929          }
04930          break;
04931       default:
04932          break;
04933       }
04934 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
04935       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
04936       if (res) {
04937          ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
04938       } else {
04939          p->echocanon = 1;
04940          ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
04941       }
04942    } else
04943       ast_debug(1, "No echo cancellation requested\n");
04944 }
04945 
04946 static void dahdi_train_ec(struct dahdi_pvt *p)
04947 {
04948    int x;
04949    int res;
04950 
04951    if (p && p->echocanon && p->echotraining) {
04952       x = p->echotraining;
04953       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
04954       if (res)
04955          ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
04956       else
04957          ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
04958    } else {
04959       ast_debug(1, "No echo training requested\n");
04960    }
04961 }
04962 
04963 static void dahdi_disable_ec(struct dahdi_pvt *p)
04964 {
04965    int res;
04966 
04967    if (p->echocanon) {
04968       struct dahdi_echocanparams ecp = { .tap_length = 0 };
04969 
04970       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
04971 
04972       if (res)
04973          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
04974       else
04975          ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
04976    }
04977 
04978    p->echocanon = 0;
04979 }
04980 
04981 /* perform a dynamic range compression transform on the given sample */
04982 static int drc_sample(int sample, float drc)
04983 {
04984    float neg;
04985    float shallow, steep;
04986    float max = SHRT_MAX;
04987    
04988    neg = (sample < 0 ? -1 : 1);
04989    steep = drc*sample;
04990    shallow = neg*(max-max/drc)+(float)sample/drc;
04991    if (abs(steep) < abs(shallow)) {
04992       sample = steep;
04993    }
04994    else {
04995       sample = shallow;
04996    }
04997 
04998    return sample;
04999 }
05000 
05001 
05002 static void fill_txgain(struct dahdi_gains *g, float gain, float drc, int law)
05003 {
05004    int j;
05005    int k;
05006 
05007    float linear_gain = pow(10.0, gain / 20.0);
05008 
05009    switch (law) {
05010    case DAHDI_LAW_ALAW:
05011       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
05012          if (gain || drc) {
05013             k = AST_ALAW(j);
05014             if (drc) {
05015                k = drc_sample(k, drc);
05016             }
05017             k = (float)k*linear_gain;
05018             if (k > 32767) k = 32767;
05019             if (k < -32767) k = -32767;
05020             g->txgain[j] = AST_LIN2A(k);
05021          } else {
05022             g->txgain[j] = j;
05023          }
05024       }
05025       break;
05026    case DAHDI_LAW_MULAW:
05027       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
05028          if (gain || drc) {
05029             k = AST_MULAW(j);
05030             if (drc) {
05031                k = drc_sample(k, drc);
05032             }
05033             k = (float)k*linear_gain;
05034             if (k > 32767) k = 32767;
05035             if (k < -32767) k = -32767;
05036             g->txgain[j] = AST_LIN2MU(k);
05037 
05038          } else {
05039             g->txgain[j] = j;
05040          }
05041       }
05042       break;
05043    }
05044 }
05045 
05046 static void fill_rxgain(struct dahdi_gains *g, float gain, float drc, int law)
05047 {
05048    int j;
05049    int k;
05050    float linear_gain = pow(10.0, gain / 20.0);
05051 
05052    switch (law) {
05053    case DAHDI_LAW_ALAW:
05054       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
05055          if (gain || drc) {
05056             k = AST_ALAW(j);
05057             if (drc) {
05058                k = drc_sample(k, drc);
05059             }
05060             k = (float)k*linear_gain;
05061             if (k > 32767) k = 32767;
05062             if (k < -32767) k = -32767;
05063             g->rxgain[j] = AST_LIN2A(k);
05064          } else {
05065             g->rxgain[j] = j;
05066          }
05067       }
05068       break;
05069    case DAHDI_LAW_MULAW:
05070       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
05071          if (gain || drc) {
05072             k = AST_MULAW(j);
05073             if (drc) {
05074                k = drc_sample(k, drc);
05075             }
05076             k = (float)k*linear_gain;
05077             if (k > 32767) k = 32767;
05078             if (k < -32767) k = -32767;
05079             g->rxgain[j] = AST_LIN2MU(k);
05080          } else {
05081             g->rxgain[j] = j;
05082          }
05083       }
05084       break;
05085    }
05086 }
05087 
05088 static int set_actual_txgain(int fd, float gain, float drc, int law)
05089 {
05090    struct dahdi_gains g;
05091    int res;
05092 
05093    memset(&g, 0, sizeof(g));
05094    res = ioctl(fd, DAHDI_GETGAINS, &g);
05095    if (res) {
05096       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
05097       return res;
05098    }
05099 
05100    fill_txgain(&g, gain, drc, law);
05101 
05102    return ioctl(fd, DAHDI_SETGAINS, &g);
05103 }
05104 
05105 static int set_actual_rxgain(int fd, float gain, float drc, int law)
05106 {
05107    struct dahdi_gains g;
05108    int res;
05109 
05110    memset(&g, 0, sizeof(g));
05111    res = ioctl(fd, DAHDI_GETGAINS, &g);
05112    if (res) {
05113       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
05114       return res;
05115    }
05116 
05117    fill_rxgain(&g, gain, drc, law);
05118 
05119    return ioctl(fd, DAHDI_SETGAINS, &g);
05120 }
05121 
05122 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law)
05123 {
05124    return set_actual_txgain(fd, txgain, txdrc, law) | set_actual_rxgain(fd, rxgain, rxdrc, law);
05125 }
05126 
05127 static int bump_gains(struct dahdi_pvt *p)
05128 {
05129    int res;
05130 
05131    /* Bump receive gain by value stored in cid_rxgain */
05132    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain + p->cid_rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05133    if (res) {
05134       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
05135       return -1;
05136    }
05137 
05138    return 0;
05139 }
05140 
05141 static int restore_gains(struct dahdi_pvt *p)
05142 {
05143    int res;
05144 
05145    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05146    if (res) {
05147       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
05148       return -1;
05149    }
05150 
05151    return 0;
05152 }
05153 
05154 static inline int dahdi_set_hook(int fd, int hs)
05155 {
05156    int x, res;
05157 
05158    x = hs;
05159    res = ioctl(fd, DAHDI_HOOK, &x);
05160 
05161    if (res < 0) {
05162       if (errno == EINPROGRESS)
05163          return 0;
05164       ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
05165       /* will expectedly fail if phone is off hook during operation, such as during a restart */
05166    }
05167 
05168    return res;
05169 }
05170 
05171 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
05172 {
05173    int x, res;
05174 
05175    x = muted;
05176 #if defined(HAVE_PRI) || defined(HAVE_SS7)
05177    switch (p->sig) {
05178 #if defined(HAVE_PRI)
05179    case SIG_PRI_LIB_HANDLE_CASES:
05180       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
05181          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
05182          break;
05183       }
05184       /* Fall through */
05185 #endif   /* defined(HAVE_PRI) */
05186 #if defined(HAVE_SS7)
05187    case SIG_SS7:
05188 #endif   /* defined(HAVE_SS7) */
05189       {
05190          int y = 1;
05191 
05192          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
05193          if (res)
05194             ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n",
05195                p->channel, strerror(errno));
05196       }
05197       break;
05198    default:
05199       break;
05200    }
05201 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
05202    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
05203    if (res < 0)
05204       ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
05205    return res;
05206 }
05207 
05208 static int save_conference(struct dahdi_pvt *p)
05209 {
05210    struct dahdi_confinfo c;
05211    int res;
05212    if (p->saveconf.confmode) {
05213       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
05214       return -1;
05215    }
05216    p->saveconf.chan = 0;
05217    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
05218    if (res) {
05219       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
05220       p->saveconf.confmode = 0;
05221       return -1;
05222    }
05223    memset(&c, 0, sizeof(c));
05224    c.confmode = DAHDI_CONF_NORMAL;
05225    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
05226    if (res) {
05227       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
05228       return -1;
05229    }
05230    ast_debug(1, "Disabled conferencing\n");
05231    return 0;
05232 }
05233 
05234 static int restore_conference(struct dahdi_pvt *p)
05235 {
05236    int res;
05237    if (p->saveconf.confmode) {
05238       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
05239       p->saveconf.confmode = 0;
05240       if (res) {
05241          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
05242          return -1;
05243       }
05244       ast_debug(1, "Restored conferencing\n");
05245    }
05246    return 0;
05247 }
05248 
05249 static int send_cwcidspill(struct dahdi_pvt *p)
05250 {
05251    p->callwaitcas = 0;
05252    p->cidcwexpire = 0;
05253    p->cid_suppress_expire = 0;
05254    if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
05255       return -1;
05256    p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
05257    /* Make sure we account for the end */
05258    p->cidlen += READ_SIZE * 4;
05259    p->cidpos = 0;
05260    send_callerid(p);
05261    ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
05262    return 0;
05263 }
05264 
05265 static int has_voicemail(struct dahdi_pvt *p)
05266 {
05267    int new_msgs;
05268    struct ast_event *event;
05269    char *mailbox, *context;
05270 
05271    mailbox = context = ast_strdupa(p->mailbox);
05272    strsep(&context, "@");
05273    if (ast_strlen_zero(context))
05274       context = "default";
05275 
05276    event = ast_event_get_cached(AST_EVENT_MWI,
05277       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
05278       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
05279       AST_EVENT_IE_END);
05280 
05281    if (event) {
05282       new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
05283       ast_event_destroy(event);
05284    } else
05285       new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
05286 
05287    return new_msgs;
05288 }
05289 
05290 
05291 
05292 static int send_callerid(struct dahdi_pvt *p)
05293 {
05294    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
05295    int res;
05296    /* Take out of linear mode if necessary */
05297    if (p->subs[SUB_REAL].linear) {
05298       p->subs[SUB_REAL].linear = 0;
05299       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
05300    }
05301    while (p->cidpos < p->cidlen) {
05302       res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
05303       ast_debug(4, "writing callerid at pos %d of %d, res = %d\n", p->cidpos, p->cidlen, res);
05304       if (res < 0) {
05305          if (errno == EAGAIN)
05306             return 0;
05307          else {
05308             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
05309             return -1;
05310          }
05311       }
05312       if (!res)
05313          return 0;
05314       p->cidpos += res;
05315    }
05316    p->cid_suppress_expire = CALLWAITING_SUPPRESS_SAMPLES;
05317    ast_free(p->cidspill);
05318    p->cidspill = NULL;
05319    if (p->callwaitcas) {
05320       /* Wait for CID/CW to expire */
05321       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
05322       p->cid_suppress_expire = p->cidcwexpire;
05323    } else
05324       restore_conference(p);
05325    return 0;
05326 }
05327 
05328 static int dahdi_callwait(struct ast_channel *ast)
05329 {
05330    struct dahdi_pvt *p = ast->tech_pvt;
05331    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
05332    if (p->cidspill) {
05333       ast_log(LOG_WARNING, "Spill already exists?!?\n");
05334       ast_free(p->cidspill);
05335    }
05336 
05337    /*
05338     * SAS: Subscriber Alert Signal, 440Hz for 300ms
05339     * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
05340     */
05341    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
05342       return -1;
05343    save_conference(p);
05344    /* Silence */
05345    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
05346    if (!p->callwaitrings && p->callwaitingcallerid) {
05347       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
05348       p->callwaitcas = 1;
05349       p->cidlen = 2400 + 680 + READ_SIZE * 4;
05350    } else {
05351       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
05352       p->callwaitcas = 0;
05353       p->cidlen = 2400 + READ_SIZE * 4;
05354    }
05355    p->cidpos = 0;
05356    send_callerid(p);
05357 
05358    return 0;
05359 }
05360 
05361 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
05362 {
05363    struct dahdi_pvt *p = ast->tech_pvt;
05364    int x, res, mysig;
05365    char dest[256]; /* must be same length as p->dialdest */
05366 
05367    ast_mutex_lock(&p->lock);
05368    ast_copy_string(dest, rdest, sizeof(dest));
05369    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
05370    if ((ast->_state == AST_STATE_BUSY)) {
05371       p->subs[SUB_REAL].needbusy = 1;
05372       ast_mutex_unlock(&p->lock);
05373       return 0;
05374    }
05375    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05376       ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
05377       ast_mutex_unlock(&p->lock);
05378       return -1;
05379    }
05380    p->waitingfordt.tv_sec = 0;
05381    p->dialednone = 0;
05382    if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
05383    {
05384       /* Special pseudo -- automatically up */
05385       ast_setstate(ast, AST_STATE_UP);
05386       ast_mutex_unlock(&p->lock);
05387       return 0;
05388    }
05389    x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
05390    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
05391    if (res)
05392       ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
05393    p->outgoing = 1;
05394 
05395    if (IS_DIGITAL(ast->transfercapability)){
05396       set_actual_gain(p->subs[SUB_REAL].dfd, 0, 0, p->rxdrc, p->txdrc, p->law);
05397    } else {
05398       set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05399    }  
05400 
05401 #ifdef HAVE_PRI
05402    if (dahdi_sig_pri_lib_handles(p->sig)) {
05403       res = sig_pri_call(p->sig_pvt, ast, rdest, timeout,
05404          (p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW);
05405       ast_mutex_unlock(&p->lock);
05406       return res;
05407    }
05408 #endif
05409 
05410 #if defined(HAVE_SS7)
05411    if (p->sig == SIG_SS7) {
05412       res = sig_ss7_call(p->sig_pvt, ast, rdest);
05413       ast_mutex_unlock(&p->lock);
05414       return res;
05415    }
05416 #endif   /* defined(HAVE_SS7) */
05417 
05418    /* If this is analog signalling we can exit here */
05419    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
05420       p->callwaitrings = 0;
05421       res = analog_call(p->sig_pvt, ast, rdest, timeout);
05422       ast_mutex_unlock(&p->lock);
05423       return res;
05424    }
05425 
05426    mysig = p->outsigmod > -1 ? p->outsigmod : p->sig;
05427    switch (mysig) {
05428    case 0:
05429       /* Special pseudo -- automatically up*/
05430       ast_setstate(ast, AST_STATE_UP);
05431       break;
05432    case SIG_MFCR2:
05433       break;
05434    default:
05435       ast_debug(1, "not yet implemented\n");
05436       ast_mutex_unlock(&p->lock);
05437       return -1;
05438    }
05439 
05440 #ifdef HAVE_OPENR2
05441    if (p->mfcr2) {
05442       openr2_calling_party_category_t chancat;
05443       int callres = 0;
05444       char *c, *l;
05445 
05446       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
05447       p->dialdest[0] = '\0';
05448 
05449       c = strchr(dest, '/');
05450       if (c) {
05451          c++;
05452       } else {
05453          c = "";
05454       }
05455       if (!p->hidecallerid) {
05456          l = ast->connected.id.number.valid ? ast->connected.id.number.str : NULL;
05457       } else {
05458          l = NULL;
05459       }
05460       if (strlen(c) < p->stripmsd) {
05461          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
05462          ast_mutex_unlock(&p->lock);
05463          return -1;
05464       }
05465       p->dialing = 1;
05466       chancat = dahdi_r2_get_channel_category(ast);
05467       callres = openr2_chan_make_call(p->r2chan, l, (c + p->stripmsd), chancat);
05468       if (-1 == callres) {
05469          ast_mutex_unlock(&p->lock);
05470          ast_log(LOG_ERROR, "unable to make new MFC/R2 call!\n");
05471          return -1;
05472       }
05473       p->mfcr2_call_accepted = 0;
05474       p->mfcr2_progress = 0;
05475       ast_setstate(ast, AST_STATE_DIALING);
05476    }
05477 #endif /* HAVE_OPENR2 */
05478    ast_mutex_unlock(&p->lock);
05479    return 0;
05480 }
05481 
05482 /*!
05483  * \internal
05484  * \brief Insert the given chan_dahdi interface structure into the interface list.
05485  * \since 1.8
05486  *
05487  * \param pvt chan_dahdi private interface structure to insert.
05488  *
05489  * \details
05490  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05491  * Any duplicates are inserted after the existing entries.
05492  *
05493  * \note The new interface must not already be in the list.
05494  *
05495  * \return Nothing
05496  */
05497 static void dahdi_iflist_insert(struct dahdi_pvt *pvt)
05498 {
05499    struct dahdi_pvt *cur;
05500 
05501    pvt->which_iflist = DAHDI_IFLIST_MAIN;
05502 
05503    /* Find place in middle of list for the new interface. */
05504    for (cur = iflist; cur; cur = cur->next) {
05505       if (pvt->channel < cur->channel) {
05506          /* New interface goes before the current interface. */
05507          pvt->prev = cur->prev;
05508          pvt->next = cur;
05509          if (cur->prev) {
05510             /* Insert into the middle of the list. */
05511             cur->prev->next = pvt;
05512          } else {
05513             /* Insert at head of list. */
05514             iflist = pvt;
05515          }
05516          cur->prev = pvt;
05517          return;
05518       }
05519    }
05520 
05521    /* New interface goes onto the end of the list */
05522    pvt->prev = ifend;
05523    pvt->next = NULL;
05524    if (ifend) {
05525       ifend->next = pvt;
05526    }
05527    ifend = pvt;
05528    if (!iflist) {
05529       /* List was empty */
05530       iflist = pvt;
05531    }
05532 }
05533 
05534 /*!
05535  * \internal
05536  * \brief Extract the given chan_dahdi interface structure from the interface list.
05537  * \since 1.8
05538  *
05539  * \param pvt chan_dahdi private interface structure to extract.
05540  *
05541  * \note
05542  * The given interface structure can be either in the interface list or a stand alone
05543  * structure that has not been put in the list if the next and prev pointers are NULL.
05544  *
05545  * \return Nothing
05546  */
05547 static void dahdi_iflist_extract(struct dahdi_pvt *pvt)
05548 {
05549    /* Extract from the forward chain. */
05550    if (pvt->prev) {
05551       pvt->prev->next = pvt->next;
05552    } else if (iflist == pvt) {
05553       /* Node is at the head of the list. */
05554       iflist = pvt->next;
05555    }
05556 
05557    /* Extract from the reverse chain. */
05558    if (pvt->next) {
05559       pvt->next->prev = pvt->prev;
05560    } else if (ifend == pvt) {
05561       /* Node is at the end of the list. */
05562       ifend = pvt->prev;
05563    }
05564 
05565    /* Node is no longer in the list. */
05566    pvt->which_iflist = DAHDI_IFLIST_NONE;
05567    pvt->prev = NULL;
05568    pvt->next = NULL;
05569 }
05570 
05571 #if defined(HAVE_PRI)
05572 /*!
05573  * \internal
05574  * \brief Insert the given chan_dahdi interface structure into the no B channel list.
05575  * \since 1.8
05576  *
05577  * \param pri sig_pri span control structure holding no B channel list.
05578  * \param pvt chan_dahdi private interface structure to insert.
05579  *
05580  * \details
05581  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05582  * Any duplicates are inserted after the existing entries.
05583  *
05584  * \note The new interface must not already be in the list.
05585  *
05586  * \return Nothing
05587  */
05588 static void dahdi_nobch_insert(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05589 {
05590    struct dahdi_pvt *cur;
05591 
05592    pvt->which_iflist = DAHDI_IFLIST_NO_B_CHAN;
05593 
05594    /* Find place in middle of list for the new interface. */
05595    for (cur = pri->no_b_chan_iflist; cur; cur = cur->next) {
05596       if (pvt->channel < cur->channel) {
05597          /* New interface goes before the current interface. */
05598          pvt->prev = cur->prev;
05599          pvt->next = cur;
05600          if (cur->prev) {
05601             /* Insert into the middle of the list. */
05602             cur->prev->next = pvt;
05603          } else {
05604             /* Insert at head of list. */
05605             pri->no_b_chan_iflist = pvt;
05606          }
05607          cur->prev = pvt;
05608          return;
05609       }
05610    }
05611 
05612    /* New interface goes onto the end of the list */
05613    pvt->prev = pri->no_b_chan_end;
05614    pvt->next = NULL;
05615    if (pri->no_b_chan_end) {
05616       ((struct dahdi_pvt *) pri->no_b_chan_end)->next = pvt;
05617    }
05618    pri->no_b_chan_end = pvt;
05619    if (!pri->no_b_chan_iflist) {
05620       /* List was empty */
05621       pri->no_b_chan_iflist = pvt;
05622    }
05623 }
05624 #endif   /* defined(HAVE_PRI) */
05625 
05626 #if defined(HAVE_PRI)
05627 /*!
05628  * \internal
05629  * \brief Extract the given chan_dahdi interface structure from the no B channel list.
05630  * \since 1.8
05631  *
05632  * \param pri sig_pri span control structure holding no B channel list.
05633  * \param pvt chan_dahdi private interface structure to extract.
05634  *
05635  * \note
05636  * The given interface structure can be either in the interface list or a stand alone
05637  * structure that has not been put in the list if the next and prev pointers are NULL.
05638  *
05639  * \return Nothing
05640  */
05641 static void dahdi_nobch_extract(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05642 {
05643    /* Extract from the forward chain. */
05644    if (pvt->prev) {
05645       pvt->prev->next = pvt->next;
05646    } else if (pri->no_b_chan_iflist == pvt) {
05647       /* Node is at the head of the list. */
05648       pri->no_b_chan_iflist = pvt->next;
05649    }
05650 
05651    /* Extract from the reverse chain. */
05652    if (pvt->next) {
05653       pvt->next->prev = pvt->prev;
05654    } else if (pri->no_b_chan_end == pvt) {
05655       /* Node is at the end of the list. */
05656       pri->no_b_chan_end = pvt->prev;
05657    }
05658 
05659    /* Node is no longer in the list. */
05660    pvt->which_iflist = DAHDI_IFLIST_NONE;
05661    pvt->prev = NULL;
05662    pvt->next = NULL;
05663 }
05664 #endif   /* defined(HAVE_PRI) */
05665 
05666 #if defined(HAVE_PRI)
05667 /*!
05668  * \internal
05669  * \brief Unlink the channel interface from the PRI private pointer array.
05670  * \since 1.8
05671  *
05672  * \param pvt chan_dahdi private interface structure to unlink.
05673  *
05674  * \return Nothing
05675  */
05676 static void dahdi_unlink_pri_pvt(struct dahdi_pvt *pvt)
05677 {
05678    unsigned idx;
05679    struct sig_pri_span *pri;
05680 
05681    pri = pvt->pri;
05682    if (!pri) {
05683       /* Not PRI signaling so cannot be in a PRI private pointer array. */
05684       return;
05685    }
05686    ast_mutex_lock(&pri->lock);
05687    for (idx = 0; idx < pri->numchans; ++idx) {
05688       if (pri->pvts[idx] == pvt->sig_pvt) {
05689          pri->pvts[idx] = NULL;
05690          ast_mutex_unlock(&pri->lock);
05691          return;
05692       }
05693    }
05694    ast_mutex_unlock(&pri->lock);
05695 }
05696 #endif   /* defined(HAVE_PRI) */
05697 
05698 #if defined(HAVE_SS7)
05699 /*!
05700  * \internal
05701  * \brief Unlink the channel interface from the SS7 private pointer array.
05702  * \since 1.8
05703  *
05704  * \param pvt chan_dahdi private interface structure to unlink.
05705  *
05706  * \return Nothing
05707  */
05708 static void dahdi_unlink_ss7_pvt(struct dahdi_pvt *pvt)
05709 {
05710    unsigned idx;
05711    struct sig_ss7_linkset *ss7;
05712 
05713    ss7 = pvt->ss7;
05714    if (!ss7) {
05715       /* Not SS7 signaling so cannot be in a SS7 private pointer array. */
05716       return;
05717    }
05718    ast_mutex_lock(&ss7->lock);
05719    for (idx = 0; idx < ss7->numchans; ++idx) {
05720       if (ss7->pvts[idx] == pvt->sig_pvt) {
05721          ss7->pvts[idx] = NULL;
05722          ast_mutex_unlock(&ss7->lock);
05723          return;
05724       }
05725    }
05726    ast_mutex_unlock(&ss7->lock);
05727 }
05728 #endif   /* defined(HAVE_SS7) */
05729 
05730 static struct dahdi_pvt *find_next_iface_in_span(struct dahdi_pvt *cur)
05731 {
05732    if (cur->next && cur->next->span == cur->span) {
05733       return cur->next;
05734    } else if (cur->prev && cur->prev->span == cur->span) {
05735       return cur->prev;
05736    }
05737 
05738    return NULL;
05739 }
05740 
05741 static void destroy_dahdi_pvt(struct dahdi_pvt *pvt)
05742 {
05743    struct dahdi_pvt *p = pvt;
05744 
05745    if (p->manages_span_alarms) {
05746       struct dahdi_pvt *next = find_next_iface_in_span(p);
05747       if (next) {
05748          next->manages_span_alarms = 1;
05749       }
05750    }
05751 
05752    /* Remove channel from the list */
05753 #if defined(HAVE_PRI)
05754    dahdi_unlink_pri_pvt(p);
05755 #endif   /* defined(HAVE_PRI) */
05756 #if defined(HAVE_SS7)
05757    dahdi_unlink_ss7_pvt(p);
05758 #endif   /* defined(HAVE_SS7) */
05759    switch (pvt->which_iflist) {
05760    case DAHDI_IFLIST_NONE:
05761       break;
05762    case DAHDI_IFLIST_MAIN:
05763       dahdi_iflist_extract(p);
05764       break;
05765 #if defined(HAVE_PRI)
05766    case DAHDI_IFLIST_NO_B_CHAN:
05767       if (p->pri) {
05768          dahdi_nobch_extract(p->pri, p);
05769       }
05770       break;
05771 #endif   /* defined(HAVE_PRI) */
05772    }
05773 
05774    if (p->sig_pvt) {
05775       if (analog_lib_handles(p->sig, 0, 0)) {
05776          analog_delete(p->sig_pvt);
05777       }
05778       switch (p->sig) {
05779 #if defined(HAVE_PRI)
05780       case SIG_PRI_LIB_HANDLE_CASES:
05781          sig_pri_chan_delete(p->sig_pvt);
05782          break;
05783 #endif   /* defined(HAVE_PRI) */
05784 #if defined(HAVE_SS7)
05785       case SIG_SS7:
05786          sig_ss7_chan_delete(p->sig_pvt);
05787          break;
05788 #endif   /* defined(HAVE_SS7) */
05789       default:
05790          break;
05791       }
05792    }
05793    ast_free(p->cidspill);
05794    if (p->use_smdi)
05795       ast_smdi_interface_unref(p->smdi_iface);
05796    if (p->mwi_event_sub)
05797       ast_event_unsubscribe(p->mwi_event_sub);
05798    if (p->vars) {
05799       ast_variables_destroy(p->vars);
05800    }
05801    if (p->cc_params) {
05802       ast_cc_config_params_destroy(p->cc_params);
05803    }
05804    ast_mutex_destroy(&p->lock);
05805    dahdi_close_sub(p, SUB_REAL);
05806    if (p->owner)
05807       p->owner->tech_pvt = NULL;
05808    ast_free(p);
05809 }
05810 
05811 static void destroy_channel(struct dahdi_pvt *cur, int now)
05812 {
05813    int i;
05814 
05815    if (!now) {
05816       /* Do not destroy the channel now if it is owned by someone. */
05817       if (cur->owner) {
05818          return;
05819       }
05820       for (i = 0; i < 3; i++) {
05821          if (cur->subs[i].owner) {
05822             return;
05823          }
05824       }
05825    }
05826    destroy_dahdi_pvt(cur);
05827 }
05828 
05829 static void destroy_all_channels(void)
05830 {
05831    int chan;
05832 #if defined(HAVE_PRI)
05833    unsigned span;
05834    struct sig_pri_span *pri;
05835 #endif   /* defined(HAVE_PRI) */
05836    struct dahdi_pvt *p;
05837 
05838    while (num_restart_pending) {
05839       usleep(1);
05840    }
05841 
05842    ast_mutex_lock(&iflock);
05843    /* Destroy all the interfaces and free their memory */
05844    while (iflist) {
05845       p = iflist;
05846 
05847       chan = p->channel;
05848 #if defined(HAVE_PRI_SERVICE_MESSAGES)
05849       {
05850          char db_chan_name[20];
05851          char db_answer[5];
05852          char state;
05853          int why = -1;
05854 
05855          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, p->span, chan);
05856          if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
05857             sscanf(db_answer, "%1c:%30d", &state, &why);
05858          }
05859          if (!why) {
05860             /* SRVST persistence is not required */
05861             ast_db_del(db_chan_name, SRVST_DBKEY);
05862          }
05863       }
05864 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
05865       /* Free associated memory */
05866       destroy_dahdi_pvt(p);
05867       ast_verb(3, "Unregistered channel %d\n", chan);
05868    }
05869    ifcount = 0;
05870    ast_mutex_unlock(&iflock);
05871 
05872 #if defined(HAVE_PRI)
05873    /* Destroy all of the no B channel interface lists */
05874    for (span = 0; span < NUM_SPANS; ++span) {
05875       if (!pris[span].dchannels[0]) {
05876          break;
05877       }
05878       pri = &pris[span].pri;
05879       ast_mutex_lock(&pri->lock);
05880       while (pri->no_b_chan_iflist) {
05881          p = pri->no_b_chan_iflist;
05882 
05883          /* Free associated memory */
05884          destroy_dahdi_pvt(p);
05885       }
05886       ast_mutex_unlock(&pri->lock);
05887    }
05888 #endif   /* defined(HAVE_PRI) */
05889 }
05890 
05891 #if defined(HAVE_PRI)
05892 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
05893 
05894 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, const char *digits)
05895 {
05896    /* Data will be our digit string */
05897    struct dahdi_pvt *p;
05898 
05899    if (ast_strlen_zero(digits)) {
05900       ast_debug(1, "No digit string sent to application!\n");
05901       return -1;
05902    }
05903 
05904    p = (struct dahdi_pvt *)chan->tech_pvt;
05905 
05906    if (!p) {
05907       ast_debug(1, "Unable to find technology private\n");
05908       return -1;
05909    }
05910 
05911    pri_send_keypad_facility_exec(p->sig_pvt, digits);
05912 
05913    return 0;
05914 }
05915 #endif   /* defined(HAVE_PRI) */
05916 
05917 #if defined(HAVE_PRI)
05918 #if defined(HAVE_PRI_PROG_W_CAUSE)
05919 static char *dahdi_send_callrerouting_facility_app = "DAHDISendCallreroutingFacility";
05920 
05921 static int dahdi_send_callrerouting_facility_exec(struct ast_channel *chan, const char *data)
05922 {
05923    /* Data will be our digit string */
05924    struct dahdi_pvt *pvt;
05925    char *parse;
05926    int res;
05927    AST_DECLARE_APP_ARGS(args,
05928       AST_APP_ARG(destination);
05929       AST_APP_ARG(original);
05930       AST_APP_ARG(reason);
05931    );
05932 
05933    if (ast_strlen_zero(data)) {
05934       ast_log(LOG_DEBUG, "No data sent to application!\n");
05935       return -1;
05936    }
05937    if (chan->tech != &dahdi_tech) {
05938       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05939       return -1;
05940    }
05941    pvt = (struct dahdi_pvt *) chan->tech_pvt;
05942    if (!pvt) {
05943       ast_log(LOG_DEBUG, "Unable to find technology private\n");
05944       return -1;
05945    }
05946    switch (pvt->sig) {
05947    case SIG_PRI_LIB_HANDLE_CASES:
05948       break;
05949    default:
05950       ast_log(LOG_DEBUG, "callrerouting attempted on non-ISDN channel %s\n",
05951          chan->name);
05952       return -1;
05953    }
05954 
05955    parse = ast_strdupa(data);
05956    AST_STANDARD_APP_ARGS(args, parse);
05957 
05958    if (ast_strlen_zero(args.destination)) {
05959       ast_log(LOG_WARNING, "callrerouting facility requires at least destination number argument\n");
05960       return -1;
05961    }
05962 
05963    if (ast_strlen_zero(args.original)) {
05964       ast_log(LOG_WARNING, "Callrerouting Facility without original called number argument\n");
05965       args.original = NULL;
05966    }
05967 
05968    if (ast_strlen_zero(args.reason)) {
05969       ast_log(LOG_NOTICE, "Callrerouting Facility without diversion reason argument, defaulting to unknown\n");
05970       args.reason = NULL;
05971    }
05972 
05973    res = pri_send_callrerouting_facility_exec(pvt->sig_pvt, chan->_state,
05974       args.destination, args.original, args.reason);
05975    if (!res) {
05976       /*
05977        * Wait up to 5 seconds for a reply before hanging up this call
05978        * leg if the peer does not disconnect first.
05979        */
05980       ast_safe_sleep(chan, 5000);
05981    }
05982 
05983    return -1;
05984 }
05985 #endif   /* defined(HAVE_PRI_PROG_W_CAUSE) */
05986 #endif   /* defined(HAVE_PRI) */
05987 
05988 #if defined(HAVE_OPENR2)
05989 static const char * const dahdi_accept_r2_call_app = "DAHDIAcceptR2Call";
05990 
05991 static int dahdi_accept_r2_call_exec(struct ast_channel *chan, const char *data)
05992 {
05993    /* data is whether to accept with charge or no charge */
05994    openr2_call_mode_t accept_mode;
05995    int res, timeout, maxloops;
05996    struct ast_frame *f;
05997    struct dahdi_pvt *p;
05998    char *parse;
05999    AST_DECLARE_APP_ARGS(args,
06000          AST_APP_ARG(charge);
06001    );
06002 
06003    if (ast_strlen_zero(data)) {
06004       ast_log(LOG_DEBUG, "No data sent to application!\n");
06005       return -1;
06006    }
06007 
06008    if (chan->tech != &dahdi_tech) {
06009       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
06010       return -1;
06011    }
06012 
06013    p = (struct dahdi_pvt *)chan->tech_pvt;
06014    if (!p) {
06015       ast_log(LOG_DEBUG, "Unable to find technology private!\n");
06016       return -1;
06017    }
06018 
06019    parse = ast_strdupa(data);
06020    AST_STANDARD_APP_ARGS(args, parse);
06021 
06022    if (ast_strlen_zero(args.charge)) {
06023       ast_log(LOG_WARNING, "DAHDIAcceptR2Call requires 'yes' or 'no' for the charge parameter\n");
06024       return -1;
06025    }
06026 
06027    ast_mutex_lock(&p->lock);
06028    if (!p->mfcr2 || !p->mfcr2call) {
06029       ast_mutex_unlock(&p->lock);
06030       ast_log(LOG_DEBUG, "Channel %s does not seems to be an R2 active channel!\n", chan->name);
06031       return -1;
06032    }
06033 
06034    if (p->mfcr2_call_accepted) {
06035       ast_mutex_unlock(&p->lock);
06036       ast_log(LOG_DEBUG, "MFC/R2 call already accepted on channel %s!\n", chan->name);
06037       return 0;
06038    }
06039    accept_mode = ast_true(args.charge) ? OR2_CALL_WITH_CHARGE : OR2_CALL_NO_CHARGE;
06040    if (openr2_chan_accept_call(p->r2chan, accept_mode)) {
06041       ast_mutex_unlock(&p->lock);
06042       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
06043       return -1;
06044    }
06045    ast_mutex_unlock(&p->lock);
06046 
06047    res = 0;
06048    timeout = 100;
06049    maxloops = 50; /* wait up to 5 seconds */
06050    /* we need to read() until the call is accepted */
06051    while (maxloops > 0) {
06052       maxloops--;
06053       if (ast_check_hangup(chan)) {
06054          break;
06055       }
06056       res = ast_waitfor(chan, timeout);
06057       if (res < 0) {
06058          ast_log(LOG_DEBUG, "ast_waitfor failed on channel %s, going out ...\n", chan->name);
06059          res = -1;
06060          break;
06061       }
06062       if (res == 0) {
06063          continue;
06064       }
06065       res = 0;
06066       f = ast_read(chan);
06067       if (!f) {
06068          ast_log(LOG_DEBUG, "No frame read on channel %s, going out ...\n", chan->name);
06069          res = -1;
06070          break;
06071       }
06072       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
06073          ast_log(LOG_DEBUG, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
06074          ast_frfree(f);
06075          res = -1;
06076          break;
06077       }
06078       ast_frfree(f);
06079       ast_mutex_lock(&p->lock);
06080       if (p->mfcr2_call_accepted) {
06081          ast_mutex_unlock(&p->lock);
06082          ast_log(LOG_DEBUG, "Accepted MFC/R2 call!\n");
06083          break;
06084       }
06085       ast_mutex_unlock(&p->lock);
06086    }
06087    if (res == -1) {
06088       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
06089    }
06090    return res;
06091 }
06092 
06093 static openr2_call_disconnect_cause_t dahdi_ast_cause_to_r2_cause(int cause)
06094 {
06095    openr2_call_disconnect_cause_t r2cause = OR2_CAUSE_NORMAL_CLEARING;
06096    switch (cause) {
06097    case AST_CAUSE_USER_BUSY:
06098    case AST_CAUSE_CALL_REJECTED:
06099    case AST_CAUSE_INTERWORKING: /* I don't know wtf is this but is used sometimes when ekiga rejects a call */
06100       r2cause = OR2_CAUSE_BUSY_NUMBER;
06101       break;
06102 
06103    case AST_CAUSE_NORMAL_CIRCUIT_CONGESTION:
06104    case AST_CAUSE_SWITCH_CONGESTION:
06105       r2cause = OR2_CAUSE_NETWORK_CONGESTION;
06106       break;
06107 
06108    case AST_CAUSE_UNALLOCATED:
06109       r2cause = OR2_CAUSE_UNALLOCATED_NUMBER;
06110       break;
06111 
06112    case AST_CAUSE_NETWORK_OUT_OF_ORDER:
06113    case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06114       r2cause = OR2_CAUSE_OUT_OF_ORDER;
06115       break;
06116 
06117    case AST_CAUSE_NO_ANSWER:
06118    case AST_CAUSE_NO_USER_RESPONSE:
06119       r2cause = OR2_CAUSE_NO_ANSWER;
06120       break;
06121 
06122    default:
06123       r2cause = OR2_CAUSE_NORMAL_CLEARING;
06124       break;
06125    }
06126    ast_log(LOG_DEBUG, "ast cause %d resulted in openr2 cause %d/%s\n",
06127          cause, r2cause, openr2_proto_get_disconnect_string(r2cause));
06128    return r2cause;
06129 }
06130 #endif
06131 
06132 static int revert_fax_buffers(struct dahdi_pvt *p, struct ast_channel *ast)
06133 {
06134    if (p->bufferoverrideinuse) {
06135       /* faxbuffers are in use, revert them */
06136       struct dahdi_bufferinfo bi = {
06137          .txbufpolicy = p->buf_policy,
06138          .rxbufpolicy = p->buf_policy,
06139          .bufsize = p->bufsize,
06140          .numbufs = p->buf_no
06141       };
06142       int bpres;
06143 
06144       if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
06145          ast_log(LOG_WARNING, "Channel '%s' unable to revert buffer policy: %s\n", ast->name, strerror(errno));
06146       }
06147       p->bufferoverrideinuse = 0;
06148       return bpres;
06149    }
06150 
06151    return -1;
06152 }
06153 
06154 static int dahdi_hangup(struct ast_channel *ast)
06155 {
06156    int res = 0;
06157    int idx,x;
06158    int law;
06159    /*static int restore_gains(struct dahdi_pvt *p);*/
06160    struct dahdi_pvt *p = ast->tech_pvt;
06161    struct dahdi_params par;
06162 
06163    ast_debug(1, "dahdi_hangup(%s)\n", ast->name);
06164    if (!ast->tech_pvt) {
06165       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
06166       return 0;
06167    }
06168 
06169    ast_mutex_lock(&p->lock);
06170    p->exten[0] = '\0';
06171    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06172       dahdi_confmute(p, 0);
06173       restore_gains(p);
06174       p->ignoredtmf = 0;
06175       p->waitingfordt.tv_sec = 0;
06176 
06177       res = analog_hangup(p->sig_pvt, ast);
06178       revert_fax_buffers(p, ast);
06179 
06180       goto hangup_out;
06181    } else {
06182       p->cid_num[0] = '\0';
06183       p->cid_name[0] = '\0';
06184       p->cid_subaddr[0] = '\0';
06185    }
06186 
06187 #if defined(HAVE_PRI)
06188    if (dahdi_sig_pri_lib_handles(p->sig)) {
06189       x = 1;
06190       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06191 
06192       dahdi_confmute(p, 0);
06193       p->muting = 0;
06194       restore_gains(p);
06195       if (p->dsp) {
06196          ast_dsp_free(p->dsp);
06197          p->dsp = NULL;
06198       }
06199       p->ignoredtmf = 0;
06200 
06201       /* Real channel, do some fixup */
06202       p->subs[SUB_REAL].owner = NULL;
06203       p->subs[SUB_REAL].needbusy = 0;
06204       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06205 
06206       p->owner = NULL;
06207       p->cid_tag[0] = '\0';
06208       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06209       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06210       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06211       p->outgoing = 0;
06212       p->digital = 0;
06213       p->faxhandled = 0;
06214       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06215 
06216       revert_fax_buffers(p, ast);
06217 
06218       p->law = p->law_default;
06219       law = p->law_default;
06220       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06221       if (res < 0) {
06222          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n",
06223             p->channel, strerror(errno));
06224       }
06225 
06226       sig_pri_hangup(p->sig_pvt, ast);
06227 
06228       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06229       dahdi_disable_ec(p);
06230 
06231       x = 0;
06232       ast_channel_setoption(ast, AST_OPTION_TDD, &x, sizeof(char), 0);
06233       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06234 
06235       p->rdnis[0] = '\0';
06236       update_conf(p);
06237       reset_conf(p);
06238 
06239       /* Restore data mode */
06240       x = 0;
06241       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06242 
06243       if (num_restart_pending == 0) {
06244          restart_monitor();
06245       }
06246       goto hangup_out;
06247    }
06248 #endif   /* defined(HAVE_PRI) */
06249 
06250 #if defined(HAVE_SS7)
06251    if (p->sig == SIG_SS7) {
06252       x = 1;
06253       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06254 
06255       dahdi_confmute(p, 0);
06256       p->muting = 0;
06257       restore_gains(p);
06258       if (p->dsp) {
06259          ast_dsp_free(p->dsp);
06260          p->dsp = NULL;
06261       }
06262       p->ignoredtmf = 0;
06263 
06264       /* Real channel, do some fixup */
06265       p->subs[SUB_REAL].owner = NULL;
06266       p->subs[SUB_REAL].needbusy = 0;
06267       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06268 
06269       p->owner = NULL;
06270       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06271       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06272       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06273       p->outgoing = 0;
06274       p->digital = 0;
06275       p->faxhandled = 0;
06276       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06277 
06278       revert_fax_buffers(p, ast);
06279 
06280       p->law = p->law_default;
06281       law = p->law_default;
06282       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06283       if (res < 0) {
06284          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n",
06285             p->channel, strerror(errno));
06286       }
06287 
06288       sig_ss7_hangup(p->sig_pvt, ast);
06289 
06290       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06291       dahdi_disable_ec(p);
06292 
06293       x = 0;
06294       ast_channel_setoption(ast, AST_OPTION_TDD, &x, sizeof(char), 0);
06295       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06296 
06297       update_conf(p);
06298       reset_conf(p);
06299 
06300       /* Restore data mode */
06301       x = 0;
06302       ast_channel_setoption(ast, AST_OPTION_AUDIO_MODE, &x, sizeof(char), 0);
06303 
06304       if (num_restart_pending == 0) {
06305          restart_monitor();
06306       }
06307       goto hangup_out;
06308    }
06309 #endif   /* defined(HAVE_SS7) */
06310 
06311    idx = dahdi_get_index(ast, p, 1);
06312 
06313    dahdi_confmute(p, 0);
06314    p->muting = 0;
06315    restore_gains(p);
06316    if (p->origcid_num) {
06317       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
06318       ast_free(p->origcid_num);
06319       p->origcid_num = NULL;
06320    }
06321    if (p->origcid_name) {
06322       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
06323       ast_free(p->origcid_name);
06324       p->origcid_name = NULL;
06325    }
06326    if (p->dsp)
06327       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
06328 
06329    ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
06330       p->channel, idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
06331    p->ignoredtmf = 0;
06332 
06333    if (idx > -1) {
06334       /* Real channel, do some fixup */
06335       p->subs[idx].owner = NULL;
06336       p->subs[idx].needanswer = 0;
06337       p->subs[idx].needflash = 0;
06338       p->subs[idx].needringing = 0;
06339       p->subs[idx].needbusy = 0;
06340       p->subs[idx].needcongestion = 0;
06341       p->subs[idx].linear = 0;
06342       p->polarity = POLARITY_IDLE;
06343       dahdi_setlinear(p->subs[idx].dfd, 0);
06344       if (idx == SUB_REAL) {
06345          if ((p->subs[SUB_CALLWAIT].dfd > -1) && (p->subs[SUB_THREEWAY].dfd > -1)) {
06346             ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
06347             if (p->subs[SUB_CALLWAIT].inthreeway) {
06348                /* We had flipped over to answer a callwait and now it's gone */
06349                ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
06350                /* Move to the call-wait, but un-own us until they flip back. */
06351                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06352                unalloc_sub(p, SUB_CALLWAIT);
06353                p->owner = NULL;
06354             } else {
06355                /* The three way hung up, but we still have a call wait */
06356                ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
06357                swap_subs(p, SUB_THREEWAY, SUB_REAL);
06358                unalloc_sub(p, SUB_THREEWAY);
06359                if (p->subs[SUB_REAL].inthreeway) {
06360                   /* This was part of a three way call.  Immediately make way for
06361                      another call */
06362                   ast_debug(1, "Call was complete, setting owner to former third call\n");
06363                   p->owner = p->subs[SUB_REAL].owner;
06364                } else {
06365                   /* This call hasn't been completed yet...  Set owner to NULL */
06366                   ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06367                   p->owner = NULL;
06368                }
06369                p->subs[SUB_REAL].inthreeway = 0;
06370             }
06371          } else if (p->subs[SUB_CALLWAIT].dfd > -1) {
06372             /* Move to the call-wait and switch back to them. */
06373             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06374             unalloc_sub(p, SUB_CALLWAIT);
06375             p->owner = p->subs[SUB_REAL].owner;
06376             if (p->owner->_state != AST_STATE_UP)
06377                p->subs[SUB_REAL].needanswer = 1;
06378             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
06379                ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
06380          } else if (p->subs[SUB_THREEWAY].dfd > -1) {
06381             swap_subs(p, SUB_THREEWAY, SUB_REAL);
06382             unalloc_sub(p, SUB_THREEWAY);
06383             if (p->subs[SUB_REAL].inthreeway) {
06384                /* This was part of a three way call.  Immediately make way for
06385                   another call */
06386                ast_debug(1, "Call was complete, setting owner to former third call\n");
06387                p->owner = p->subs[SUB_REAL].owner;
06388             } else {
06389                /* This call hasn't been completed yet...  Set owner to NULL */
06390                ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06391                p->owner = NULL;
06392             }
06393             p->subs[SUB_REAL].inthreeway = 0;
06394          }
06395       } else if (idx == SUB_CALLWAIT) {
06396          /* Ditch the holding callwait call, and immediately make it availabe */
06397          if (p->subs[SUB_CALLWAIT].inthreeway) {
06398             /* This is actually part of a three way, placed on hold.  Place the third part
06399                on music on hold now */
06400             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
06401                ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
06402                   S_OR(p->mohsuggest, NULL),
06403                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06404             }
06405             p->subs[SUB_THREEWAY].inthreeway = 0;
06406             /* Make it the call wait now */
06407             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
06408             unalloc_sub(p, SUB_THREEWAY);
06409          } else
06410             unalloc_sub(p, SUB_CALLWAIT);
06411       } else if (idx == SUB_THREEWAY) {
06412          if (p->subs[SUB_CALLWAIT].inthreeway) {
06413             /* The other party of the three way call is currently in a call-wait state.
06414                Start music on hold for them, and take the main guy out of the third call */
06415             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
06416                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
06417                   S_OR(p->mohsuggest, NULL),
06418                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06419             }
06420             p->subs[SUB_CALLWAIT].inthreeway = 0;
06421          }
06422          p->subs[SUB_REAL].inthreeway = 0;
06423          /* If this was part of a three way call index, let us make
06424             another three way call */
06425          unalloc_sub(p, SUB_THREEWAY);
06426       } else {
06427          /* This wasn't any sort of call, but how are we an index? */
06428          ast_log(LOG_WARNING, "Index found but not any type of call?\n");
06429       }
06430    }
06431 
06432    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
06433       p->owner = NULL;
06434       p->ringt = 0;
06435       p->distinctivering = 0;
06436       p->confirmanswer = 0;
06437       p->outgoing = 0;
06438       p->digital = 0;
06439       p->faxhandled = 0;
06440       p->pulsedial = 0;
06441       if (p->dsp) {
06442          ast_dsp_free(p->dsp);
06443          p->dsp = NULL;
06444       }
06445 
06446       revert_fax_buffers(p, ast);
06447 
06448       p->law = p->law_default;
06449       law = p->law_default;
06450       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06451       if (res < 0)
06452          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
06453       /* Perform low level hangup if no owner left */
06454 #ifdef HAVE_OPENR2
06455       if (p->mfcr2 && p->mfcr2call && openr2_chan_get_direction(p->r2chan) != OR2_DIR_STOPPED) {
06456          ast_log(LOG_DEBUG, "disconnecting MFC/R2 call on chan %d\n", p->channel);
06457          /* If it's an incoming call, check the mfcr2_forced_release setting */
06458          if (openr2_chan_get_direction(p->r2chan) == OR2_DIR_BACKWARD && p->mfcr2_forced_release) {
06459             dahdi_r2_disconnect_call(p, OR2_CAUSE_FORCED_RELEASE);
06460          } else {
06461             const char *r2causestr = pbx_builtin_getvar_helper(ast, "MFCR2_CAUSE");
06462             int r2cause_user = r2causestr ? atoi(r2causestr) : 0;
06463             openr2_call_disconnect_cause_t r2cause = r2cause_user ? dahdi_ast_cause_to_r2_cause(r2cause_user)
06464                                                              : dahdi_ast_cause_to_r2_cause(ast->hangupcause);
06465             dahdi_r2_disconnect_call(p, r2cause);
06466          }
06467       } else if (p->mfcr2call) {
06468          ast_log(LOG_DEBUG, "Clearing call request on channel %d\n", p->channel);
06469          /* since ast_request() was called but not ast_call() we have not yet dialed
06470          and the openr2 stack will not call on_call_end callback, we need to unset
06471          the mfcr2call flag and bump the monitor count so the monitor thread can take
06472          care of this channel events from now on */
06473          p->mfcr2call = 0;
06474       }
06475 #endif
06476       switch (p->sig) {
06477       case SIG_SS7:
06478       case SIG_MFCR2:
06479       case SIG_PRI_LIB_HANDLE_CASES:
06480       case 0:
06481          break;
06482       default:
06483          res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
06484          break;
06485       }
06486       if (res < 0) {
06487          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
06488       }
06489       switch (p->sig) {
06490       case SIG_FXOGS:
06491       case SIG_FXOLS:
06492       case SIG_FXOKS:
06493          memset(&par, 0, sizeof(par));
06494          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
06495          if (!res) {
06496             struct analog_pvt *analog_p = p->sig_pvt;
06497 #if 0
06498             ast_debug(1, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
06499 #endif
06500             /* If they're off hook, try playing congestion */
06501             if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
06502                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
06503             else
06504                tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06505             analog_p->fxsoffhookstate = par.rxisoffhook;
06506          }
06507          break;
06508       case SIG_FXSGS:
06509       case SIG_FXSLS:
06510       case SIG_FXSKS:
06511          /* Make sure we're not made available for at least two seconds assuming
06512          we were actually used for an inbound or outbound call. */
06513          if (ast->_state != AST_STATE_RESERVED) {
06514             time(&p->guardtime);
06515             p->guardtime += 2;
06516          }
06517          break;
06518       default:
06519          tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06520          break;
06521       }
06522       if (p->sig)
06523          dahdi_disable_ec(p);
06524       x = 0;
06525       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
06526       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
06527       p->didtdd = 0;
06528       p->callwaitcas = 0;
06529       p->callwaiting = p->permcallwaiting;
06530       p->hidecallerid = p->permhidecallerid;
06531       p->waitingfordt.tv_sec = 0;
06532       p->dialing = 0;
06533       p->rdnis[0] = '\0';
06534       update_conf(p);
06535       reset_conf(p);
06536       /* Restore data mode */
06537       switch (p->sig) {
06538       case SIG_PRI_LIB_HANDLE_CASES:
06539       case SIG_SS7:
06540          x = 0;
06541          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
06542          break;
06543       default:
06544          break;
06545       }
06546       if (num_restart_pending == 0)
06547          restart_monitor();
06548    }
06549 
06550    p->callwaitingrepeat = 0;
06551    p->cidcwexpire = 0;
06552    p->cid_suppress_expire = 0;
06553    p->oprmode = 0;
06554 hangup_out:
06555    ast->tech_pvt = NULL;
06556    ast_free(p->cidspill);
06557    p->cidspill = NULL;
06558 
06559    ast_mutex_unlock(&p->lock);
06560    ast_verb(3, "Hungup '%s'\n", ast->name);
06561 
06562    ast_mutex_lock(&iflock);
06563    if (p->restartpending) {
06564       num_restart_pending--;
06565    }
06566 
06567    if (p->destroy) {
06568       destroy_channel(p, 0);
06569    }
06570    ast_mutex_unlock(&iflock);
06571 
06572    ast_module_unref(ast_module_info->self);
06573    return 0;
06574 }
06575 
06576 static int dahdi_answer(struct ast_channel *ast)
06577 {
06578    struct dahdi_pvt *p = ast->tech_pvt;
06579    int res = 0;
06580    int idx;
06581    ast_setstate(ast, AST_STATE_UP);/*! \todo XXX this is redundantly set by the analog and PRI submodules! */
06582    ast_mutex_lock(&p->lock);
06583    idx = dahdi_get_index(ast, p, 0);
06584    if (idx < 0)
06585       idx = SUB_REAL;
06586    /* nothing to do if a radio channel */
06587    if ((p->radio || (p->oprmode < 0))) {
06588       ast_mutex_unlock(&p->lock);
06589       return 0;
06590    }
06591 
06592    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06593       res = analog_answer(p->sig_pvt, ast);
06594       ast_mutex_unlock(&p->lock);
06595       return res;
06596    }
06597 
06598    switch (p->sig) {
06599 #if defined(HAVE_PRI)
06600    case SIG_PRI_LIB_HANDLE_CASES:
06601       res = sig_pri_answer(p->sig_pvt, ast);
06602       break;
06603 #endif   /* defined(HAVE_PRI) */
06604 #if defined(HAVE_SS7)
06605    case SIG_SS7:
06606       res = sig_ss7_answer(p->sig_pvt, ast);
06607       break;
06608 #endif   /* defined(HAVE_SS7) */
06609 #ifdef HAVE_OPENR2
06610    case SIG_MFCR2:
06611       if (!p->mfcr2_call_accepted) {
06612          /* The call was not accepted on offer nor the user, so it must be accepted now before answering,
06613             openr2_chan_answer_call will be called when the callback on_call_accepted is executed */
06614          p->mfcr2_answer_pending = 1;
06615          if (p->mfcr2_charge_calls) {
06616             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge before answering on chan %d\n", p->channel);
06617             openr2_chan_accept_call(p->r2chan, OR2_CALL_WITH_CHARGE);
06618          } else {
06619             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge before answering on chan %d\n", p->channel);
06620             openr2_chan_accept_call(p->r2chan, OR2_CALL_NO_CHARGE);
06621          }
06622       } else {
06623          ast_log(LOG_DEBUG, "Answering MFC/R2 call on chan %d\n", p->channel);
06624          dahdi_r2_answer(p);
06625       }
06626       break;
06627 #endif
06628    case 0:
06629       ast_mutex_unlock(&p->lock);
06630       return 0;
06631    default:
06632       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
06633       res = -1;
06634       break;
06635    }
06636    ast_mutex_unlock(&p->lock);
06637    return res;
06638 }
06639 
06640 static void disable_dtmf_detect(struct dahdi_pvt *p)
06641 {
06642    int val = 0;
06643 
06644    p->ignoredtmf = 1;
06645 
06646    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06647 
06648    if (!p->hardwaredtmf && p->dsp) {
06649       p->dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
06650       ast_dsp_set_features(p->dsp, p->dsp_features);
06651    }
06652 }
06653 
06654 static void enable_dtmf_detect(struct dahdi_pvt *p)
06655 {
06656    int val = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
06657 
06658    if (p->channel == CHAN_PSEUDO)
06659       return;
06660 
06661    p->ignoredtmf = 0;
06662 
06663    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06664 
06665    if (!p->hardwaredtmf && p->dsp) {
06666       p->dsp_features |= DSP_FEATURE_DIGIT_DETECT;
06667       ast_dsp_set_features(p->dsp, p->dsp_features);
06668    }
06669 }
06670 
06671 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
06672 {
06673    char *cp;
06674    struct dahdi_pvt *p = chan->tech_pvt;
06675 
06676    /* all supported options require data */
06677    if (!p || !data || (*datalen < 1)) {
06678       errno = EINVAL;
06679       return -1;
06680    }
06681 
06682    switch (option) {
06683    case AST_OPTION_DIGIT_DETECT:
06684       cp = (char *) data;
06685       *cp = p->ignoredtmf ? 0 : 1;
06686       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06687       break;
06688    case AST_OPTION_FAX_DETECT:
06689       cp = (char *) data;
06690       *cp = (p->dsp_features & DSP_FEATURE_FAX_DETECT) ? 0 : 1;
06691       ast_debug(1, "Reporting fax tone detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06692       break;
06693    case AST_OPTION_CC_AGENT_TYPE:
06694 #if defined(HAVE_PRI)
06695 #if defined(HAVE_PRI_CCSS)
06696       if (dahdi_sig_pri_lib_handles(p->sig)) {
06697          ast_copy_string((char *) data, dahdi_pri_cc_type, *datalen);
06698          break;
06699       }
06700 #endif   /* defined(HAVE_PRI_CCSS) */
06701 #endif   /* defined(HAVE_PRI) */
06702       return -1;
06703    default:
06704       return -1;
06705    }
06706 
06707    errno = 0;
06708 
06709    return 0;
06710 }
06711 
06712 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen)
06713 {
06714    char *cp;
06715    signed char *scp;
06716    int x;
06717    int idx;
06718    struct dahdi_pvt *p = chan->tech_pvt, *pp;
06719    struct oprmode *oprmode;
06720 
06721 
06722    /* all supported options require data */
06723    if (!p || !data || (datalen < 1)) {
06724       errno = EINVAL;
06725       return -1;
06726    }
06727 
06728    switch (option) {
06729    case AST_OPTION_TXGAIN:
06730       scp = (signed char *) data;
06731       idx = dahdi_get_index(chan, p, 0);
06732       if (idx < 0) {
06733          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
06734          return -1;
06735       }
06736       ast_debug(1, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
06737       return set_actual_txgain(p->subs[idx].dfd, p->txgain + (float) *scp, p->txdrc, p->law);
06738    case AST_OPTION_RXGAIN:
06739       scp = (signed char *) data;
06740       idx = dahdi_get_index(chan, p, 0);
06741       if (idx < 0) {
06742          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
06743          return -1;
06744       }
06745       ast_debug(1, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
06746       return set_actual_rxgain(p->subs[idx].dfd, p->rxgain + (float) *scp, p->rxdrc, p->law);
06747    case AST_OPTION_TONE_VERIFY:
06748       if (!p->dsp)
06749          break;
06750       cp = (char *) data;
06751       switch (*cp) {
06752       case 1:
06753          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
06754          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
06755          break;
06756       case 2:
06757          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
06758          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
06759          break;
06760       default:
06761          ast_debug(1, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
06762          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
06763          break;
06764       }
06765       break;
06766    case AST_OPTION_TDD:
06767       /* turn on or off TDD */
06768       cp = (char *) data;
06769       p->mate = 0;
06770       if (!*cp) { /* turn it off */
06771          ast_debug(1, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
06772          if (p->tdd)
06773             tdd_free(p->tdd);
06774          p->tdd = 0;
06775          break;
06776       }
06777       ast_debug(1, "Set option TDD MODE, value: %s(%d) on %s\n",
06778          (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
06779       dahdi_disable_ec(p);
06780       /* otherwise, turn it on */
06781       if (!p->didtdd) { /* if havent done it yet */
06782          unsigned char mybuf[41000];/*! \todo XXX This is an abuse of the stack!! */
06783          unsigned char *buf;
06784          int size, res, fd, len;
06785          struct pollfd fds[1];
06786 
06787          buf = mybuf;
06788          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
06789          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
06790          len = 40000;
06791          idx = dahdi_get_index(chan, p, 0);
06792          if (idx < 0) {
06793             ast_log(LOG_WARNING, "No index in TDD?\n");
06794             return -1;
06795          }
06796          fd = p->subs[idx].dfd;
06797          while (len) {
06798             if (ast_check_hangup(chan))
06799                return -1;
06800             size = len;
06801             if (size > READ_SIZE)
06802                size = READ_SIZE;
06803             fds[0].fd = fd;
06804             fds[0].events = POLLPRI | POLLOUT;
06805             fds[0].revents = 0;
06806             res = poll(fds, 1, -1);
06807             if (!res) {
06808                ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
06809                continue;
06810             }
06811             /* if got exception */
06812             if (fds[0].revents & POLLPRI)
06813                return -1;
06814             if (!(fds[0].revents & POLLOUT)) {
06815                ast_debug(1, "write fd not ready on channel %d\n", p->channel);
06816                continue;
06817             }
06818             res = write(fd, buf, size);
06819             if (res != size) {
06820                if (res == -1) return -1;
06821                ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
06822                break;
06823             }
06824             len -= size;
06825             buf += size;
06826          }
06827          p->didtdd = 1; /* set to have done it now */
06828       }
06829       if (*cp == 2) { /* Mate mode */
06830          if (p->tdd)
06831             tdd_free(p->tdd);
06832          p->tdd = 0;
06833          p->mate = 1;
06834          break;
06835       }
06836       if (!p->tdd) { /* if we don't have one yet */
06837          p->tdd = tdd_new(); /* allocate one */
06838       }
06839       break;
06840    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
06841       if (!p->dsp)
06842          break;
06843       cp = (char *) data;
06844       ast_debug(1, "Set option RELAX DTMF, value: %s(%d) on %s\n",
06845          *cp ? "ON" : "OFF", (int) *cp, chan->name);
06846       ast_dsp_set_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
06847       break;
06848    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
06849 #if defined(HAVE_PRI)
06850       if (dahdi_sig_pri_lib_handles(p->sig)
06851          && ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
06852          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
06853          break;
06854       }
06855 #endif   /* defined(HAVE_PRI) */
06856 
06857       cp = (char *) data;
06858       if (!*cp) {
06859          ast_debug(1, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
06860          x = 0;
06861          dahdi_disable_ec(p);
06862       } else {
06863          ast_debug(1, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
06864          x = 1;
06865       }
06866       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x) == -1)
06867          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", p->channel, x, strerror(errno));
06868       break;
06869    case AST_OPTION_OPRMODE:  /* Operator services mode */
06870       oprmode = (struct oprmode *) data;
06871       /* We don't support operator mode across technologies */
06872       if (strcasecmp(chan->tech->type, oprmode->peer->tech->type)) {
06873          ast_log(LOG_NOTICE, "Operator mode not supported on %s to %s calls.\n",
06874                chan->tech->type, oprmode->peer->tech->type);
06875          errno = EINVAL;
06876          return -1;
06877       }
06878       pp = oprmode->peer->tech_pvt;
06879       p->oprmode = pp->oprmode = 0;
06880       /* setup peers */
06881       p->oprpeer = pp;
06882       pp->oprpeer = p;
06883       /* setup modes, if any */
06884       if (oprmode->mode)
06885       {
06886          pp->oprmode = oprmode->mode;
06887          p->oprmode = -oprmode->mode;
06888       }
06889       ast_debug(1, "Set Operator Services mode, value: %d on %s/%s\n",
06890          oprmode->mode, chan->name,oprmode->peer->name);
06891       break;
06892    case AST_OPTION_ECHOCAN:
06893       cp = (char *) data;
06894       if (*cp) {
06895          ast_debug(1, "Enabling echo cancellation on %s\n", chan->name);
06896          dahdi_enable_ec(p);
06897       } else {
06898          ast_debug(1, "Disabling echo cancellation on %s\n", chan->name);
06899          dahdi_disable_ec(p);
06900       }
06901       break;
06902    case AST_OPTION_DIGIT_DETECT:
06903       cp = (char *) data;
06904       ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
06905       if (*cp) {
06906          enable_dtmf_detect(p);
06907       } else {
06908          disable_dtmf_detect(p);
06909       }
06910       break;
06911    case AST_OPTION_FAX_DETECT:
06912       cp = (char *) data;
06913       if (p->dsp) {
06914          ast_debug(1, "%sabling fax tone detection on %s\n", *cp ? "En" : "Dis", chan->name);
06915          if (*cp) {
06916             p->dsp_features |= DSP_FEATURE_FAX_DETECT;
06917          } else {
06918             p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
06919          }
06920          ast_dsp_set_features(p->dsp, p->dsp_features);
06921       }
06922       break;
06923    default:
06924       return -1;
06925    }
06926    errno = 0;
06927 
06928    return 0;
06929 }
06930 
06931 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
06932 {
06933    struct dahdi_pvt *p = chan->tech_pvt;
06934    int res = 0;
06935 
06936    if (!p) {
06937       /* No private structure! */
06938       *buf = '\0';
06939       return -1;
06940    }
06941 
06942    if (!strcasecmp(data, "rxgain")) {
06943       ast_mutex_lock(&p->lock);
06944       snprintf(buf, len, "%f", p->rxgain);
06945       ast_mutex_unlock(&p->lock);
06946    } else if (!strcasecmp(data, "txgain")) {
06947       ast_mutex_lock(&p->lock);
06948       snprintf(buf, len, "%f", p->txgain);
06949       ast_mutex_unlock(&p->lock);
06950    } else if (!strcasecmp(data, "dahdi_channel")) {
06951       ast_mutex_lock(&p->lock);
06952       snprintf(buf, len, "%d", p->channel);
06953       ast_mutex_unlock(&p->lock);
06954    } else if (!strcasecmp(data, "dahdi_span")) {
06955       ast_mutex_lock(&p->lock);
06956       snprintf(buf, len, "%d", p->span);
06957       ast_mutex_unlock(&p->lock);
06958    } else if (!strcasecmp(data, "dahdi_type")) {
06959       ast_mutex_lock(&p->lock);
06960       switch (p->sig) {
06961 #if defined(HAVE_OPENR2)
06962       case SIG_MFCR2:
06963          ast_copy_string(buf, "mfc/r2", len);
06964          break;
06965 #endif   /* defined(HAVE_OPENR2) */
06966 #if defined(HAVE_PRI)
06967       case SIG_PRI_LIB_HANDLE_CASES:
06968          ast_copy_string(buf, "pri", len);
06969          break;
06970 #endif   /* defined(HAVE_PRI) */
06971       case 0:
06972          ast_copy_string(buf, "pseudo", len);
06973          break;
06974 #if defined(HAVE_SS7)
06975       case SIG_SS7:
06976          ast_copy_string(buf, "ss7", len);
06977          break;
06978 #endif   /* defined(HAVE_SS7) */
06979       default:
06980          /* The only thing left is analog ports. */
06981          ast_copy_string(buf, "analog", len);
06982          break;
06983       }
06984       ast_mutex_unlock(&p->lock);
06985 #if defined(HAVE_PRI)
06986 #if defined(HAVE_PRI_REVERSE_CHARGE)
06987    } else if (!strcasecmp(data, "reversecharge")) {
06988       ast_mutex_lock(&p->lock);
06989       switch (p->sig) {
06990       case SIG_PRI_LIB_HANDLE_CASES:
06991          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->reverse_charging_indication);
06992          break;
06993       default:
06994          *buf = '\0';
06995          res = -1;
06996          break;
06997       }
06998       ast_mutex_unlock(&p->lock);
06999 #endif
07000 #if defined(HAVE_PRI_SETUP_KEYPAD)
07001    } else if (!strcasecmp(data, "keypad_digits")) {
07002       ast_mutex_lock(&p->lock);
07003       switch (p->sig) {
07004       case SIG_PRI_LIB_HANDLE_CASES:
07005          ast_copy_string(buf, ((struct sig_pri_chan *) p->sig_pvt)->keypad_digits,
07006             len);
07007          break;
07008       default:
07009          *buf = '\0';
07010          res = -1;
07011          break;
07012       }
07013       ast_mutex_unlock(&p->lock);
07014 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
07015    } else if (!strcasecmp(data, "no_media_path")) {
07016       ast_mutex_lock(&p->lock);
07017       switch (p->sig) {
07018       case SIG_PRI_LIB_HANDLE_CASES:
07019          /*
07020           * TRUE if the call is on hold or is call waiting because
07021           * there is no media path available.
07022           */
07023          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel);
07024          break;
07025       default:
07026          *buf = '\0';
07027          res = -1;
07028          break;
07029       }
07030       ast_mutex_unlock(&p->lock);
07031 #endif   /* defined(HAVE_PRI) */
07032    } else {
07033       *buf = '\0';
07034       res = -1;
07035    }
07036 
07037    return res;
07038 }
07039 
07040 
07041 static int parse_buffers_policy(const char *parse, int *num_buffers, int *policy)
07042 {
07043    int res;
07044    char policy_str[21] = "";
07045 
07046    if ((res = sscanf(parse, "%30d,%20s", num_buffers, policy_str)) != 2) {
07047       ast_log(LOG_WARNING, "Parsing buffer string '%s' failed.\n", parse);
07048       return 1;
07049    }
07050    if (*num_buffers < 0) {
07051       ast_log(LOG_WARNING, "Invalid buffer count given '%d'.\n", *num_buffers);
07052       return -1;
07053    }
07054    if (!strcasecmp(policy_str, "full")) {
07055       *policy = DAHDI_POLICY_WHEN_FULL;
07056    } else if (!strcasecmp(policy_str, "immediate")) {
07057       *policy = DAHDI_POLICY_IMMEDIATE;
07058 #if defined(HAVE_DAHDI_HALF_FULL)
07059    } else if (!strcasecmp(policy_str, "half")) {
07060       *policy = DAHDI_POLICY_HALF_FULL;
07061 #endif
07062    } else {
07063       ast_log(LOG_WARNING, "Invalid policy name given '%s'.\n", policy_str);
07064       return -1;
07065    }
07066 
07067    return 0;
07068 }
07069 
07070 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value)
07071 {
07072    struct dahdi_pvt *p = chan->tech_pvt;
07073    int res = 0;
07074 
07075    if (!p) {
07076       /* No private structure! */
07077       return -1;
07078    }
07079 
07080    if (!strcasecmp(data, "buffers")) {
07081       int num_bufs, policy;
07082 
07083       if (!(parse_buffers_policy(value, &num_bufs, &policy))) {
07084          struct dahdi_bufferinfo bi = {
07085             .txbufpolicy = policy,
07086             .rxbufpolicy = policy,
07087             .bufsize = p->bufsize,
07088             .numbufs = num_bufs,
07089          };
07090          int bpres;
07091 
07092          if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07093             ast_log(LOG_WARNING, "Channel '%d' unable to override buffer policy: %s\n", p->channel, strerror(errno));
07094          } else {
07095             p->bufferoverrideinuse = 1;
07096          }
07097       } else {
07098          res = -1;
07099       }
07100    } else if (!strcasecmp(data, "echocan_mode")) {
07101       if (!strcasecmp(value, "on")) {
07102          ast_mutex_lock(&p->lock);
07103          dahdi_enable_ec(p);
07104          ast_mutex_unlock(&p->lock);
07105       } else if (!strcasecmp(value, "off")) {
07106          ast_mutex_lock(&p->lock);
07107          dahdi_disable_ec(p);
07108          ast_mutex_unlock(&p->lock);
07109 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07110       } else if (!strcasecmp(value, "fax")) {
07111          int blah = 1;
07112 
07113          ast_mutex_lock(&p->lock);
07114          if (!p->echocanon) {
07115             dahdi_enable_ec(p);
07116          }
07117          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
07118             ast_log(LOG_WARNING, "Unable to place echocan into fax mode on channel %d: %s\n", p->channel, strerror(errno));
07119          }
07120          ast_mutex_unlock(&p->lock);
07121       } else if (!strcasecmp(value, "voice")) {
07122          int blah = 0;
07123 
07124          ast_mutex_lock(&p->lock);
07125          if (!p->echocanon) {
07126             dahdi_enable_ec(p);
07127          }
07128          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
07129             ast_log(LOG_WARNING, "Unable to place echocan into voice mode on channel %d: %s\n", p->channel, strerror(errno));
07130          }
07131          ast_mutex_unlock(&p->lock);
07132 #endif
07133       } else {
07134          ast_log(LOG_WARNING, "Unsupported value '%s' provided for '%s' item.\n", value, data);
07135          res = -1;
07136       }
07137    } else {
07138       res = -1;
07139    }
07140 
07141    return res;
07142 }
07143 
07144 static void dahdi_unlink(struct dahdi_pvt *slave, struct dahdi_pvt *master, int needlock)
07145 {
07146    /* Unlink a specific slave or all slaves/masters from a given master */
07147    int x;
07148    int hasslaves;
07149    if (!master)
07150       return;
07151    if (needlock) {
07152       ast_mutex_lock(&master->lock);
07153       if (slave) {
07154          while (ast_mutex_trylock(&slave->lock)) {
07155             DEADLOCK_AVOIDANCE(&master->lock);
07156          }
07157       }
07158    }
07159    hasslaves = 0;
07160    for (x = 0; x < MAX_SLAVES; x++) {
07161       if (master->slaves[x]) {
07162          if (!slave || (master->slaves[x] == slave)) {
07163             /* Take slave out of the conference */
07164             ast_debug(1, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
07165             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
07166             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
07167             master->slaves[x]->master = NULL;
07168             master->slaves[x] = NULL;
07169          } else
07170             hasslaves = 1;
07171       }
07172       if (!hasslaves)
07173          master->inconference = 0;
07174    }
07175    if (!slave) {
07176       if (master->master) {
07177          /* Take master out of the conference */
07178          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
07179          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
07180          hasslaves = 0;
07181          for (x = 0; x < MAX_SLAVES; x++) {
07182             if (master->master->slaves[x] == master)
07183                master->master->slaves[x] = NULL;
07184             else if (master->master->slaves[x])
07185                hasslaves = 1;
07186          }
07187          if (!hasslaves)
07188             master->master->inconference = 0;
07189       }
07190       master->master = NULL;
07191    }
07192    update_conf(master);
07193    if (needlock) {
07194       if (slave)
07195          ast_mutex_unlock(&slave->lock);
07196       ast_mutex_unlock(&master->lock);
07197    }
07198 }
07199 
07200 static void dahdi_link(struct dahdi_pvt *slave, struct dahdi_pvt *master) {
07201    int x;
07202    if (!slave || !master) {
07203       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
07204       return;
07205    }
07206    for (x = 0; x < MAX_SLAVES; x++) {
07207       if (!master->slaves[x]) {
07208          master->slaves[x] = slave;
07209          break;
07210       }
07211    }
07212    if (x >= MAX_SLAVES) {
07213       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
07214       master->slaves[MAX_SLAVES - 1] = slave;
07215    }
07216    if (slave->master)
07217       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
07218    slave->master = master;
07219 
07220    ast_debug(1, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
07221 }
07222 
07223 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)
07224 {
07225    struct ast_channel *who;
07226    struct dahdi_pvt *p0, *p1, *op0, *op1;
07227    struct dahdi_pvt *master = NULL, *slave = NULL;
07228    struct ast_frame *f;
07229    int inconf = 0;
07230    int nothingok = 1;
07231    int ofd0, ofd1;
07232    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
07233    int os0 = -1, os1 = -1;
07234    int priority = 0;
07235    struct ast_channel *oc0, *oc1;
07236    enum ast_bridge_result res;
07237    struct timeval start = ast_tvnow();
07238 #ifdef PRI_2BCT
07239    int triedtopribridge = 0;
07240    q931_call *q931c0;
07241    q931_call *q931c1;
07242 #endif
07243 
07244    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
07245       There is code below to handle it properly until DTMF is actually seen,
07246       but due to currently unresolved issues it's ignored...
07247    */
07248 
07249    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
07250       return AST_BRIDGE_FAILED_NOWARN;
07251 
07252    ast_channel_lock(c0);
07253    while (ast_channel_trylock(c1)) {
07254       CHANNEL_DEADLOCK_AVOIDANCE(c0);
07255    }
07256 
07257    p0 = c0->tech_pvt;
07258    p1 = c1->tech_pvt;
07259    /* cant do pseudo-channels here */
07260    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
07261       ast_channel_unlock(c0);
07262       ast_channel_unlock(c1);
07263       return AST_BRIDGE_FAILED_NOWARN;
07264    }
07265 
07266    oi0 = dahdi_get_index(c0, p0, 0);
07267    oi1 = dahdi_get_index(c1, p1, 0);
07268    if ((oi0 < 0) || (oi1 < 0)) {
07269       ast_channel_unlock(c0);
07270       ast_channel_unlock(c1);
07271       return AST_BRIDGE_FAILED;
07272    }
07273 
07274    op0 = p0 = c0->tech_pvt;
07275    op1 = p1 = c1->tech_pvt;
07276    ofd0 = c0->fds[0];
07277    ofd1 = c1->fds[0];
07278    oc0 = p0->owner;
07279    oc1 = p1->owner;
07280 
07281    if (ast_mutex_trylock(&p0->lock)) {
07282       /* Don't block, due to potential for deadlock */
07283       ast_channel_unlock(c0);
07284       ast_channel_unlock(c1);
07285       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
07286       return AST_BRIDGE_RETRY;
07287    }
07288    if (ast_mutex_trylock(&p1->lock)) {
07289       /* Don't block, due to potential for deadlock */
07290       ast_mutex_unlock(&p0->lock);
07291       ast_channel_unlock(c0);
07292       ast_channel_unlock(c1);
07293       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
07294       return AST_BRIDGE_RETRY;
07295    }
07296 
07297    if ((p0->callwaiting && p0->callwaitingcallerid)
07298       || (p1->callwaiting && p1->callwaitingcallerid)) {
07299       /*
07300        * Call Waiting Caller ID requires DTMF detection to know if it
07301        * can send the CID spill.
07302        *
07303        * For now, don't attempt to native bridge if either channel
07304        * needs DTMF detection.  There is code below to handle it
07305        * properly until DTMF is actually seen, but due to currently
07306        * unresolved issues it's ignored...
07307        */
07308       ast_mutex_unlock(&p0->lock);
07309       ast_mutex_unlock(&p1->lock);
07310       ast_channel_unlock(c0);
07311       ast_channel_unlock(c1);
07312       return AST_BRIDGE_FAILED_NOWARN;
07313    }
07314 
07315 #if defined(HAVE_PRI)
07316    if ((dahdi_sig_pri_lib_handles(p0->sig)
07317          && ((struct sig_pri_chan *) p0->sig_pvt)->no_b_channel)
07318       || (dahdi_sig_pri_lib_handles(p1->sig)
07319          && ((struct sig_pri_chan *) p1->sig_pvt)->no_b_channel)) {
07320       /*
07321        * PRI nobch channels (hold and call waiting) are equivalent to
07322        * pseudo channels and cannot be done here.
07323        */
07324       ast_mutex_unlock(&p0->lock);
07325       ast_mutex_unlock(&p1->lock);
07326       ast_channel_unlock(c0);
07327       ast_channel_unlock(c1);
07328       return AST_BRIDGE_FAILED_NOWARN;
07329    }
07330 #endif   /* defined(HAVE_PRI) */
07331 
07332    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07333       if (p0->owner && p1->owner) {
07334          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
07335          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
07336             master = p0;
07337             slave = p1;
07338             inconf = 1;
07339          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
07340             master = p1;
07341             slave = p0;
07342             inconf = 1;
07343          } else {
07344             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
07345             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
07346                p0->channel,
07347                oi0, (p0->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07348                p0->subs[SUB_REAL].inthreeway, p0->channel,
07349                oi0, (p1->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07350                p1->subs[SUB_REAL].inthreeway);
07351          }
07352          nothingok = 0;
07353       }
07354    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
07355       if (p1->subs[SUB_THREEWAY].inthreeway) {
07356          master = p1;
07357          slave = p0;
07358          nothingok = 0;
07359       }
07360    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
07361       if (p0->subs[SUB_THREEWAY].inthreeway) {
07362          master = p0;
07363          slave = p1;
07364          nothingok = 0;
07365       }
07366    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
07367       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise,
07368          don't put us in anything */
07369       if (p1->subs[SUB_CALLWAIT].inthreeway) {
07370          master = p1;
07371          slave = p0;
07372          nothingok = 0;
07373       }
07374    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
07375       /* Same as previous */
07376       if (p0->subs[SUB_CALLWAIT].inthreeway) {
07377          master = p0;
07378          slave = p1;
07379          nothingok = 0;
07380       }
07381    }
07382    ast_debug(1, "master: %d, slave: %d, nothingok: %d\n",
07383       master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
07384    if (master && slave) {
07385       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
07386          in an active threeway call with a channel that is ringing, we should
07387          indicate ringing. */
07388       if ((oi1 == SUB_THREEWAY) &&
07389          p1->subs[SUB_THREEWAY].inthreeway &&
07390          p1->subs[SUB_REAL].owner &&
07391          p1->subs[SUB_REAL].inthreeway &&
07392          (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07393          ast_debug(1,
07394             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
07395             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
07396          tone_zone_play_tone(p0->subs[oi0].dfd, DAHDI_TONE_RINGTONE);
07397          os1 = p1->subs[SUB_REAL].owner->_state;
07398       } else {
07399          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
07400             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
07401          tone_zone_play_tone(p0->subs[oi0].dfd, -1);
07402       }
07403       if ((oi0 == SUB_THREEWAY) &&
07404          p0->subs[SUB_THREEWAY].inthreeway &&
07405          p0->subs[SUB_REAL].owner &&
07406          p0->subs[SUB_REAL].inthreeway &&
07407          (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07408          ast_debug(1,
07409             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
07410             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
07411          tone_zone_play_tone(p1->subs[oi1].dfd, DAHDI_TONE_RINGTONE);
07412          os0 = p0->subs[SUB_REAL].owner->_state;
07413       } else {
07414          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
07415             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
07416          tone_zone_play_tone(p1->subs[oi1].dfd, -1);
07417       }
07418       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07419          if (!p0->echocanbridged || !p1->echocanbridged) {
07420             /* Disable echo cancellation if appropriate */
07421             dahdi_disable_ec(p0);
07422             dahdi_disable_ec(p1);
07423          }
07424       }
07425       dahdi_link(slave, master);
07426       master->inconference = inconf;
07427    } else if (!nothingok)
07428       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
07429 
07430    update_conf(p0);
07431    update_conf(p1);
07432    t0 = p0->subs[SUB_REAL].inthreeway;
07433    t1 = p1->subs[SUB_REAL].inthreeway;
07434 
07435    ast_mutex_unlock(&p0->lock);
07436    ast_mutex_unlock(&p1->lock);
07437 
07438    ast_channel_unlock(c0);
07439    ast_channel_unlock(c1);
07440 
07441    /* Native bridge failed */
07442    if ((!master || !slave) && !nothingok) {
07443       dahdi_enable_ec(p0);
07444       dahdi_enable_ec(p1);
07445       return AST_BRIDGE_FAILED;
07446    }
07447 
07448    ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
07449 
07450    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07451       disable_dtmf_detect(op0);
07452 
07453    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07454       disable_dtmf_detect(op1);
07455 
07456    for (;;) {
07457       struct ast_channel *c0_priority[2] = {c0, c1};
07458       struct ast_channel *c1_priority[2] = {c1, c0};
07459       int ms;
07460 
07461       /* Here's our main loop...  Start by locking things, looking for private parts,
07462          and then balking if anything is wrong */
07463 
07464       ast_channel_lock(c0);
07465       while (ast_channel_trylock(c1)) {
07466          CHANNEL_DEADLOCK_AVOIDANCE(c0);
07467       }
07468 
07469       p0 = c0->tech_pvt;
07470       p1 = c1->tech_pvt;
07471 
07472       if (op0 == p0)
07473          i0 = dahdi_get_index(c0, p0, 1);
07474       if (op1 == p1)
07475          i1 = dahdi_get_index(c1, p1, 1);
07476 
07477       ast_channel_unlock(c0);
07478       ast_channel_unlock(c1);
07479       ms = ast_remaining_ms(start, timeoutms);
07480       if (!ms ||
07481          (op0 != p0) ||
07482          (op1 != p1) ||
07483          (ofd0 != c0->fds[0]) ||
07484          (ofd1 != c1->fds[0]) ||
07485          (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
07486          (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
07487          (oc0 != p0->owner) ||
07488          (oc1 != p1->owner) ||
07489          (t0 != p0->subs[SUB_REAL].inthreeway) ||
07490          (t1 != p1->subs[SUB_REAL].inthreeway) ||
07491          (oi0 != i0) ||
07492          (oi1 != i1)) {
07493          ast_debug(1, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
07494             op0->channel, oi0, op1->channel, oi1);
07495          res = AST_BRIDGE_RETRY;
07496          goto return_from_bridge;
07497       }
07498 
07499 #ifdef PRI_2BCT
07500       if (!triedtopribridge) {
07501          triedtopribridge = 1;
07502          if (p0->pri && p0->pri == p1->pri && p0->pri->transfer) {
07503             ast_mutex_lock(&p0->pri->lock);
07504             switch (p0->sig) {
07505             case SIG_PRI_LIB_HANDLE_CASES:
07506                q931c0 = ((struct sig_pri_chan *) (p0->sig_pvt))->call;
07507                break;
07508             default:
07509                q931c0 = NULL;
07510                break;
07511             }
07512             switch (p1->sig) {
07513             case SIG_PRI_LIB_HANDLE_CASES:
07514                q931c1 = ((struct sig_pri_chan *) (p1->sig_pvt))->call;
07515                break;
07516             default:
07517                q931c1 = NULL;
07518                break;
07519             }
07520             if (q931c0 && q931c1) {
07521                pri_channel_bridge(q931c0, q931c1);
07522             }
07523             ast_mutex_unlock(&p0->pri->lock);
07524          }
07525       }
07526 #endif
07527 
07528       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &ms);
07529       if (!who) {
07530          ast_debug(1, "Ooh, empty read...\n");
07531          continue;
07532       }
07533       f = ast_read(who);
07534       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
07535          *fo = f;
07536          *rc = who;
07537          res = AST_BRIDGE_COMPLETE;
07538          goto return_from_bridge;
07539       }
07540       if (f->frametype == AST_FRAME_DTMF) {
07541          if ((who == c0) && p0->pulsedial) {
07542             ast_write(c1, f);
07543          } else if ((who == c1) && p1->pulsedial) {
07544             ast_write(c0, f);
07545          } else {
07546             *fo = f;
07547             *rc = who;
07548             res = AST_BRIDGE_COMPLETE;
07549             goto return_from_bridge;
07550          }
07551       }
07552       ast_frfree(f);
07553 
07554       /* Swap who gets priority */
07555       priority = !priority;
07556    }
07557 
07558 return_from_bridge:
07559    if (op0 == p0)
07560       dahdi_enable_ec(p0);
07561 
07562    if (op1 == p1)
07563       dahdi_enable_ec(p1);
07564 
07565    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07566       enable_dtmf_detect(op0);
07567 
07568    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07569       enable_dtmf_detect(op1);
07570 
07571    dahdi_unlink(slave, master, 1);
07572 
07573    return res;
07574 }
07575 
07576 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07577 {
07578    struct dahdi_pvt *p = newchan->tech_pvt;
07579    int x;
07580 
07581    ast_mutex_lock(&p->lock);
07582 
07583    ast_debug(1, "New owner for channel %d is %s\n", p->channel, newchan->name);
07584    if (p->owner == oldchan) {
07585       p->owner = newchan;
07586    }
07587    for (x = 0; x < 3; x++) {
07588       if (p->subs[x].owner == oldchan) {
07589          if (!x) {
07590             dahdi_unlink(NULL, p, 0);
07591          }
07592          p->subs[x].owner = newchan;
07593       }
07594    }
07595    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
07596       analog_fixup(oldchan, newchan, p->sig_pvt);
07597 #if defined(HAVE_PRI)
07598    } else if (dahdi_sig_pri_lib_handles(p->sig)) {
07599       sig_pri_fixup(oldchan, newchan, p->sig_pvt);
07600 #endif   /* defined(HAVE_PRI) */
07601 #if defined(HAVE_SS7)
07602    } else if (p->sig == SIG_SS7) {
07603       sig_ss7_fixup(oldchan, newchan, p->sig_pvt);
07604 #endif   /* defined(HAVE_SS7) */
07605    }
07606    update_conf(p);
07607 
07608    ast_mutex_unlock(&p->lock);
07609 
07610    if (newchan->_state == AST_STATE_RINGING) {
07611       dahdi_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
07612    }
07613    return 0;
07614 }
07615 
07616 static int dahdi_ring_phone(struct dahdi_pvt *p)
07617 {
07618    int x;
07619    int res;
07620    /* Make sure our transmit state is on hook */
07621    x = 0;
07622    x = DAHDI_ONHOOK;
07623    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07624    do {
07625       x = DAHDI_RING;
07626       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07627       if (res) {
07628          switch (errno) {
07629          case EBUSY:
07630          case EINTR:
07631             /* Wait just in case */
07632             usleep(10000);
07633             continue;
07634          case EINPROGRESS:
07635             res = 0;
07636             break;
07637          default:
07638             ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
07639             res = 0;
07640          }
07641       }
07642    } while (res);
07643    return res;
07644 }
07645 
07646 static void *analog_ss_thread(void *data);
07647 
07648 static int attempt_transfer(struct dahdi_pvt *p)
07649 {
07650    /* In order to transfer, we need at least one of the channels to
07651       actually be in a call bridge.  We can't conference two applications
07652       together (but then, why would we want to?) */
07653    if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
07654       /* The three-way person we're about to transfer to could still be in MOH, so
07655          stop if now if appropriate */
07656       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
07657          ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
07658       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
07659          ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
07660       }
07661       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
07662          tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, DAHDI_TONE_RINGTONE);
07663       }
07664        if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
07665          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07666                ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
07667          return -1;
07668       }
07669       /* Orphan the channel after releasing the lock */
07670       ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07671       unalloc_sub(p, SUB_THREEWAY);
07672    } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
07673       ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
07674       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
07675          ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
07676       }
07677       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
07678          tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
07679       }
07680       if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
07681          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07682                ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
07683          return -1;
07684       }
07685       /* Three-way is now the REAL */
07686       swap_subs(p, SUB_THREEWAY, SUB_REAL);
07687       ast_channel_unlock(p->subs[SUB_REAL].owner);
07688       unalloc_sub(p, SUB_THREEWAY);
07689       /* Tell the caller not to hangup */
07690       return 1;
07691    } else {
07692       ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
07693          p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
07694       p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07695       return -1;
07696    }
07697    return 0;
07698 }
07699 
07700 static int check_for_conference(struct dahdi_pvt *p)
07701 {
07702    struct dahdi_confinfo ci;
07703    /* Fine if we already have a master, etc */
07704    if (p->master || (p->confno > -1))
07705       return 0;
07706    memset(&ci, 0, sizeof(ci));
07707    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
07708       ast_log(LOG_WARNING, "Failed to get conference info on channel %d: %s\n", p->channel, strerror(errno));
07709       return 0;
07710    }
07711    /* If we have no master and don't have a confno, then
07712       if we're in a conference, it's probably a MeetMe room or
07713       some such, so don't let us 3-way out! */
07714    if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
07715       ast_verb(3, "Avoiding 3-way call when in an external conference\n");
07716       return 1;
07717    }
07718    return 0;
07719 }
07720 
07721 /*! Checks channel for alarms
07722  * \param p a channel to check for alarms.
07723  * \returns the alarms on the span to which the channel belongs, or alarms on
07724  *          the channel if no span alarms.
07725  */
07726 static int get_alarms(struct dahdi_pvt *p)
07727 {
07728    int res;
07729    struct dahdi_spaninfo zi;
07730    struct dahdi_params params;
07731 
07732    memset(&zi, 0, sizeof(zi));
07733    zi.spanno = p->span;
07734 
07735    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SPANSTAT, &zi)) >= 0) {
07736       if (zi.alarms != DAHDI_ALARM_NONE)
07737          return zi.alarms;
07738    } else {
07739       ast_log(LOG_WARNING, "Unable to determine alarm on channel %d: %s\n", p->channel, strerror(errno));
07740       return 0;
07741    }
07742 
07743    /* No alarms on the span. Check for channel alarms. */
07744    memset(&params, 0, sizeof(params));
07745    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &params)) >= 0)
07746       return params.chan_alarms;
07747 
07748    ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
07749 
07750    return DAHDI_ALARM_NONE;
07751 }
07752 
07753 static void dahdi_handle_dtmf(struct ast_channel *ast, int idx, struct ast_frame **dest)
07754 {
07755    struct dahdi_pvt *p = ast->tech_pvt;
07756    struct ast_frame *f = *dest;
07757 
07758    ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
07759       f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
07760       f->subclass.integer, f->subclass.integer, ast->name);
07761 
07762    if (p->confirmanswer) {
07763       if (f->frametype == AST_FRAME_DTMF_END) {
07764          ast_debug(1, "Confirm answer on %s!\n", ast->name);
07765          /* Upon receiving a DTMF digit, consider this an answer confirmation instead
07766             of a DTMF digit */
07767          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07768          p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07769          /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
07770          p->confirmanswer = 0;
07771       } else {
07772          p->subs[idx].f.frametype = AST_FRAME_NULL;
07773          p->subs[idx].f.subclass.integer = 0;
07774       }
07775       *dest = &p->subs[idx].f;
07776    } else if (p->callwaitcas) {
07777       if (f->frametype == AST_FRAME_DTMF_END) {
07778          if ((f->subclass.integer == 'A') || (f->subclass.integer == 'D')) {
07779             ast_debug(1, "Got some DTMF, but it's for the CAS\n");
07780             ast_free(p->cidspill);
07781             p->cidspill = NULL;
07782             send_cwcidspill(p);
07783          }
07784          p->callwaitcas = 0;
07785       }
07786       p->subs[idx].f.frametype = AST_FRAME_NULL;
07787       p->subs[idx].f.subclass.integer = 0;
07788       *dest = &p->subs[idx].f;
07789    } else if (f->subclass.integer == 'f') {
07790       if (f->frametype == AST_FRAME_DTMF_END) {
07791          /* Fax tone -- Handle and return NULL */
07792          if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
07793             /* If faxbuffers are configured, use them for the fax transmission */
07794             if (p->usefaxbuffers && !p->bufferoverrideinuse) {
07795                struct dahdi_bufferinfo bi = {
07796                   .txbufpolicy = p->faxbuf_policy,
07797                   .bufsize = p->bufsize,
07798                   .numbufs = p->faxbuf_no
07799                };
07800                int res;
07801 
07802                if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07803                   ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
07804                } else {
07805                   p->bufferoverrideinuse = 1;
07806                }
07807             }
07808             p->faxhandled = 1;
07809             if (p->dsp) {
07810                p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
07811                ast_dsp_set_features(p->dsp, p->dsp_features);
07812                ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
07813             }
07814             if (strcmp(ast->exten, "fax")) {
07815                const char *target_context = S_OR(ast->macrocontext, ast->context);
07816 
07817                /* We need to unlock 'ast' here because ast_exists_extension has the
07818                 * potential to start autoservice on the channel. Such action is prone
07819                 * to deadlock.
07820                 */
07821                ast_mutex_unlock(&p->lock);
07822                ast_channel_unlock(ast);
07823                if (ast_exists_extension(ast, target_context, "fax", 1,
07824                   S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07825                   ast_channel_lock(ast);
07826                   ast_mutex_lock(&p->lock);
07827                   ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
07828                   /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
07829                   pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07830                   if (ast_async_goto(ast, target_context, "fax", 1))
07831                      ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07832                } else {
07833                   ast_channel_lock(ast);
07834                   ast_mutex_lock(&p->lock);
07835                   ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
07836                }
07837             } else {
07838                ast_debug(1, "Already in a fax extension, not redirecting\n");
07839             }
07840          } else {
07841             ast_debug(1, "Fax already handled\n");
07842          }
07843          dahdi_confmute(p, 0);
07844       }
07845       p->subs[idx].f.frametype = AST_FRAME_NULL;
07846       p->subs[idx].f.subclass.integer = 0;
07847       *dest = &p->subs[idx].f;
07848    }
07849 }
07850 
07851 static void handle_alarms(struct dahdi_pvt *p, int alms)
07852 {
07853    const char *alarm_str;
07854 
07855 #if defined(HAVE_PRI)
07856    if (dahdi_sig_pri_lib_handles(p->sig) && sig_pri_is_alarm_ignored(p->pri)) {
07857       return;
07858    }
07859 #endif   /* defined(HAVE_PRI) */
07860 
07861    alarm_str = alarm2str(alms);
07862    if (report_alarms & REPORT_CHANNEL_ALARMS) {
07863       ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm_str);
07864       manager_event(EVENT_FLAG_SYSTEM, "Alarm",
07865                  "Alarm: %s\r\n"
07866                  "Channel: %d\r\n",
07867                  alarm_str, p->channel);
07868    }
07869 
07870    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
07871       ast_log(LOG_WARNING, "Detected alarm on span %d: %s\n", p->span, alarm_str);
07872       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarm",
07873                  "Alarm: %s\r\n"
07874                  "Span: %d\r\n",
07875                  alarm_str, p->span);
07876    }
07877 }
07878 
07879 static struct ast_frame *dahdi_handle_event(struct ast_channel *ast)
07880 {
07881    int res, x;
07882    int idx, mysig;
07883    char *c;
07884    struct dahdi_pvt *p = ast->tech_pvt;
07885    pthread_t threadid;
07886    struct ast_channel *chan;
07887    struct ast_frame *f;
07888 
07889    idx = dahdi_get_index(ast, p, 0);
07890    if (idx < 0) {
07891       return &ast_null_frame;
07892    }
07893    mysig = p->sig;
07894    if (p->outsigmod > -1)
07895       mysig = p->outsigmod;
07896    p->subs[idx].f.frametype = AST_FRAME_NULL;
07897    p->subs[idx].f.subclass.integer = 0;
07898    p->subs[idx].f.datalen = 0;
07899    p->subs[idx].f.samples = 0;
07900    p->subs[idx].f.mallocd = 0;
07901    p->subs[idx].f.offset = 0;
07902    p->subs[idx].f.src = "dahdi_handle_event";
07903    p->subs[idx].f.data.ptr = NULL;
07904    f = &p->subs[idx].f;
07905 
07906    if (p->fake_event) {
07907       res = p->fake_event;
07908       p->fake_event = 0;
07909    } else
07910       res = dahdi_get_event(p->subs[idx].dfd);
07911 
07912    ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, idx);
07913 
07914    if (res & (DAHDI_EVENT_PULSEDIGIT | DAHDI_EVENT_DTMFUP)) {
07915       p->pulsedial = (res & DAHDI_EVENT_PULSEDIGIT) ? 1 : 0;
07916       ast_debug(1, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
07917 #if defined(HAVE_PRI)
07918       if (dahdi_sig_pri_lib_handles(p->sig)
07919          && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
07920          && p->pri
07921          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07922          /* absorb event */
07923       } else
07924 #endif   /* defined(HAVE_PRI) */
07925       {
07926          /* Unmute conference */
07927          dahdi_confmute(p, 0);
07928          p->subs[idx].f.frametype = AST_FRAME_DTMF_END;
07929          p->subs[idx].f.subclass.integer = res & 0xff;
07930          dahdi_handle_dtmf(ast, idx, &f);
07931       }
07932       return f;
07933    }
07934 
07935    if (res & DAHDI_EVENT_DTMFDOWN) {
07936       ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
07937 #if defined(HAVE_PRI)
07938       if (dahdi_sig_pri_lib_handles(p->sig)
07939          && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
07940          && p->pri
07941          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07942          /* absorb event */
07943       } else
07944 #endif   /* defined(HAVE_PRI) */
07945       {
07946          /* Mute conference */
07947          dahdi_confmute(p, 1);
07948          p->subs[idx].f.frametype = AST_FRAME_DTMF_BEGIN;
07949          p->subs[idx].f.subclass.integer = res & 0xff;
07950          dahdi_handle_dtmf(ast, idx, &f);
07951       }
07952       return &p->subs[idx].f;
07953    }
07954 
07955    switch (res) {
07956    case DAHDI_EVENT_EC_DISABLED:
07957       ast_verb(3, "Channel %d echo canceler disabled.\n", p->channel);
07958       p->echocanon = 0;
07959       break;
07960 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07961    case DAHDI_EVENT_TX_CED_DETECTED:
07962       ast_verb(3, "Channel %d detected a CED tone towards the network.\n", p->channel);
07963       break;
07964    case DAHDI_EVENT_RX_CED_DETECTED:
07965       ast_verb(3, "Channel %d detected a CED tone from the network.\n", p->channel);
07966       break;
07967    case DAHDI_EVENT_EC_NLP_DISABLED:
07968       ast_verb(3, "Channel %d echo canceler disabled its NLP.\n", p->channel);
07969       break;
07970    case DAHDI_EVENT_EC_NLP_ENABLED:
07971       ast_verb(3, "Channel %d echo canceler enabled its NLP.\n", p->channel);
07972       break;
07973 #endif
07974    case DAHDI_EVENT_BITSCHANGED:
07975 #ifdef HAVE_OPENR2
07976       if (p->sig != SIG_MFCR2) {
07977          ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07978       } else {
07979          ast_log(LOG_DEBUG, "bits changed in chan %d\n", p->channel);
07980          openr2_chan_handle_cas(p->r2chan);
07981       }
07982 #else
07983       ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07984 #endif
07985       break;
07986    case DAHDI_EVENT_PULSE_START:
07987       /* Stop tone if there's a pulse start and the PBX isn't started */
07988       if (!ast->pbx)
07989          tone_zone_play_tone(p->subs[idx].dfd, -1);
07990       break;
07991    case DAHDI_EVENT_DIALCOMPLETE:
07992       /* DAHDI has completed dialing all digits sent using DAHDI_DIAL. */
07993 #if defined(HAVE_PRI)
07994       if (dahdi_sig_pri_lib_handles(p->sig)) {
07995          if (p->inalarm) {
07996             break;
07997          }
07998          if (ioctl(p->subs[idx].dfd, DAHDI_DIALING, &x) == -1) {
07999             ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n", ast->name,
08000                strerror(errno));
08001             return NULL;
08002          }
08003          if (x) {
08004             /* Still dialing in DAHDI driver */
08005             break;
08006          }
08007          /*
08008           * The ast channel is locked and the private may be locked more
08009           * than once.
08010           */
08011          sig_pri_dial_complete(p->sig_pvt, ast);
08012          break;
08013       }
08014 #endif   /* defined(HAVE_PRI) */
08015 #ifdef HAVE_OPENR2
08016       if ((p->sig & SIG_MFCR2) && p->r2chan && ast->_state != AST_STATE_UP) {
08017          /* we don't need to do anything for this event for R2 signaling
08018             if the call is being setup */
08019          break;
08020       }
08021 #endif
08022       if (p->inalarm) break;
08023       if ((p->radio || (p->oprmode < 0))) break;
08024       if (ioctl(p->subs[idx].dfd,DAHDI_DIALING,&x) == -1) {
08025          ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n",ast->name, strerror(errno));
08026          return NULL;
08027       }
08028       if (!x) { /* if not still dialing in driver */
08029          dahdi_enable_ec(p);
08030          if (p->echobreak) {
08031             dahdi_train_ec(p);
08032             ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
08033             p->dop.op = DAHDI_DIAL_OP_REPLACE;
08034             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08035             p->echobreak = 0;
08036          } else {
08037             p->dialing = 0;
08038             if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
08039                /* if thru with dialing after offhook */
08040                if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
08041                   ast_setstate(ast, AST_STATE_UP);
08042                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08043                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08044                   break;
08045                } else { /* if to state wait for offhook to dial rest */
08046                   /* we now wait for off hook */
08047                   ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
08048                }
08049             }
08050             if (ast->_state == AST_STATE_DIALING) {
08051                if ((p->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
08052                   ast_debug(1, "Done dialing, but waiting for progress detection before doing more...\n");
08053                } else if (p->confirmanswer || (!p->dialednone
08054                   && ((mysig == SIG_EM) || (mysig == SIG_EM_E1)
08055                      || (mysig == SIG_EMWINK) || (mysig == SIG_FEATD)
08056                      || (mysig == SIG_FEATDMF_TA) || (mysig == SIG_FEATDMF)
08057                      || (mysig == SIG_E911) || (mysig == SIG_FGC_CAMA)
08058                      || (mysig == SIG_FGC_CAMAMF) || (mysig == SIG_FEATB)
08059                      || (mysig == SIG_SF) || (mysig == SIG_SFWINK)
08060                      || (mysig == SIG_SF_FEATD) || (mysig == SIG_SF_FEATDMF)
08061                      || (mysig == SIG_SF_FEATB)))) {
08062                   ast_setstate(ast, AST_STATE_RINGING);
08063                } else if (!p->answeronpolarityswitch) {
08064                   ast_setstate(ast, AST_STATE_UP);
08065                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08066                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08067                   /* If aops=0 and hops=1, this is necessary */
08068                   p->polarity = POLARITY_REV;
08069                } else {
08070                   /* Start clean, so we can catch the change to REV polarity when party answers */
08071                   p->polarity = POLARITY_IDLE;
08072                }
08073             }
08074          }
08075       }
08076       break;
08077    case DAHDI_EVENT_ALARM:
08078       switch (p->sig) {
08079 #if defined(HAVE_PRI)
08080       case SIG_PRI_LIB_HANDLE_CASES:
08081          sig_pri_chan_alarm_notify(p->sig_pvt, 0);
08082          break;
08083 #endif   /* defined(HAVE_PRI) */
08084 #if defined(HAVE_SS7)
08085       case SIG_SS7:
08086          sig_ss7_set_alarm(p->sig_pvt, 1);
08087          break;
08088 #endif   /* defined(HAVE_SS7) */
08089       default:
08090          p->inalarm = 1;
08091          break;
08092       }
08093       res = get_alarms(p);
08094       handle_alarms(p, res);
08095 #ifdef HAVE_PRI
08096       if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
08097          /* fall through intentionally */
08098       } else {
08099          break;
08100       }
08101 #endif
08102 #if defined(HAVE_SS7)
08103       if (p->sig == SIG_SS7)
08104          break;
08105 #endif   /* defined(HAVE_SS7) */
08106 #ifdef HAVE_OPENR2
08107       if (p->sig == SIG_MFCR2)
08108          break;
08109 #endif
08110    case DAHDI_EVENT_ONHOOK:
08111       if (p->radio) {
08112          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08113          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08114          break;
08115       }
08116       if (p->oprmode < 0)
08117       {
08118          if (p->oprmode != -1) break;
08119          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
08120          {
08121             /* Make sure it starts ringing */
08122             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08123             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RING);
08124             save_conference(p->oprpeer);
08125             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08126          }
08127          break;
08128       }
08129       switch (p->sig) {
08130       case SIG_FXOLS:
08131       case SIG_FXOGS:
08132       case SIG_FXOKS:
08133          /* Check for some special conditions regarding call waiting */
08134          if (idx == SUB_REAL) {
08135             /* The normal line was hung up */
08136             if (p->subs[SUB_CALLWAIT].owner) {
08137                /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
08138                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
08139                ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
08140                unalloc_sub(p, SUB_CALLWAIT);
08141 #if 0
08142                p->subs[idx].needanswer = 0;
08143                p->subs[idx].needringing = 0;
08144 #endif
08145                p->callwaitingrepeat = 0;
08146                p->cidcwexpire = 0;
08147                p->cid_suppress_expire = 0;
08148                p->owner = NULL;
08149                /* Don't start streaming audio yet if the incoming call isn't up yet */
08150                if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
08151                   p->dialing = 1;
08152                dahdi_ring_phone(p);
08153             } else if (p->subs[SUB_THREEWAY].owner) {
08154                unsigned int mssinceflash;
08155                /* Here we have to retain the lock on both the main channel, the 3-way channel, and
08156                   the private structure -- not especially easy or clean */
08157                while (p->subs[SUB_THREEWAY].owner && ast_channel_trylock(p->subs[SUB_THREEWAY].owner)) {
08158                   /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
08159                   DLA_UNLOCK(&p->lock);
08160                   CHANNEL_DEADLOCK_AVOIDANCE(ast);
08161                   /* We can grab ast and p in that order, without worry.  We should make sure
08162                      nothing seriously bad has happened though like some sort of bizarre double
08163                      masquerade! */
08164                   DLA_LOCK(&p->lock);
08165                   if (p->owner != ast) {
08166                      ast_log(LOG_WARNING, "This isn't good...\n");
08167                      return NULL;
08168                   }
08169                }
08170                if (!p->subs[SUB_THREEWAY].owner) {
08171                   ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
08172                   return NULL;
08173                }
08174                mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
08175                ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
08176                if (mssinceflash < MIN_MS_SINCE_FLASH) {
08177                   /* It hasn't been long enough since the last flashook.  This is probably a bounce on
08178                      hanging up.  Hangup both channels now */
08179                   if (p->subs[SUB_THREEWAY].owner)
08180                      ast_queue_hangup_with_cause(p->subs[SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
08181                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08182                   ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
08183                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08184                } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
08185                   if (p->transfer) {
08186                      /* In any case this isn't a threeway call anymore */
08187                      p->subs[SUB_REAL].inthreeway = 0;
08188                      p->subs[SUB_THREEWAY].inthreeway = 0;
08189                      /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
08190                      if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
08191                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08192                         /* Swap subs and dis-own channel */
08193                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
08194                         p->owner = NULL;
08195                         /* Ring the phone */
08196                         dahdi_ring_phone(p);
08197                      } else {
08198                         if ((res = attempt_transfer(p)) < 0) {
08199                            p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08200                            if (p->subs[SUB_THREEWAY].owner)
08201                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08202                         } else if (res) {
08203                            /* Don't actually hang up at this point */
08204                            if (p->subs[SUB_THREEWAY].owner)
08205                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08206                            break;
08207                         }
08208                      }
08209                   } else {
08210                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08211                      if (p->subs[SUB_THREEWAY].owner)
08212                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08213                   }
08214                } else {
08215                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
08216                   /* Swap subs and dis-own channel */
08217                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08218                   p->owner = NULL;
08219                   /* Ring the phone */
08220                   dahdi_ring_phone(p);
08221                }
08222             }
08223          } else {
08224             ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", idx);
08225          }
08226          /* Fall through */
08227       default:
08228          dahdi_disable_ec(p);
08229          return NULL;
08230       }
08231       break;
08232    case DAHDI_EVENT_RINGOFFHOOK:
08233       if (p->inalarm) break;
08234       if (p->oprmode < 0)
08235       {
08236          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
08237          {
08238             /* Make sure it stops ringing */
08239             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08240             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, -1);
08241             restore_conference(p->oprpeer);
08242          }
08243          break;
08244       }
08245       if (p->radio)
08246       {
08247          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08248          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08249          break;
08250       }
08251       /* for E911, its supposed to wait for offhook then dial
08252          the second half of the dial string */
08253       if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
08254          c = strchr(p->dialdest, '/');
08255          if (c)
08256             c++;
08257          else
08258             c = p->dialdest;
08259          if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
08260          else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
08261          if (strlen(p->dop.dialstr) > 4) {
08262             memset(p->echorest, 'w', sizeof(p->echorest) - 1);
08263             strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
08264             p->echorest[sizeof(p->echorest) - 1] = '\0';
08265             p->echobreak = 1;
08266             p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
08267          } else
08268             p->echobreak = 0;
08269          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
08270             int saveerr = errno;
08271 
08272             x = DAHDI_ONHOOK;
08273             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
08274             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
08275             return NULL;
08276             }
08277          p->dialing = 1;
08278          return &p->subs[idx].f;
08279       }
08280       switch (p->sig) {
08281       case SIG_FXOLS:
08282       case SIG_FXOGS:
08283       case SIG_FXOKS:
08284          switch (ast->_state) {
08285          case AST_STATE_RINGING:
08286             dahdi_enable_ec(p);
08287             dahdi_train_ec(p);
08288             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08289             p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08290             /* Make sure it stops ringing */
08291             p->subs[SUB_REAL].needringing = 0;
08292             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
08293             ast_debug(1, "channel %d answered\n", p->channel);
08294 
08295             /* Cancel any running CallerID spill */
08296             ast_free(p->cidspill);
08297             p->cidspill = NULL;
08298             restore_conference(p);
08299 
08300             p->dialing = 0;
08301             p->callwaitcas = 0;
08302             if (p->confirmanswer) {
08303                /* Ignore answer if "confirm answer" is enabled */
08304                p->subs[idx].f.frametype = AST_FRAME_NULL;
08305                p->subs[idx].f.subclass.integer = 0;
08306             } else if (!ast_strlen_zero(p->dop.dialstr)) {
08307                /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
08308                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08309                if (res < 0) {
08310                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08311                   p->dop.dialstr[0] = '\0';
08312                   return NULL;
08313                } else {
08314                   ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
08315                   p->subs[idx].f.frametype = AST_FRAME_NULL;
08316                   p->subs[idx].f.subclass.integer = 0;
08317                   p->dialing = 1;
08318                }
08319                p->dop.dialstr[0] = '\0';
08320                ast_setstate(ast, AST_STATE_DIALING);
08321             } else
08322                ast_setstate(ast, AST_STATE_UP);
08323             return &p->subs[idx].f;
08324          case AST_STATE_DOWN:
08325             ast_setstate(ast, AST_STATE_RING);
08326             ast->rings = 1;
08327             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08328             p->subs[idx].f.subclass.integer = AST_CONTROL_OFFHOOK;
08329             ast_debug(1, "channel %d picked up\n", p->channel);
08330             return &p->subs[idx].f;
08331          case AST_STATE_UP:
08332             /* Make sure it stops ringing */
08333             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
08334             /* Okay -- probably call waiting*/
08335             if (ast_bridged_channel(p->owner))
08336                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08337             p->subs[idx].needunhold = 1;
08338             break;
08339          case AST_STATE_RESERVED:
08340             /* Start up dialtone */
08341             if (has_voicemail(p))
08342                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
08343             else
08344                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
08345             break;
08346          default:
08347             ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
08348          }
08349          break;
08350       case SIG_FXSLS:
08351       case SIG_FXSGS:
08352       case SIG_FXSKS:
08353          if (ast->_state == AST_STATE_RING) {
08354             p->ringt = p->ringt_base;
08355          }
08356 
08357          /* If we get a ring then we cannot be in
08358           * reversed polarity. So we reset to idle */
08359          ast_debug(1, "Setting IDLE polarity due "
08360             "to ring. Old polarity was %d\n",
08361             p->polarity);
08362          p->polarity = POLARITY_IDLE;
08363 
08364          /* Fall through */
08365       case SIG_EM:
08366       case SIG_EM_E1:
08367       case SIG_EMWINK:
08368       case SIG_FEATD:
08369       case SIG_FEATDMF:
08370       case SIG_FEATDMF_TA:
08371       case SIG_E911:
08372       case SIG_FGC_CAMA:
08373       case SIG_FGC_CAMAMF:
08374       case SIG_FEATB:
08375       case SIG_SF:
08376       case SIG_SFWINK:
08377       case SIG_SF_FEATD:
08378       case SIG_SF_FEATDMF:
08379       case SIG_SF_FEATB:
08380          if (ast->_state == AST_STATE_PRERING)
08381             ast_setstate(ast, AST_STATE_RING);
08382          if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
08383             ast_debug(1, "Ring detected\n");
08384             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08385             p->subs[idx].f.subclass.integer = AST_CONTROL_RING;
08386          } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
08387             ast_debug(1, "Line answered\n");
08388             if (p->confirmanswer) {
08389                p->subs[idx].f.frametype = AST_FRAME_NULL;
08390                p->subs[idx].f.subclass.integer = 0;
08391             } else {
08392                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08393                p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08394                ast_setstate(ast, AST_STATE_UP);
08395             }
08396          } else if (ast->_state != AST_STATE_RING)
08397             ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
08398          break;
08399       default:
08400          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08401       }
08402       break;
08403    case DAHDI_EVENT_RINGBEGIN:
08404       switch (p->sig) {
08405       case SIG_FXSLS:
08406       case SIG_FXSGS:
08407       case SIG_FXSKS:
08408          if (ast->_state == AST_STATE_RING) {
08409             p->ringt = p->ringt_base;
08410          }
08411          break;
08412       }
08413       break;
08414    case DAHDI_EVENT_RINGERON:
08415       break;
08416    case DAHDI_EVENT_NOALARM:
08417       switch (p->sig) {
08418 #if defined(HAVE_PRI)
08419       case SIG_PRI_LIB_HANDLE_CASES:
08420          sig_pri_chan_alarm_notify(p->sig_pvt, 1);
08421          break;
08422 #endif   /* defined(HAVE_PRI) */
08423 #if defined(HAVE_SS7)
08424       case SIG_SS7:
08425          sig_ss7_set_alarm(p->sig_pvt, 0);
08426          break;
08427 #endif   /* defined(HAVE_SS7) */
08428       default:
08429          p->inalarm = 0;
08430          break;
08431       }
08432       handle_clear_alarms(p);
08433       break;
08434    case DAHDI_EVENT_WINKFLASH:
08435       if (p->inalarm) break;
08436       if (p->radio) break;
08437       if (p->oprmode < 0) break;
08438       if (p->oprmode > 1)
08439       {
08440          struct dahdi_params par;
08441 
08442          memset(&par, 0, sizeof(par));
08443          if (ioctl(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par) != -1)
08444          {
08445             if (!par.rxisoffhook)
08446             {
08447                /* Make sure it stops ringing */
08448                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08449                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RING);
08450                save_conference(p);
08451                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08452             }
08453          }
08454          break;
08455       }
08456       /* Remember last time we got a flash-hook */
08457       p->flashtime = ast_tvnow();
08458       switch (mysig) {
08459       case SIG_FXOLS:
08460       case SIG_FXOGS:
08461       case SIG_FXOKS:
08462          ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
08463             idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
08464 
08465          /* Cancel any running CallerID spill */
08466          ast_free(p->cidspill);
08467          p->cidspill = NULL;
08468          restore_conference(p);
08469          p->callwaitcas = 0;
08470 
08471          if (idx != SUB_REAL) {
08472             ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", idx, p->channel);
08473             goto winkflashdone;
08474          }
08475 
08476          if (p->subs[SUB_CALLWAIT].owner) {
08477             /* Swap to call-wait */
08478             swap_subs(p, SUB_REAL, SUB_CALLWAIT);
08479             tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
08480             p->owner = p->subs[SUB_REAL].owner;
08481             ast_debug(1, "Making %s the new owner\n", p->owner->name);
08482             if (p->owner->_state == AST_STATE_RINGING) {
08483                ast_setstate(p->owner, AST_STATE_UP);
08484                p->subs[SUB_REAL].needanswer = 1;
08485             }
08486             p->callwaitingrepeat = 0;
08487             p->cidcwexpire = 0;
08488             p->cid_suppress_expire = 0;
08489             /* Start music on hold if appropriate */
08490             if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
08491                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
08492                   S_OR(p->mohsuggest, NULL),
08493                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08494             }
08495             p->subs[SUB_CALLWAIT].needhold = 1;
08496             if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
08497                ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
08498                   S_OR(p->mohsuggest, NULL),
08499                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08500             }
08501             p->subs[SUB_REAL].needunhold = 1;
08502          } else if (!p->subs[SUB_THREEWAY].owner) {
08503             if (!p->threewaycalling) {
08504                /* Just send a flash if no 3-way calling */
08505                p->subs[SUB_REAL].needflash = 1;
08506                goto winkflashdone;
08507             } else if (!check_for_conference(p)) {
08508                char cid_num[256];
08509                char cid_name[256];
08510 
08511                cid_num[0] = 0;
08512                cid_name[0] = 0;
08513                if (p->dahditrcallerid && p->owner) {
08514                   if (p->owner->caller.id.number.valid
08515                      && p->owner->caller.id.number.str) {
08516                      ast_copy_string(cid_num, p->owner->caller.id.number.str,
08517                         sizeof(cid_num));
08518                   }
08519                   if (p->owner->caller.id.name.valid
08520                      && p->owner->caller.id.name.str) {
08521                      ast_copy_string(cid_name, p->owner->caller.id.name.str,
08522                         sizeof(cid_name));
08523                   }
08524                }
08525                /* XXX This section needs much more error checking!!! XXX */
08526                /* Start a 3-way call if feasible */
08527                if (!((ast->pbx) ||
08528                   (ast->_state == AST_STATE_UP) ||
08529                   (ast->_state == AST_STATE_RING))) {
08530                   ast_debug(1, "Flash when call not up or ringing\n");
08531                   goto winkflashdone;
08532                }
08533                if (alloc_sub(p, SUB_THREEWAY)) {
08534                   ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
08535                   goto winkflashdone;
08536                }
08537 
08538                /*
08539                 * Make new channel
08540                 *
08541                 * We cannot hold the p or ast locks while creating a new
08542                 * channel.
08543                 */
08544                ast_mutex_unlock(&p->lock);
08545                ast_channel_unlock(ast);
08546                chan = dahdi_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, NULL);
08547                ast_channel_lock(ast);
08548                ast_mutex_lock(&p->lock);
08549                if (p->dahditrcallerid) {
08550                   if (!p->origcid_num)
08551                      p->origcid_num = ast_strdup(p->cid_num);
08552                   if (!p->origcid_name)
08553                      p->origcid_name = ast_strdup(p->cid_name);
08554                   ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
08555                   ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
08556                }
08557                /* Swap things around between the three-way and real call */
08558                swap_subs(p, SUB_THREEWAY, SUB_REAL);
08559                /* Disable echo canceller for better dialing */
08560                dahdi_disable_ec(p);
08561                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALRECALL);
08562                if (res)
08563                   ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
08564                p->owner = chan;
08565                if (!chan) {
08566                   ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
08567                } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
08568                   ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
08569                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
08570                   dahdi_enable_ec(p);
08571                   ast_hangup(chan);
08572                } else {
08573                   ast_verb(3, "Started three way call on channel %d\n", p->channel);
08574 
08575                   /* Start music on hold if appropriate */
08576                   if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
08577                      ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
08578                         S_OR(p->mohsuggest, NULL),
08579                         !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08580                   }
08581                   p->subs[SUB_THREEWAY].needhold = 1;
08582                }
08583             }
08584          } else {
08585             /* Already have a 3 way call */
08586             if (p->subs[SUB_THREEWAY].inthreeway) {
08587                /* Call is already up, drop the last person */
08588                ast_debug(1, "Got flash with three way call up, dropping last call on %d\n", p->channel);
08589                /* If the primary call isn't answered yet, use it */
08590                if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
08591                   /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
08592                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08593                   p->owner = p->subs[SUB_REAL].owner;
08594                }
08595                /* Drop the last call and stop the conference */
08596                ast_verb(3, "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
08597                p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08598                p->subs[SUB_REAL].inthreeway = 0;
08599                p->subs[SUB_THREEWAY].inthreeway = 0;
08600             } else {
08601                /* Lets see what we're up to */
08602                if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
08603                   (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
08604                   int otherindex = SUB_THREEWAY;
08605 
08606                   ast_verb(3, "Building conference call with %s and %s\n",
08607                      p->subs[SUB_THREEWAY].owner->name,
08608                      p->subs[SUB_REAL].owner->name);
08609                   /* Put them in the threeway, and flip */
08610                   p->subs[SUB_THREEWAY].inthreeway = 1;
08611                   p->subs[SUB_REAL].inthreeway = 1;
08612                   if (ast->_state == AST_STATE_UP) {
08613                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
08614                      otherindex = SUB_REAL;
08615                   }
08616                   if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
08617                      ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
08618                   p->subs[otherindex].needunhold = 1;
08619                   p->owner = p->subs[SUB_REAL].owner;
08620                } else {
08621                   ast_verb(3, "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
08622                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08623                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08624                   p->owner = p->subs[SUB_REAL].owner;
08625                   if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
08626                      ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
08627                   p->subs[SUB_REAL].needunhold = 1;
08628                   dahdi_enable_ec(p);
08629                }
08630             }
08631          }
08632 winkflashdone:
08633          update_conf(p);
08634          break;
08635       case SIG_EM:
08636       case SIG_EM_E1:
08637       case SIG_FEATD:
08638       case SIG_SF:
08639       case SIG_SFWINK:
08640       case SIG_SF_FEATD:
08641       case SIG_FXSLS:
08642       case SIG_FXSGS:
08643          if (p->dialing)
08644             ast_debug(1, "Ignoring wink on channel %d\n", p->channel);
08645          else
08646             ast_debug(1, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
08647          break;
08648       case SIG_FEATDMF_TA:
08649          switch (p->whichwink) {
08650          case 0:
08651             ast_debug(1, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->caller.ani2,
08652                S_COR(p->owner->caller.ani.number.valid,
08653                   p->owner->caller.ani.number.str, ""));
08654             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#",
08655                p->owner->caller.ani2,
08656                S_COR(p->owner->caller.ani.number.valid,
08657                   p->owner->caller.ani.number.str, ""));
08658             break;
08659          case 1:
08660             ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
08661             break;
08662          case 2:
08663             ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
08664             return NULL;
08665          }
08666          p->whichwink++;
08667          /* Fall through */
08668       case SIG_FEATDMF:
08669       case SIG_E911:
08670       case SIG_FGC_CAMAMF:
08671       case SIG_FGC_CAMA:
08672       case SIG_FEATB:
08673       case SIG_SF_FEATDMF:
08674       case SIG_SF_FEATB:
08675       case SIG_EMWINK:
08676          /* FGD MF and EMWINK *Must* wait for wink */
08677          if (!ast_strlen_zero(p->dop.dialstr)) {
08678             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08679             if (res < 0) {
08680                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08681                p->dop.dialstr[0] = '\0';
08682                return NULL;
08683             } else
08684                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08685          }
08686          p->dop.dialstr[0] = '\0';
08687          break;
08688       default:
08689          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08690       }
08691       break;
08692    case DAHDI_EVENT_HOOKCOMPLETE:
08693       if (p->inalarm) break;
08694       if ((p->radio || (p->oprmode < 0))) break;
08695       if (p->waitingfordt.tv_sec) break;
08696       switch (mysig) {
08697       case SIG_FXSLS:  /* only interesting for FXS */
08698       case SIG_FXSGS:
08699       case SIG_FXSKS:
08700       case SIG_EM:
08701       case SIG_EM_E1:
08702       case SIG_EMWINK:
08703       case SIG_FEATD:
08704       case SIG_SF:
08705       case SIG_SFWINK:
08706       case SIG_SF_FEATD:
08707          if (!ast_strlen_zero(p->dop.dialstr)) {
08708             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08709             if (res < 0) {
08710                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08711                p->dop.dialstr[0] = '\0';
08712                return NULL;
08713             } else
08714                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08715          }
08716          p->dop.dialstr[0] = '\0';
08717          p->dop.op = DAHDI_DIAL_OP_REPLACE;
08718          break;
08719       case SIG_FEATDMF:
08720       case SIG_FEATDMF_TA:
08721       case SIG_E911:
08722       case SIG_FGC_CAMA:
08723       case SIG_FGC_CAMAMF:
08724       case SIG_FEATB:
08725       case SIG_SF_FEATDMF:
08726       case SIG_SF_FEATB:
08727          ast_debug(1, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
08728          break;
08729       default:
08730          break;
08731       }
08732       break;
08733    case DAHDI_EVENT_POLARITY:
08734       /*
08735        * If we get a Polarity Switch event, check to see
08736        * if we should change the polarity state and
08737        * mark the channel as UP or if this is an indication
08738        * of remote end disconnect.
08739        */
08740       if (p->polarity == POLARITY_IDLE) {
08741          p->polarity = POLARITY_REV;
08742          if (p->answeronpolarityswitch &&
08743             ((ast->_state == AST_STATE_DIALING) ||
08744             (ast->_state == AST_STATE_RINGING))) {
08745             ast_debug(1, "Answering on polarity switch!\n");
08746             ast_setstate(p->owner, AST_STATE_UP);
08747             if (p->hanguponpolarityswitch) {
08748                p->polaritydelaytv = ast_tvnow();
08749             }
08750          } else
08751             ast_debug(1, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
08752       }
08753       /* Removed else statement from here as it was preventing hangups from ever happening*/
08754       /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
08755       if (p->hanguponpolarityswitch &&
08756          (p->polarityonanswerdelay > 0) &&
08757          (p->polarity == POLARITY_REV) &&
08758          ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
08759          /* Added log_debug information below to provide a better indication of what is going on */
08760          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) );
08761 
08762          if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
08763             ast_debug(1, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
08764             ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
08765             p->polarity = POLARITY_IDLE;
08766          } else
08767             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);
08768 
08769       } else {
08770          p->polarity = POLARITY_IDLE;
08771          ast_debug(1, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
08772       }
08773       /* Added more log_debug information below to provide a better indication of what is going on */
08774       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) );
08775       break;
08776    default:
08777       ast_debug(1, "Dunno what to do with event %d on channel %d\n", res, p->channel);
08778    }
08779    return &p->subs[idx].f;
08780 }
08781 
08782 static struct ast_frame *__dahdi_exception(struct ast_channel *ast)
08783 {
08784    int res;
08785    int idx;
08786    struct ast_frame *f;
08787    int usedindex = -1;
08788    struct dahdi_pvt *p = ast->tech_pvt;
08789 
08790    if ((idx = dahdi_get_index(ast, p, 0)) < 0) {
08791       idx = SUB_REAL;
08792    }
08793 
08794    p->subs[idx].f.frametype = AST_FRAME_NULL;
08795    p->subs[idx].f.datalen = 0;
08796    p->subs[idx].f.samples = 0;
08797    p->subs[idx].f.mallocd = 0;
08798    p->subs[idx].f.offset = 0;
08799    p->subs[idx].f.subclass.integer = 0;
08800    p->subs[idx].f.delivery = ast_tv(0,0);
08801    p->subs[idx].f.src = "dahdi_exception";
08802    p->subs[idx].f.data.ptr = NULL;
08803 
08804 
08805    if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
08806       /* If nobody owns us, absorb the event appropriately, otherwise
08807          we loop indefinitely.  This occurs when, during call waiting, the
08808          other end hangs up our channel so that it no longer exists, but we
08809          have neither FLASH'd nor ONHOOK'd to signify our desire to
08810          change to the other channel. */
08811       if (p->fake_event) {
08812          res = p->fake_event;
08813          p->fake_event = 0;
08814       } else
08815          res = dahdi_get_event(p->subs[SUB_REAL].dfd);
08816       /* Switch to real if there is one and this isn't something really silly... */
08817       if ((res != DAHDI_EVENT_RINGEROFF) && (res != DAHDI_EVENT_RINGERON) &&
08818          (res != DAHDI_EVENT_HOOKCOMPLETE)) {
08819          ast_debug(1, "Restoring owner of channel %d on event %d\n", p->channel, res);
08820          p->owner = p->subs[SUB_REAL].owner;
08821          if (p->owner && ast_bridged_channel(p->owner))
08822             ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08823          p->subs[SUB_REAL].needunhold = 1;
08824       }
08825       switch (res) {
08826       case DAHDI_EVENT_ONHOOK:
08827          dahdi_disable_ec(p);
08828          if (p->owner) {
08829             ast_verb(3, "Channel %s still has call, ringing phone\n", p->owner->name);
08830             dahdi_ring_phone(p);
08831             p->callwaitingrepeat = 0;
08832             p->cidcwexpire = 0;
08833             p->cid_suppress_expire = 0;
08834          } else
08835             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08836          update_conf(p);
08837          break;
08838       case DAHDI_EVENT_RINGOFFHOOK:
08839          dahdi_enable_ec(p);
08840          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08841          if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
08842             p->subs[SUB_REAL].needanswer = 1;
08843             p->dialing = 0;
08844          }
08845          break;
08846       case DAHDI_EVENT_HOOKCOMPLETE:
08847       case DAHDI_EVENT_RINGERON:
08848       case DAHDI_EVENT_RINGEROFF:
08849          /* Do nothing */
08850          break;
08851       case DAHDI_EVENT_WINKFLASH:
08852          p->flashtime = ast_tvnow();
08853          if (p->owner) {
08854             ast_verb(3, "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
08855             if (p->owner->_state != AST_STATE_UP) {
08856                /* Answer if necessary */
08857                usedindex = dahdi_get_index(p->owner, p, 0);
08858                if (usedindex > -1) {
08859                   p->subs[usedindex].needanswer = 1;
08860                }
08861                ast_setstate(p->owner, AST_STATE_UP);
08862             }
08863             p->callwaitingrepeat = 0;
08864             p->cidcwexpire = 0;
08865             p->cid_suppress_expire = 0;
08866             if (ast_bridged_channel(p->owner))
08867                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08868             p->subs[SUB_REAL].needunhold = 1;
08869          } else
08870             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08871          update_conf(p);
08872          break;
08873       default:
08874          ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
08875       }
08876       f = &p->subs[idx].f;
08877       return f;
08878    }
08879    if (!(p->radio || (p->oprmode < 0)))
08880       ast_debug(1, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
08881    /* If it's not us, return NULL immediately */
08882    if (ast != p->owner) {
08883       if (p->owner) {
08884          ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
08885       }
08886       f = &p->subs[idx].f;
08887       return f;
08888    }
08889 
08890    f = dahdi_handle_event(ast);
08891    if (!f) {
08892       const char *name = ast_strdupa(ast->name);
08893 
08894       /* Tell the CDR this DAHDI device hung up */
08895       ast_mutex_unlock(&p->lock);
08896       ast_channel_unlock(ast);
08897       ast_set_hangupsource(ast, name, 0);
08898       ast_channel_lock(ast);
08899       ast_mutex_lock(&p->lock);
08900    }
08901    return f;
08902 }
08903 
08904 static struct ast_frame *dahdi_exception(struct ast_channel *ast)
08905 {
08906    struct dahdi_pvt *p = ast->tech_pvt;
08907    struct ast_frame *f;
08908    ast_mutex_lock(&p->lock);
08909    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08910       struct analog_pvt *analog_p = p->sig_pvt;
08911       f = analog_exception(analog_p, ast);
08912    } else {
08913       f = __dahdi_exception(ast);
08914    }
08915    ast_mutex_unlock(&p->lock);
08916    return f;
08917 }
08918 
08919 static struct ast_frame *dahdi_read(struct ast_channel *ast)
08920 {
08921    struct dahdi_pvt *p;
08922    int res;
08923    int idx;
08924    void *readbuf;
08925    struct ast_frame *f;
08926 
08927    /*
08928     * For analog channels, we must do deadlock avoidance because
08929     * analog ports can have more than one Asterisk channel using
08930     * the same private structure.
08931     */
08932    p = ast->tech_pvt;
08933    while (ast_mutex_trylock(&p->lock)) {
08934       CHANNEL_DEADLOCK_AVOIDANCE(ast);
08935 
08936       /*
08937        * Check to see if the channel is still associated with the same
08938        * private structure.  While the Asterisk channel was unlocked
08939        * the following events may have occured:
08940        *
08941        * 1) A masquerade may have associated the channel with another
08942        * technology or private structure.
08943        *
08944        * 2) For PRI calls, call signaling could change the channel
08945        * association to another B channel (private structure).
08946        */
08947       if (ast->tech_pvt != p) {
08948          /* The channel is no longer associated.  Quit gracefully. */
08949          return &ast_null_frame;
08950       }
08951    }
08952 
08953    idx = dahdi_get_index(ast, p, 0);
08954 
08955    /* Hang up if we don't really exist */
08956    if (idx < 0)   {
08957       ast_log(LOG_WARNING, "We don't exist?\n");
08958       ast_mutex_unlock(&p->lock);
08959       return NULL;
08960    }
08961 
08962    if ((p->radio || (p->oprmode < 0)) && p->inalarm) {
08963       ast_mutex_unlock(&p->lock);
08964       return NULL;
08965    }
08966 
08967    p->subs[idx].f.frametype = AST_FRAME_NULL;
08968    p->subs[idx].f.datalen = 0;
08969    p->subs[idx].f.samples = 0;
08970    p->subs[idx].f.mallocd = 0;
08971    p->subs[idx].f.offset = 0;
08972    p->subs[idx].f.subclass.integer = 0;
08973    p->subs[idx].f.delivery = ast_tv(0,0);
08974    p->subs[idx].f.src = "dahdi_read";
08975    p->subs[idx].f.data.ptr = NULL;
08976 
08977    /* make sure it sends initial key state as first frame */
08978    if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
08979    {
08980       struct dahdi_params ps;
08981 
08982       memset(&ps, 0, sizeof(ps));
08983       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
08984          ast_mutex_unlock(&p->lock);
08985          return NULL;
08986       }
08987       p->firstradio = 1;
08988       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08989       if (ps.rxisoffhook)
08990       {
08991          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08992       }
08993       else
08994       {
08995          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08996       }
08997       ast_mutex_unlock(&p->lock);
08998       return &p->subs[idx].f;
08999    }
09000    if (p->ringt > 0) {
09001       if (!(--p->ringt)) {
09002          ast_mutex_unlock(&p->lock);
09003          return NULL;
09004       }
09005    }
09006 
09007 #ifdef HAVE_OPENR2
09008    if (p->mfcr2) {
09009       openr2_chan_process_event(p->r2chan);
09010       if (OR2_DIR_FORWARD == openr2_chan_get_direction(p->r2chan)) {
09011          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_PROGRESS }, };
09012          /* if the call is already accepted and we already delivered AST_CONTROL_RINGING
09013           * now enqueue a progress frame to bridge the media up */
09014          if (p->mfcr2_call_accepted &&
09015              !p->mfcr2_progress && 
09016              ast->_state == AST_STATE_RINGING) {
09017             ast_log(LOG_DEBUG, "Enqueuing progress frame after R2 accept in chan %d\n", p->channel);
09018             ast_queue_frame(p->owner, &f);
09019             p->mfcr2_progress = 1;
09020          }
09021       }
09022    }
09023 #endif
09024 
09025    if (p->subs[idx].needringing) {
09026       /* Send ringing frame if requested */
09027       p->subs[idx].needringing = 0;
09028       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09029       p->subs[idx].f.subclass.integer = AST_CONTROL_RINGING;
09030       ast_setstate(ast, AST_STATE_RINGING);
09031       ast_mutex_unlock(&p->lock);
09032       return &p->subs[idx].f;
09033    }
09034 
09035    if (p->subs[idx].needbusy) {
09036       /* Send busy frame if requested */
09037       p->subs[idx].needbusy = 0;
09038       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09039       p->subs[idx].f.subclass.integer = AST_CONTROL_BUSY;
09040       ast_mutex_unlock(&p->lock);
09041       return &p->subs[idx].f;
09042    }
09043 
09044    if (p->subs[idx].needcongestion) {
09045       /* Send congestion frame if requested */
09046       p->subs[idx].needcongestion = 0;
09047       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09048       p->subs[idx].f.subclass.integer = AST_CONTROL_CONGESTION;
09049       ast_mutex_unlock(&p->lock);
09050       return &p->subs[idx].f;
09051    }
09052 
09053    if (p->subs[idx].needanswer) {
09054       /* Send answer frame if requested */
09055       p->subs[idx].needanswer = 0;
09056       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09057       p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
09058       ast_mutex_unlock(&p->lock);
09059       return &p->subs[idx].f;
09060    }
09061 #ifdef HAVE_OPENR2
09062    if (p->mfcr2 && openr2_chan_get_read_enabled(p->r2chan)) {
09063       /* openr2 took care of reading and handling any event
09064         (needanswer, needbusy etc), if we continue we will read()
09065         twice, lets just return a null frame. This should only
09066         happen when openr2 is dialing out */
09067       ast_mutex_unlock(&p->lock);
09068       return &ast_null_frame;
09069    }
09070 #endif
09071 
09072    if (p->subs[idx].needflash) {
09073       /* Send answer frame if requested */
09074       p->subs[idx].needflash = 0;
09075       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09076       p->subs[idx].f.subclass.integer = AST_CONTROL_FLASH;
09077       ast_mutex_unlock(&p->lock);
09078       return &p->subs[idx].f;
09079    }
09080 
09081    if (p->subs[idx].needhold) {
09082       /* Send answer frame if requested */
09083       p->subs[idx].needhold = 0;
09084       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09085       p->subs[idx].f.subclass.integer = AST_CONTROL_HOLD;
09086       ast_mutex_unlock(&p->lock);
09087       ast_debug(1, "Sending hold on '%s'\n", ast->name);
09088       return &p->subs[idx].f;
09089    }
09090 
09091    if (p->subs[idx].needunhold) {
09092       /* Send answer frame if requested */
09093       p->subs[idx].needunhold = 0;
09094       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
09095       p->subs[idx].f.subclass.integer = AST_CONTROL_UNHOLD;
09096       ast_mutex_unlock(&p->lock);
09097       ast_debug(1, "Sending unhold on '%s'\n", ast->name);
09098       return &p->subs[idx].f;
09099    }
09100 
09101    /*
09102     * If we have a fake_event, fake an exception to handle it only
09103     * if this channel owns the private.
09104     */
09105    if (p->fake_event && p->owner == ast) {
09106       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09107          struct analog_pvt *analog_p = p->sig_pvt;
09108 
09109          f = analog_exception(analog_p, ast);
09110       } else {
09111          f = __dahdi_exception(ast);
09112       }
09113       ast_mutex_unlock(&p->lock);
09114       return f;
09115    }
09116 
09117    if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
09118       if (!p->subs[idx].linear) {
09119          p->subs[idx].linear = 1;
09120          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09121          if (res)
09122             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, idx);
09123       }
09124    } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
09125       (ast->rawreadformat == AST_FORMAT_ALAW)) {
09126       if (p->subs[idx].linear) {
09127          p->subs[idx].linear = 0;
09128          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09129          if (res)
09130             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, idx);
09131       }
09132    } else {
09133       ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
09134       ast_mutex_unlock(&p->lock);
09135       return NULL;
09136    }
09137    readbuf = ((unsigned char *)p->subs[idx].buffer) + AST_FRIENDLY_OFFSET;
09138    CHECK_BLOCKING(ast);
09139    res = read(p->subs[idx].dfd, readbuf, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
09140    ast_clear_flag(ast, AST_FLAG_BLOCKING);
09141    /* Check for hangup */
09142    if (res < 0) {
09143       f = NULL;
09144       if (res == -1) {
09145          if (errno == EAGAIN) {
09146             /* Return "NULL" frame if there is nobody there */
09147             ast_mutex_unlock(&p->lock);
09148             return &p->subs[idx].f;
09149          } else if (errno == ELAST) {
09150             if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09151                struct analog_pvt *analog_p = p->sig_pvt;
09152                f = analog_exception(analog_p, ast);
09153             } else {
09154                f = __dahdi_exception(ast);
09155             }
09156          } else
09157             ast_log(LOG_WARNING, "dahdi_rec: %s\n", strerror(errno));
09158       }
09159       ast_mutex_unlock(&p->lock);
09160       return f;
09161    }
09162    if (res != (p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE)) {
09163       ast_debug(1, "Short read (%d/%d), must be an event...\n", res, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
09164       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09165          struct analog_pvt *analog_p = p->sig_pvt;
09166          f = analog_exception(analog_p, ast);
09167       } else {
09168          f = __dahdi_exception(ast);
09169       }
09170       ast_mutex_unlock(&p->lock);
09171       return f;
09172    }
09173    if (p->tdd) { /* if in TDD mode, see if we receive that */
09174       int c;
09175 
09176       c = tdd_feed(p->tdd,readbuf,READ_SIZE);
09177       if (c < 0) {
09178          ast_debug(1,"tdd_feed failed\n");
09179          ast_mutex_unlock(&p->lock);
09180          return NULL;
09181       }
09182       if (c) { /* if a char to return */
09183          p->subs[idx].f.subclass.integer = 0;
09184          p->subs[idx].f.frametype = AST_FRAME_TEXT;
09185          p->subs[idx].f.mallocd = 0;
09186          p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
09187          p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET;
09188          p->subs[idx].f.datalen = 1;
09189          *((char *) p->subs[idx].f.data.ptr) = c;
09190          ast_mutex_unlock(&p->lock);
09191          return &p->subs[idx].f;
09192       }
09193    }
09194    if (idx == SUB_REAL) {
09195       /* Ensure the CW timers decrement only on a single subchannel */
09196       if (p->cidcwexpire) {
09197          if (!--p->cidcwexpire) {
09198             /* Expired CID/CW */
09199             ast_verb(3, "CPE does not support Call Waiting Caller*ID.\n");
09200             restore_conference(p);
09201          }
09202       }
09203       if (p->cid_suppress_expire) {
09204          --p->cid_suppress_expire;
09205       }
09206       if (p->callwaitingrepeat) {
09207          if (!--p->callwaitingrepeat) {
09208             /* Expired, Repeat callwaiting tone */
09209             ++p->callwaitrings;
09210             dahdi_callwait(ast);
09211          }
09212       }
09213    }
09214    if (p->subs[idx].linear) {
09215       p->subs[idx].f.datalen = READ_SIZE * 2;
09216    } else
09217       p->subs[idx].f.datalen = READ_SIZE;
09218 
09219    /* Handle CallerID Transmission */
09220    if ((p->owner == ast) && p->cidspill) {
09221       send_callerid(p);
09222    }
09223 
09224    p->subs[idx].f.frametype = AST_FRAME_VOICE;
09225    p->subs[idx].f.subclass.codec = ast->rawreadformat;
09226    p->subs[idx].f.samples = READ_SIZE;
09227    p->subs[idx].f.mallocd = 0;
09228    p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
09229    p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[idx].buffer[0]);
09230 #if 0
09231    ast_debug(1, "Read %d of voice on %s\n", p->subs[idx].f.datalen, ast->name);
09232 #endif
09233    if (p->dialing ||  p->radio || /* Transmitting something */
09234       (idx && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
09235       ((idx == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
09236       ) {
09237       /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
09238          don't send anything */
09239       p->subs[idx].f.frametype = AST_FRAME_NULL;
09240       p->subs[idx].f.subclass.integer = 0;
09241       p->subs[idx].f.samples = 0;
09242       p->subs[idx].f.mallocd = 0;
09243       p->subs[idx].f.offset = 0;
09244       p->subs[idx].f.data.ptr = NULL;
09245       p->subs[idx].f.datalen= 0;
09246    }
09247    if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress || p->waitingfordt.tv_sec) && !idx) {
09248       /* Perform busy detection etc on the dahdi line */
09249       int mute;
09250 
09251       f = ast_dsp_process(ast, p->dsp, &p->subs[idx].f);
09252 
09253       /* Check if DSP code thinks we should be muting this frame and mute the conference if so */
09254       mute = ast_dsp_was_muted(p->dsp);
09255       if (p->muting != mute) {
09256          p->muting = mute;
09257          dahdi_confmute(p, mute);
09258       }
09259 
09260       if (f) {
09261          if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_BUSY)) {
09262             if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
09263                /* Treat this as a "hangup" instead of a "busy" on the assumption that
09264                   a busy */
09265                ast_frfree(f);
09266                f = NULL;
09267             }
09268          } else if (f->frametype == AST_FRAME_DTMF_BEGIN
09269             || f->frametype == AST_FRAME_DTMF_END) {
09270 #ifdef HAVE_PRI
09271             if (dahdi_sig_pri_lib_handles(p->sig)
09272                && ((struct sig_pri_chan *) p->sig_pvt)->call_level < SIG_PRI_CALL_LEVEL_PROCEEDING
09273                && p->pri
09274                && ((!p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING))
09275                   || (p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)))) {
09276                /* Don't accept in-band DTMF when in overlap dial mode */
09277                ast_debug(1, "Absorbing inband %s DTMF digit: 0x%02X '%c' on %s\n",
09278                   f->frametype == AST_FRAME_DTMF_BEGIN ? "begin" : "end",
09279                   f->subclass.integer, f->subclass.integer, ast->name);
09280 
09281                f->frametype = AST_FRAME_NULL;
09282                f->subclass.integer = 0;
09283             }
09284 #endif
09285             /* DSP clears us of being pulse */
09286             p->pulsedial = 0;
09287          } else if (p->waitingfordt.tv_sec) {
09288             if (ast_tvdiff_ms(ast_tvnow(), p->waitingfordt) >= p->waitfordialtone ) {
09289                p->waitingfordt.tv_sec = 0;
09290                ast_log(LOG_WARNING, "Never saw dialtone on channel %d\n", p->channel);
09291                ast_frfree(f);
09292                f = NULL;
09293             } else if (f->frametype == AST_FRAME_VOICE) {
09294                f->frametype = AST_FRAME_NULL;
09295                f->subclass.integer = 0;
09296                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) {
09297                   p->waitingfordt.tv_sec = 0;
09298                   p->dsp_features &= ~DSP_FEATURE_WAITDIALTONE;
09299                   ast_dsp_set_features(p->dsp, p->dsp_features);
09300                   ast_log(LOG_DEBUG, "Got 10 samples of dialtone!\n");
09301                   if (!ast_strlen_zero(p->dop.dialstr)) { /* Dial deferred digits */
09302                      res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
09303                      if (res < 0) {
09304                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
09305                         p->dop.dialstr[0] = '\0';
09306                         ast_mutex_unlock(&p->lock);
09307                         ast_frfree(f);
09308                         return NULL;
09309                      } else {
09310                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
09311                         p->dialing = 1;
09312                         p->dop.dialstr[0] = '\0';
09313                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
09314                         ast_setstate(ast, AST_STATE_DIALING);
09315                      }
09316                   }
09317                }
09318             }
09319          }
09320       }
09321    } else
09322       f = &p->subs[idx].f;
09323 
09324    if (f) {
09325       switch (f->frametype) {
09326       case AST_FRAME_DTMF_BEGIN:
09327       case AST_FRAME_DTMF_END:
09328          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
09329             analog_handle_dtmf(p->sig_pvt, ast, idx, &f);
09330          } else {
09331             dahdi_handle_dtmf(ast, idx, &f);
09332          }
09333          break;
09334       case AST_FRAME_VOICE:
09335          if (p->cidspill || p->cid_suppress_expire) {
09336             /* We are/were sending a caller id spill.  Suppress any echo. */
09337             p->subs[idx].f.frametype = AST_FRAME_NULL;
09338             p->subs[idx].f.subclass.integer = 0;
09339             p->subs[idx].f.samples = 0;
09340             p->subs[idx].f.mallocd = 0;
09341             p->subs[idx].f.offset = 0;
09342             p->subs[idx].f.data.ptr = NULL;
09343             p->subs[idx].f.datalen= 0;
09344          }
09345          break;
09346       default:
09347          break;
09348       }
09349    }
09350 
09351    ast_mutex_unlock(&p->lock);
09352    return f;
09353 }
09354 
09355 static int my_dahdi_write(struct dahdi_pvt *p, unsigned char *buf, int len, int idx, int linear)
09356 {
09357    int sent=0;
09358    int size;
09359    int res;
09360    int fd;
09361    fd = p->subs[idx].dfd;
09362    while (len) {
09363       size = len;
09364       if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
09365          size = (linear ? READ_SIZE * 2 : READ_SIZE);
09366       res = write(fd, buf, size);
09367       if (res != size) {
09368          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
09369          return sent;
09370       }
09371       len -= size;
09372       buf += size;
09373    }
09374    return sent;
09375 }
09376 
09377 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame)
09378 {
09379    struct dahdi_pvt *p = ast->tech_pvt;
09380    int res;
09381    int idx;
09382    idx = dahdi_get_index(ast, p, 0);
09383    if (idx < 0) {
09384       ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
09385       return -1;
09386    }
09387 
09388    /* Write a frame of (presumably voice) data */
09389    if (frame->frametype != AST_FRAME_VOICE) {
09390       if (frame->frametype != AST_FRAME_IMAGE)
09391          ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
09392       return 0;
09393    }
09394    if ((frame->subclass.codec != AST_FORMAT_SLINEAR) &&
09395       (frame->subclass.codec != AST_FORMAT_ULAW) &&
09396       (frame->subclass.codec != AST_FORMAT_ALAW)) {
09397       ast_log(LOG_WARNING, "Cannot handle frames in %s format\n", ast_getformatname(frame->subclass.codec));
09398       return -1;
09399    }
09400    if (p->dialing) {
09401       ast_debug(1, "Dropping frame since I'm still dialing on %s...\n",ast->name);
09402       return 0;
09403    }
09404    if (!p->owner) {
09405       ast_debug(1, "Dropping frame since there is no active owner on %s...\n",ast->name);
09406       return 0;
09407    }
09408    if (p->cidspill) {
09409       ast_debug(1, "Dropping frame since I've still got a callerid spill on %s...\n",
09410          ast->name);
09411       return 0;
09412    }
09413    /* Return if it's not valid data */
09414    if (!frame->data.ptr || !frame->datalen)
09415       return 0;
09416 
09417    if (frame->subclass.codec == AST_FORMAT_SLINEAR) {
09418       if (!p->subs[idx].linear) {
09419          p->subs[idx].linear = 1;
09420          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09421          if (res)
09422             ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
09423       }
09424       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 1);
09425    } else {
09426       /* x-law already */
09427       if (p->subs[idx].linear) {
09428          p->subs[idx].linear = 0;
09429          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09430          if (res)
09431             ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
09432       }
09433       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 0);
09434    }
09435    if (res < 0) {
09436       ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
09437       return -1;
09438    }
09439    return 0;
09440 }
09441 
09442 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
09443 {
09444    struct dahdi_pvt *p = chan->tech_pvt;
09445    int res=-1;
09446    int idx;
09447    int func = DAHDI_FLASH;
09448 
09449    ast_mutex_lock(&p->lock);
09450    ast_debug(1, "Requested indication %d on channel %s\n", condition, chan->name);
09451    switch (p->sig) {
09452 #if defined(HAVE_PRI)
09453    case SIG_PRI_LIB_HANDLE_CASES:
09454       res = sig_pri_indicate(p->sig_pvt, chan, condition, data, datalen);
09455       ast_mutex_unlock(&p->lock);
09456       return res;
09457 #endif   /* defined(HAVE_PRI) */
09458 #if defined(HAVE_SS7)
09459    case SIG_SS7:
09460       res = sig_ss7_indicate(p->sig_pvt, chan, condition, data, datalen);
09461       ast_mutex_unlock(&p->lock);
09462       return res;
09463 #endif   /* defined(HAVE_SS7) */
09464    default:
09465       break;
09466    }
09467 #ifdef HAVE_OPENR2
09468    if (p->mfcr2 && !p->mfcr2_call_accepted) {
09469       ast_mutex_unlock(&p->lock);
09470       /* if this is an R2 call and the call is not yet accepted, we don't want the
09471          tone indications to mess up with the MF tones */
09472       return 0;
09473    }
09474 #endif
09475    idx = dahdi_get_index(chan, p, 0);
09476    if (idx == SUB_REAL) {
09477       switch (condition) {
09478       case AST_CONTROL_BUSY:
09479          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_BUSY);
09480          break;
09481       case AST_CONTROL_RINGING:
09482          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_RINGTONE);
09483 
09484          if (chan->_state != AST_STATE_UP) {
09485             if ((chan->_state != AST_STATE_RING) ||
09486                ((p->sig != SIG_FXSKS) &&
09487              (p->sig != SIG_FXSLS) &&
09488              (p->sig != SIG_FXSGS)))
09489             ast_setstate(chan, AST_STATE_RINGING);
09490          }
09491          break;
09492       case AST_CONTROL_INCOMPLETE:
09493          ast_debug(1, "Received AST_CONTROL_INCOMPLETE on %s\n", chan->name);
09494          /* act as a progress or proceeding, allowing the caller to enter additional numbers */
09495          res = 0;
09496          break;
09497       case AST_CONTROL_PROCEEDING:
09498          ast_debug(1, "Received AST_CONTROL_PROCEEDING on %s\n", chan->name);
09499          /* don't continue in ast_indicate */
09500          res = 0;
09501          break;
09502       case AST_CONTROL_PROGRESS:
09503          ast_debug(1, "Received AST_CONTROL_PROGRESS on %s\n", chan->name);
09504          /* don't continue in ast_indicate */
09505          res = 0;
09506          break;
09507       case AST_CONTROL_CONGESTION:
09508          /* There are many cause codes that generate an AST_CONTROL_CONGESTION. */
09509          switch (chan->hangupcause) {
09510          case AST_CAUSE_USER_BUSY:
09511          case AST_CAUSE_NORMAL_CLEARING:
09512          case 0:/* Cause has not been set. */
09513             /* Supply a more appropriate cause. */
09514             chan->hangupcause = AST_CAUSE_CONGESTION;
09515             break;
09516          default:
09517             break;
09518          }
09519          break;
09520       case AST_CONTROL_HOLD:
09521          ast_moh_start(chan, data, p->mohinterpret);
09522          break;
09523       case AST_CONTROL_UNHOLD:
09524          ast_moh_stop(chan);
09525          break;
09526       case AST_CONTROL_RADIO_KEY:
09527          if (p->radio)
09528             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
09529          res = 0;
09530          break;
09531       case AST_CONTROL_RADIO_UNKEY:
09532          if (p->radio)
09533             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_RINGOFF);
09534          res = 0;
09535          break;
09536       case AST_CONTROL_FLASH:
09537          /* flash hookswitch */
09538          if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
09539             /* Clear out the dial buffer */
09540             p->dop.dialstr[0] = '\0';
09541             if ((ioctl(p->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
09542                ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
09543                   chan->name, strerror(errno));
09544             } else
09545                res = 0;
09546          } else
09547             res = 0;
09548          break;
09549       case AST_CONTROL_SRCUPDATE:
09550          res = 0;
09551          break;
09552       case -1:
09553          res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09554          break;
09555       }
09556    } else {
09557       res = 0;
09558    }
09559    ast_mutex_unlock(&p->lock);
09560    return res;
09561 }
09562 
09563 #if defined(HAVE_PRI)
09564 static struct ast_str *create_channel_name(struct dahdi_pvt *i, int is_outgoing, char *address)
09565 #else
09566 static struct ast_str *create_channel_name(struct dahdi_pvt *i)
09567 #endif   /* defined(HAVE_PRI) */
09568 {
09569    struct ast_str *chan_name;
09570    int x, y;
09571 
09572    /* Create the new channel name tail. */
09573    if (!(chan_name = ast_str_create(32))) {
09574       return NULL;
09575    }
09576    if (i->channel == CHAN_PSEUDO) {
09577       ast_str_set(&chan_name, 0, "pseudo-%ld", ast_random());
09578 #if defined(HAVE_PRI)
09579    } else if (i->pri) {
09580       ast_mutex_lock(&i->pri->lock);
09581       y = ++i->pri->new_chan_seq;
09582       if (is_outgoing) {
09583          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, address, y);
09584          address[0] = '\0';
09585       } else if (ast_strlen_zero(i->cid_subaddr)) {
09586          /* Put in caller-id number only since there is no subaddress. */
09587          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, i->cid_num, y);
09588       } else {
09589          /* Put in caller-id number and subaddress. */
09590          ast_str_set(&chan_name, 0, "i%d/%s:%s-%x", i->pri->span, i->cid_num,
09591             i->cid_subaddr, y);
09592       }
09593       ast_mutex_unlock(&i->pri->lock);
09594 #endif   /* defined(HAVE_PRI) */
09595    } else {
09596       y = 1;
09597       do {
09598          ast_str_set(&chan_name, 0, "%d-%d", i->channel, y);
09599          for (x = 0; x < 3; ++x) {
09600             if (i->subs[x].owner && !strcasecmp(ast_str_buffer(chan_name),
09601                i->subs[x].owner->name + 6)) {
09602                break;
09603             }
09604          }
09605          ++y;
09606       } while (x < 3);
09607    }
09608    return chan_name;
09609 }
09610 
09611 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid)
09612 {
09613    struct ast_channel *tmp;
09614    format_t deflaw;
09615    int x;
09616    int features;
09617    struct ast_str *chan_name;
09618    struct ast_variable *v;
09619    char *dashptr;
09620    char device_name[AST_CHANNEL_NAME];
09621 
09622    if (i->subs[idx].owner) {
09623       ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[idx]);
09624       return NULL;
09625    }
09626 
09627 #if defined(HAVE_PRI)
09628    /*
09629     * The dnid has been stuffed with the called-number[:subaddress]
09630     * by dahdi_request() for outgoing calls.
09631     */
09632    chan_name = create_channel_name(i, i->outgoing, i->dnid);
09633 #else
09634    chan_name = create_channel_name(i);
09635 #endif   /* defined(HAVE_PRI) */
09636    if (!chan_name) {
09637       return NULL;
09638    }
09639 
09640    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));
09641    ast_free(chan_name);
09642    if (!tmp)
09643       return NULL;
09644    tmp->tech = &dahdi_tech;
09645 #if defined(HAVE_PRI)
09646    if (i->pri) {
09647       ast_cc_copy_config_params(i->cc_params, i->pri->cc_params);
09648    }
09649 #endif   /* defined(HAVE_PRI) */
09650    ast_channel_cc_params_init(tmp, i->cc_params);
09651    if (law) {
09652       i->law = law;
09653       if (law == DAHDI_LAW_ALAW) {
09654          deflaw = AST_FORMAT_ALAW;
09655       } else {
09656          deflaw = AST_FORMAT_ULAW;
09657       }
09658    } else {
09659       switch (i->sig) {
09660       case SIG_PRI_LIB_HANDLE_CASES:
09661          /* Make sure companding law is known. */
09662          i->law = (i->law_default == DAHDI_LAW_ALAW)
09663             ? DAHDI_LAW_ALAW : DAHDI_LAW_MULAW;
09664          break;
09665       default:
09666          i->law = i->law_default;
09667          break;
09668       }
09669       if (i->law_default == DAHDI_LAW_ALAW) {
09670          deflaw = AST_FORMAT_ALAW;
09671       } else {
09672          deflaw = AST_FORMAT_ULAW;
09673       }
09674    }
09675    ast_channel_set_fd(tmp, 0, i->subs[idx].dfd);
09676    tmp->nativeformats = deflaw;
09677    /* Start out assuming ulaw since it's smaller :) */
09678    tmp->rawreadformat = deflaw;
09679    tmp->readformat = deflaw;
09680    tmp->rawwriteformat = deflaw;
09681    tmp->writeformat = deflaw;
09682    i->subs[idx].linear = 0;
09683    dahdi_setlinear(i->subs[idx].dfd, i->subs[idx].linear);
09684    features = 0;
09685    if (idx == SUB_REAL) {
09686       if (i->busydetect && CANBUSYDETECT(i))
09687          features |= DSP_FEATURE_BUSY_DETECT;
09688       if ((i->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(i))
09689          features |= DSP_FEATURE_CALL_PROGRESS;
09690       if ((i->waitfordialtone) && CANPROGRESSDETECT(i))
09691          features |= DSP_FEATURE_WAITDIALTONE;
09692       if ((!i->outgoing && (i->callprogress & CALLPROGRESS_FAX_INCOMING)) ||
09693          (i->outgoing && (i->callprogress & CALLPROGRESS_FAX_OUTGOING))) {
09694          features |= DSP_FEATURE_FAX_DETECT;
09695       }
09696       x = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
09697       if (ioctl(i->subs[idx].dfd, DAHDI_TONEDETECT, &x)) {
09698          i->hardwaredtmf = 0;
09699          features |= DSP_FEATURE_DIGIT_DETECT;
09700       } else if (NEED_MFDETECT(i)) {
09701          i->hardwaredtmf = 1;
09702          features |= DSP_FEATURE_DIGIT_DETECT;
09703       }
09704    }
09705    if (features) {
09706       if (i->dsp) {
09707          ast_debug(1, "Already have a dsp on %s?\n", tmp->name);
09708       } else {
09709          if (i->channel != CHAN_PSEUDO)
09710             i->dsp = ast_dsp_new();
09711          else
09712             i->dsp = NULL;
09713          if (i->dsp) {
09714             i->dsp_features = features;
09715 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09716             /* We cannot do progress detection until receive PROGRESS message */
09717             if (i->outgoing && (dahdi_sig_pri_lib_handles(i->sig) || (i->sig == SIG_SS7))) {
09718                /* Remember requested DSP features, don't treat
09719                   talking as ANSWER */
09720                i->dsp_features = features & ~DSP_PROGRESS_TALK;
09721                features = 0;
09722             }
09723 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09724             ast_dsp_set_features(i->dsp, features);
09725             ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
09726             if (!ast_strlen_zero(progzone))
09727                ast_dsp_set_call_progress_zone(i->dsp, progzone);
09728             if (i->busydetect && CANBUSYDETECT(i)) {
09729                ast_dsp_set_busy_count(i->dsp, i->busycount);
09730                ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
09731             }
09732          }
09733       }
09734    }
09735 
09736    if (state == AST_STATE_RING)
09737       tmp->rings = 1;
09738    tmp->tech_pvt = i;
09739    if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
09740       /* Only FXO signalled stuff can be picked up */
09741       tmp->callgroup = i->callgroup;
09742       tmp->pickupgroup = i->pickupgroup;
09743    }
09744    if (!ast_strlen_zero(i->parkinglot))
09745       ast_string_field_set(tmp, parkinglot, i->parkinglot);
09746    if (!ast_strlen_zero(i->language))
09747       ast_string_field_set(tmp, language, i->language);
09748    if (!i->owner)
09749       i->owner = tmp;
09750    if (!ast_strlen_zero(i->accountcode))
09751       ast_string_field_set(tmp, accountcode, i->accountcode);
09752    if (i->amaflags)
09753       tmp->amaflags = i->amaflags;
09754    i->subs[idx].owner = tmp;
09755    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
09756    if (!analog_lib_handles(i->sig, i->radio, i->oprmode)) {
09757       ast_string_field_set(tmp, call_forward, i->call_forward);
09758    }
09759    /* If we've been told "no ADSI" then enforce it */
09760    if (!i->adsi)
09761       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
09762    if (!ast_strlen_zero(i->exten))
09763       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
09764    if (!ast_strlen_zero(i->rdnis)) {
09765       tmp->redirecting.from.number.valid = 1;
09766       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
09767    }
09768    if (!ast_strlen_zero(i->dnid)) {
09769       tmp->dialed.number.str = ast_strdup(i->dnid);
09770    }
09771 
09772    /* Don't use ast_set_callerid() here because it will
09773     * generate a needless NewCallerID event */
09774 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09775    if (!ast_strlen_zero(i->cid_ani)) {
09776       tmp->caller.ani.number.valid = 1;
09777       tmp->caller.ani.number.str = ast_strdup(i->cid_ani);
09778    } else if (!ast_strlen_zero(i->cid_num)) {
09779       tmp->caller.ani.number.valid = 1;
09780       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09781    }
09782 #else
09783    if (!ast_strlen_zero(i->cid_num)) {
09784       tmp->caller.ani.number.valid = 1;
09785       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09786    }
09787 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09788    tmp->caller.id.name.presentation = i->callingpres;
09789    tmp->caller.id.number.presentation = i->callingpres;
09790    tmp->caller.id.number.plan = i->cid_ton;
09791    tmp->caller.ani2 = i->cid_ani2;
09792    tmp->caller.id.tag = ast_strdup(i->cid_tag);
09793    /* clear the fake event in case we posted one before we had ast_channel */
09794    i->fake_event = 0;
09795    /* Assure there is no confmute on this channel */
09796    dahdi_confmute(i, 0);
09797    i->muting = 0;
09798    /* Configure the new channel jb */
09799    ast_jb_configure(tmp, &global_jbconf);
09800 
09801    /* Set initial device state */
09802    ast_copy_string(device_name, tmp->name, sizeof(device_name));
09803    dashptr = strrchr(device_name, '-');
09804    if (dashptr) {
09805       *dashptr = '\0';
09806    }
09807    tmp->flags |= AST_FLAG_DISABLE_DEVSTATE_CACHE;
09808    ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, AST_DEVSTATE_NOT_CACHABLE, device_name);
09809 
09810    for (v = i->vars ; v ; v = v->next)
09811       pbx_builtin_setvar_helper(tmp, v->name, v->value);
09812 
09813    ast_module_ref(ast_module_info->self);
09814 
09815    dahdi_ami_channel_event(i, tmp);
09816    if (startpbx) {
09817 #ifdef HAVE_OPENR2
09818       if (i->mfcr2call) {
09819          pbx_builtin_setvar_helper(tmp, "MFCR2_CATEGORY", openr2_proto_get_category_string(i->mfcr2_recvd_category));
09820       }
09821 #endif
09822       if (ast_pbx_start(tmp)) {
09823          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
09824          ast_hangup(tmp);
09825          return NULL;
09826       }
09827    }
09828    return tmp;
09829 }
09830 
09831 
09832 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
09833 {
09834    char c;
09835 
09836    *str = 0; /* start with empty output buffer */
09837    for (;;)
09838    {
09839       /* Wait for the first digit (up to specified ms). */
09840       c = ast_waitfordigit(chan, ms);
09841       /* if timeout, hangup or error, return as such */
09842       if (c < 1)
09843          return c;
09844       *str++ = c;
09845       *str = 0;
09846       if (strchr(term, c))
09847          return 1;
09848    }
09849 }
09850 
09851 static int dahdi_wink(struct dahdi_pvt *p, int idx)
09852 {
09853    int j;
09854    dahdi_set_hook(p->subs[idx].dfd, DAHDI_WINK);
09855    for (;;)
09856    {
09857       /* set bits of interest */
09858       j = DAHDI_IOMUX_SIGEVENT;
09859       /* wait for some happening */
09860       if (ioctl(p->subs[idx].dfd,DAHDI_IOMUX,&j) == -1) return(-1);
09861       /* exit loop if we have it */
09862       if (j & DAHDI_IOMUX_SIGEVENT) break;
09863    }
09864    /* get the event info */
09865    if (ioctl(p->subs[idx].dfd,DAHDI_GETEVENT,&j) == -1) return(-1);
09866    return 0;
09867 }
09868 
09869 /*! \brief enable or disable the chan_dahdi Do-Not-Disturb mode for a DAHDI channel
09870  * \param dahdichan "Physical" DAHDI channel (e.g: DAHDI/5)
09871  * \param flag on 1 to enable, 0 to disable, -1 return dnd value
09872  *
09873  * chan_dahdi has a DND (Do Not Disturb) mode for each dahdichan (physical
09874  * DAHDI channel). Use this to enable or disable it.
09875  *
09876  * \bug the use of the word "channel" for those dahdichans is really confusing.
09877  */
09878 static int dahdi_dnd(struct dahdi_pvt *dahdichan, int flag)
09879 {
09880    if (analog_lib_handles(dahdichan->sig, dahdichan->radio, dahdichan->oprmode)) {
09881       return analog_dnd(dahdichan->sig_pvt, flag);
09882    }
09883 
09884    if (flag == -1) {
09885       return dahdichan->dnd;
09886    }
09887 
09888    /* Do not disturb */
09889    dahdichan->dnd = flag;
09890    ast_verb(3, "%s DND on channel %d\n",
09891          flag? "Enabled" : "Disabled",
09892          dahdichan->channel);
09893    manager_event(EVENT_FLAG_SYSTEM, "DNDState",
09894          "Channel: DAHDI/%d\r\n"
09895          "Status: %s\r\n", dahdichan->channel,
09896          flag? "enabled" : "disabled");
09897 
09898    return 0;
09899 }
09900 
09901 static int canmatch_featurecode(const char *exten)
09902 {
09903    int extlen = strlen(exten);
09904    const char *pickup_ext;
09905    if (!extlen) {
09906       return 1;
09907    }
09908    pickup_ext = ast_pickup_ext();
09909    if (extlen < strlen(pickup_ext) && !strncmp(pickup_ext, exten, extlen)) {
09910       return 1;
09911    }
09912    /* hardcoded features are *60, *67, *69, *70, *72, *73, *78, *79, *82, *0 */
09913    if (exten[0] == '*' && extlen < 3) {
09914       if (extlen == 1) {
09915          return 1;
09916       }
09917       /* "*0" should be processed before it gets here */
09918       switch (exten[1]) {
09919       case '6':
09920       case '7':
09921       case '8':
09922          return 1;
09923       }
09924    }
09925    return 0;
09926 }
09927 
09928 static void *analog_ss_thread(void *data)
09929 {
09930    struct ast_channel *chan = data;
09931    struct dahdi_pvt *p = chan->tech_pvt;
09932    char exten[AST_MAX_EXTENSION] = "";
09933    char exten2[AST_MAX_EXTENSION] = "";
09934    unsigned char buf[256];
09935    char dtmfcid[300];
09936    char dtmfbuf[300];
09937    struct callerid_state *cs = NULL;
09938    char *name = NULL, *number = NULL;
09939    int distMatches;
09940    int curRingData[3];
09941    int receivedRingT;
09942    int counter1;
09943    int counter;
09944    int samples = 0;
09945    struct ast_smdi_md_message *smdi_msg = NULL;
09946    int flags = 0;
09947    int i;
09948    int timeout;
09949    int getforward = 0;
09950    char *s1, *s2;
09951    int len = 0;
09952    int res;
09953    int idx;
09954 
09955    ast_mutex_lock(&ss_thread_lock);
09956    ss_thread_count++;
09957    ast_mutex_unlock(&ss_thread_lock);
09958    /* in the bizarre case where the channel has become a zombie before we
09959       even get started here, abort safely
09960    */
09961    if (!p) {
09962       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
09963       ast_hangup(chan);
09964       goto quit;
09965    }
09966    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
09967    idx = dahdi_get_index(chan, p, 1);
09968    if (idx < 0) {
09969       ast_log(LOG_WARNING, "Huh?\n");
09970       ast_hangup(chan);
09971       goto quit;
09972    }
09973    if (p->dsp)
09974       ast_dsp_digitreset(p->dsp);
09975    switch (p->sig) {
09976    case SIG_FEATD:
09977    case SIG_FEATDMF:
09978    case SIG_FEATDMF_TA:
09979    case SIG_E911:
09980    case SIG_FGC_CAMAMF:
09981    case SIG_FEATB:
09982    case SIG_EMWINK:
09983    case SIG_SF_FEATD:
09984    case SIG_SF_FEATDMF:
09985    case SIG_SF_FEATB:
09986    case SIG_SFWINK:
09987       if (dahdi_wink(p, idx))
09988          goto quit;
09989       /* Fall through */
09990    case SIG_EM:
09991    case SIG_EM_E1:
09992    case SIG_SF:
09993    case SIG_FGC_CAMA:
09994       res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09995       if (p->dsp)
09996          ast_dsp_digitreset(p->dsp);
09997       /* set digit mode appropriately */
09998       if (p->dsp) {
09999          if (NEED_MFDETECT(p))
10000             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
10001          else
10002             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10003       }
10004       memset(dtmfbuf, 0, sizeof(dtmfbuf));
10005       /* Wait for the first digit only if immediate=no */
10006       if (!p->immediate)
10007          /* Wait for the first digit (up to 5 seconds). */
10008          res = ast_waitfordigit(chan, 5000);
10009       else
10010          res = 0;
10011       if (res > 0) {
10012          /* save first char */
10013          dtmfbuf[0] = res;
10014          switch (p->sig) {
10015          case SIG_FEATD:
10016          case SIG_SF_FEATD:
10017             res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
10018             if (res > 0)
10019                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
10020             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10021             break;
10022          case SIG_FEATDMF_TA:
10023             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10024             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10025             if (dahdi_wink(p, idx)) goto quit;
10026             dtmfbuf[0] = 0;
10027             /* Wait for the first digit (up to 5 seconds). */
10028             res = ast_waitfordigit(chan, 5000);
10029             if (res <= 0) break;
10030             dtmfbuf[0] = res;
10031             /* fall through intentionally */
10032          case SIG_FEATDMF:
10033          case SIG_E911:
10034          case SIG_FGC_CAMAMF:
10035          case SIG_SF_FEATDMF:
10036             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10037             /* if international caca, do it again to get real ANO */
10038             if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
10039             {
10040                if (dahdi_wink(p, idx)) goto quit;
10041                dtmfbuf[0] = 0;
10042                /* Wait for the first digit (up to 5 seconds). */
10043                res = ast_waitfordigit(chan, 5000);
10044                if (res <= 0) break;
10045                dtmfbuf[0] = res;
10046                res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10047             }
10048             if (res > 0) {
10049                /* if E911, take off hook */
10050                if (p->sig == SIG_E911)
10051                   dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10052                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
10053             }
10054             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10055             break;
10056          case SIG_FEATB:
10057          case SIG_SF_FEATB:
10058             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
10059             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10060             break;
10061          case SIG_EMWINK:
10062             /* if we received a '*', we are actually receiving Feature Group D
10063                dial syntax, so use that mode; otherwise, fall through to normal
10064                mode
10065             */
10066             if (res == '*') {
10067                res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
10068                if (res > 0)
10069                   res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
10070                if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
10071                break;
10072             }
10073          default:
10074             /* If we got the first digit, get the rest */
10075             len = 1;
10076             dtmfbuf[len] = '\0';
10077             while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
10078                if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
10079                   timeout = matchdigittimeout;
10080                } else {
10081                   timeout = gendigittimeout;
10082                }
10083                res = ast_waitfordigit(chan, timeout);
10084                if (res < 0) {
10085                   ast_debug(1, "waitfordigit returned < 0...\n");
10086                   ast_hangup(chan);
10087                   goto quit;
10088                } else if (res) {
10089                   dtmfbuf[len++] = res;
10090                   dtmfbuf[len] = '\0';
10091                } else {
10092                   break;
10093                }
10094             }
10095             break;
10096          }
10097       }
10098       if (res == -1) {
10099          ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
10100          ast_hangup(chan);
10101          goto quit;
10102       } else if (res < 0) {
10103          ast_debug(1, "Got hung up before digits finished\n");
10104          ast_hangup(chan);
10105          goto quit;
10106       }
10107 
10108       if (p->sig == SIG_FGC_CAMA) {
10109          char anibuf[100];
10110 
10111          if (ast_safe_sleep(chan,1000) == -1) {
10112             ast_hangup(chan);
10113             goto quit;
10114          }
10115          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10116          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
10117          res = my_getsigstr(chan, anibuf, "#", 10000);
10118          if ((res > 0) && (strlen(anibuf) > 2)) {
10119             if (anibuf[strlen(anibuf) - 1] == '#')
10120                anibuf[strlen(anibuf) - 1] = 0;
10121             ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
10122          }
10123          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10124       }
10125 
10126       ast_copy_string(exten, dtmfbuf, sizeof(exten));
10127       if (ast_strlen_zero(exten))
10128          ast_copy_string(exten, "s", sizeof(exten));
10129       if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
10130          /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
10131          if (exten[0] == '*') {
10132             char *stringp=NULL;
10133             ast_copy_string(exten2, exten, sizeof(exten2));
10134             /* Parse out extension and callerid */
10135             stringp=exten2 +1;
10136             s1 = strsep(&stringp, "*");
10137             s2 = strsep(&stringp, "*");
10138             if (s2) {
10139                if (!ast_strlen_zero(p->cid_num))
10140                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10141                else
10142                   ast_set_callerid(chan, s1, NULL, s1);
10143                ast_copy_string(exten, s2, sizeof(exten));
10144             } else
10145                ast_copy_string(exten, s1, sizeof(exten));
10146          } else if (p->sig == SIG_FEATD)
10147             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10148       }
10149       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
10150          if (exten[0] == '*') {
10151             char *stringp=NULL;
10152             ast_copy_string(exten2, exten, sizeof(exten2));
10153             /* Parse out extension and callerid */
10154             stringp=exten2 +1;
10155             s1 = strsep(&stringp, "#");
10156             s2 = strsep(&stringp, "#");
10157             if (s2) {
10158                if (!ast_strlen_zero(p->cid_num))
10159                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10160                else
10161                   if (*(s1 + 2))
10162                      ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
10163                ast_copy_string(exten, s2 + 1, sizeof(exten));
10164             } else
10165                ast_copy_string(exten, s1 + 2, sizeof(exten));
10166          } else
10167             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10168       }
10169       if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
10170          if (exten[0] == '*') {
10171             char *stringp=NULL;
10172             ast_copy_string(exten2, exten, sizeof(exten2));
10173             /* Parse out extension and callerid */
10174             stringp=exten2 +1;
10175             s1 = strsep(&stringp, "#");
10176             s2 = strsep(&stringp, "#");
10177             if (s2 && (*(s2 + 1) == '0')) {
10178                if (*(s2 + 2))
10179                   ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
10180             }
10181             if (s1)  ast_copy_string(exten, s1, sizeof(exten));
10182             else ast_copy_string(exten, "911", sizeof(exten));
10183          } else
10184             ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10185       }
10186       if (p->sig == SIG_FEATB) {
10187          if (exten[0] == '*') {
10188             char *stringp=NULL;
10189             ast_copy_string(exten2, exten, sizeof(exten2));
10190             /* Parse out extension and callerid */
10191             stringp=exten2 +1;
10192             s1 = strsep(&stringp, "#");
10193             ast_copy_string(exten, exten2 + 1, sizeof(exten));
10194          } else
10195             ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
10196       }
10197       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
10198          dahdi_wink(p, idx);
10199          /* some switches require a minimum guard time between
10200             the last FGD wink and something that answers
10201             immediately. This ensures it */
10202          if (ast_safe_sleep(chan, 100)) {
10203             ast_hangup(chan);
10204             goto quit;
10205          }
10206       }
10207       dahdi_enable_ec(p);
10208       if (NEED_MFDETECT(p)) {
10209          if (p->dsp) {
10210             if (!p->hardwaredtmf)
10211                ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
10212             else {
10213                ast_dsp_free(p->dsp);
10214                p->dsp = NULL;
10215             }
10216          }
10217       }
10218 
10219       if (ast_exists_extension(chan, chan->context, exten, 1,
10220          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
10221          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
10222          if (p->dsp) ast_dsp_digitreset(p->dsp);
10223          res = ast_pbx_run(chan);
10224          if (res) {
10225             ast_log(LOG_WARNING, "PBX exited non-zero\n");
10226             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10227          }
10228          goto quit;
10229       } else {
10230          ast_verb(2, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
10231          sleep(2);
10232          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_INFO);
10233          if (res < 0)
10234             ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
10235          else
10236             sleep(1);
10237          res = ast_streamfile(chan, "ss-noservice", chan->language);
10238          if (res >= 0)
10239             ast_waitstream(chan, "");
10240          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10241          ast_hangup(chan);
10242          goto quit;
10243       }
10244       break;
10245    case SIG_FXOLS:
10246    case SIG_FXOGS:
10247    case SIG_FXOKS:
10248       /* Read the first digit */
10249       timeout = firstdigittimeout;
10250       /* If starting a threeway call, never timeout on the first digit so someone
10251          can use flash-hook as a "hold" feature */
10252       if (p->subs[SUB_THREEWAY].owner)
10253          timeout = 999999;
10254       while (len < AST_MAX_EXTENSION-1) {
10255          /* Read digit unless it's supposed to be immediate, in which case the
10256             only answer is 's' */
10257          if (p->immediate)
10258             res = 's';
10259          else
10260             res = ast_waitfordigit(chan, timeout);
10261          timeout = 0;
10262          if (res < 0) {
10263             ast_debug(1, "waitfordigit returned < 0...\n");
10264             res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10265             ast_hangup(chan);
10266             goto quit;
10267          } else if (res) {
10268             ast_debug(1,"waitfordigit returned '%c' (%d), timeout = %d\n", res, res, timeout);
10269             exten[len++]=res;
10270             exten[len] = '\0';
10271          }
10272          if (!ast_ignore_pattern(chan->context, exten))
10273             tone_zone_play_tone(p->subs[idx].dfd, -1);
10274          else
10275             tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
10276          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && !ast_parking_ext_valid(exten, chan, chan->context)) {
10277             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
10278                if (getforward) {
10279                   /* Record this as the forwarding extension */
10280                   ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
10281                   ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
10282                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10283                   if (res)
10284                      break;
10285                   usleep(500000);
10286                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10287                   sleep(1);
10288                   memset(exten, 0, sizeof(exten));
10289                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
10290                   len = 0;
10291                   getforward = 0;
10292                } else {
10293                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
10294                   ast_copy_string(chan->exten, exten, sizeof(chan->exten));
10295                   if (!ast_strlen_zero(p->cid_num)) {
10296                      if (!p->hidecallerid)
10297                         ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
10298                      else
10299                         ast_set_callerid(chan, NULL, NULL, p->cid_num);
10300                   }
10301                   if (!ast_strlen_zero(p->cid_name)) {
10302                      if (!p->hidecallerid)
10303                         ast_set_callerid(chan, NULL, p->cid_name, NULL);
10304                   }
10305                   ast_setstate(chan, AST_STATE_RING);
10306                   dahdi_enable_ec(p);
10307                   res = ast_pbx_run(chan);
10308                   if (res) {
10309                      ast_log(LOG_WARNING, "PBX exited non-zero\n");
10310                      res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10311                   }
10312                   goto quit;
10313                }
10314             } else {
10315                /* It's a match, but they just typed a digit, and there is an ambiguous match,
10316                   so just set the timeout to matchdigittimeout and wait some more */
10317                timeout = matchdigittimeout;
10318             }
10319          } else if (res == 0) {
10320             ast_debug(1, "not enough digits (and no ambiguous match)...\n");
10321             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10322             dahdi_wait_event(p->subs[idx].dfd);
10323             ast_hangup(chan);
10324             goto quit;
10325          } else if (p->callwaiting && !strcmp(exten, "*70")) {
10326             ast_verb(3, "Disabling call waiting on %s\n", chan->name);
10327             /* Disable call waiting if enabled */
10328             p->callwaiting = 0;
10329             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10330             if (res) {
10331                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10332                   chan->name, strerror(errno));
10333             }
10334             len = 0;
10335             ioctl(p->subs[idx].dfd,DAHDI_CONFDIAG,&len);
10336             memset(exten, 0, sizeof(exten));
10337             timeout = firstdigittimeout;
10338 
10339          } else if (!strcmp(exten,ast_pickup_ext())) {
10340             /* Scan all channels and see if there are any
10341              * ringing channels that have call groups
10342              * that equal this channels pickup group
10343              */
10344             if (idx == SUB_REAL) {
10345                /* Switch us from Third call to Call Wait */
10346                if (p->subs[SUB_THREEWAY].owner) {
10347                   /* If you make a threeway call and the *8# a call, it should actually
10348                      look like a callwait */
10349                   alloc_sub(p, SUB_CALLWAIT);
10350                   swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
10351                   unalloc_sub(p, SUB_THREEWAY);
10352                }
10353                dahdi_enable_ec(p);
10354                if (ast_pickup_call(chan)) {
10355                   ast_debug(1, "No call pickup possible...\n");
10356                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10357                   dahdi_wait_event(p->subs[idx].dfd);
10358                }
10359                ast_hangup(chan);
10360                goto quit;
10361             } else {
10362                ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
10363                ast_hangup(chan);
10364                goto quit;
10365             }
10366 
10367          } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
10368             ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
10369             /* Disable Caller*ID if enabled */
10370             p->hidecallerid = 1;
10371             ast_party_number_free(&chan->caller.id.number);
10372             ast_party_number_init(&chan->caller.id.number);
10373             ast_party_name_free(&chan->caller.id.name);
10374             ast_party_name_init(&chan->caller.id.name);
10375             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10376             if (res) {
10377                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10378                   chan->name, strerror(errno));
10379             }
10380             len = 0;
10381             memset(exten, 0, sizeof(exten));
10382             timeout = firstdigittimeout;
10383          } else if (p->callreturn && !strcmp(exten, "*69")) {
10384             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10385             break;
10386          } else if (!strcmp(exten, "*78")) {
10387             dahdi_dnd(p, 1);
10388             /* Do not disturb */
10389             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10390             getforward = 0;
10391             memset(exten, 0, sizeof(exten));
10392             len = 0;
10393          } else if (!strcmp(exten, "*79")) {
10394             dahdi_dnd(p, 0);
10395             /* Do not disturb */
10396             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10397             getforward = 0;
10398             memset(exten, 0, sizeof(exten));
10399             len = 0;
10400          } else if (p->cancallforward && !strcmp(exten, "*72")) {
10401             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10402             getforward = 1;
10403             memset(exten, 0, sizeof(exten));
10404             len = 0;
10405          } else if (p->cancallforward && !strcmp(exten, "*73")) {
10406             ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
10407             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10408             memset(p->call_forward, 0, sizeof(p->call_forward));
10409             getforward = 0;
10410             memset(exten, 0, sizeof(exten));
10411             len = 0;
10412          } else if ((p->transfer || p->canpark) && ast_parking_ext_valid(exten, chan, chan->context) &&
10413                   p->subs[SUB_THREEWAY].owner &&
10414                   ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
10415             /* This is a three way call, the main call being a real channel,
10416                and we're parking the first call. */
10417             ast_masq_park_call_exten(ast_bridged_channel(p->subs[SUB_THREEWAY].owner),
10418                chan, exten, chan->context, 0, NULL);
10419             ast_verb(3, "Parking call to '%s'\n", chan->name);
10420             break;
10421          } else if (p->hidecallerid && !strcmp(exten, "*82")) {
10422             ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
10423             /* Enable Caller*ID if enabled */
10424             p->hidecallerid = 0;
10425             ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
10426             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
10427             if (res) {
10428                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
10429                   chan->name, strerror(errno));
10430             }
10431             len = 0;
10432             memset(exten, 0, sizeof(exten));
10433             timeout = firstdigittimeout;
10434          } else if (!strcmp(exten, "*0")) {
10435             struct ast_channel *nbridge =
10436                p->subs[SUB_THREEWAY].owner;
10437             struct dahdi_pvt *pbridge = NULL;
10438             /* set up the private struct of the bridged one, if any */
10439             if (nbridge && ast_bridged_channel(nbridge))
10440                pbridge = ast_bridged_channel(nbridge)->tech_pvt;
10441             if (nbridge && pbridge &&
10442                (nbridge->tech == &dahdi_tech) &&
10443                (ast_bridged_channel(nbridge)->tech == &dahdi_tech) &&
10444                ISTRUNK(pbridge)) {
10445                int func = DAHDI_FLASH;
10446                /* Clear out the dial buffer */
10447                p->dop.dialstr[0] = '\0';
10448                /* flash hookswitch */
10449                if ((ioctl(pbridge->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
10450                   ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
10451                      nbridge->name, strerror(errno));
10452                }
10453                swap_subs(p, SUB_REAL, SUB_THREEWAY);
10454                unalloc_sub(p, SUB_THREEWAY);
10455                p->owner = p->subs[SUB_REAL].owner;
10456                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
10457                   ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
10458                ast_hangup(chan);
10459                goto quit;
10460             } else {
10461                tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10462                dahdi_wait_event(p->subs[idx].dfd);
10463                tone_zone_play_tone(p->subs[idx].dfd, -1);
10464                swap_subs(p, SUB_REAL, SUB_THREEWAY);
10465                unalloc_sub(p, SUB_THREEWAY);
10466                p->owner = p->subs[SUB_REAL].owner;
10467                ast_hangup(chan);
10468                goto quit;
10469             }
10470          } else if (!ast_canmatch_extension(chan, chan->context, exten, 1,
10471             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
10472             && !canmatch_featurecode(exten)) {
10473             ast_debug(1, "Can't match %s from '%s' in context %s\n", exten,
10474                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<Unknown Caller>"),
10475                chan->context);
10476             break;
10477          }
10478          if (!timeout)
10479             timeout = gendigittimeout;
10480          if (len && !ast_ignore_pattern(chan->context, exten))
10481             tone_zone_play_tone(p->subs[idx].dfd, -1);
10482       }
10483       break;
10484    case SIG_FXSLS:
10485    case SIG_FXSGS:
10486    case SIG_FXSKS:
10487       /* check for SMDI messages */
10488       if (p->use_smdi && p->smdi_iface) {
10489          smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
10490 
10491          if (smdi_msg != NULL) {
10492             ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
10493 
10494             if (smdi_msg->type == 'B')
10495                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
10496             else if (smdi_msg->type == 'N')
10497                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
10498 
10499             ast_debug(1, "Received SMDI message on %s\n", chan->name);
10500          } else {
10501             ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
10502          }
10503       }
10504 
10505       if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
10506          number = smdi_msg->calling_st;
10507 
10508       /* If we want caller id, we're in a prering state due to a polarity reversal
10509        * and we're set to use a polarity reversal to trigger the start of caller id,
10510        * grab the caller id and wait for ringing to start... */
10511       } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING &&
10512                    (p->cid_start == CID_START_POLARITY || p->cid_start == CID_START_POLARITY_IN || p->cid_start == CID_START_DTMF_NOALERT))) {
10513          /* If set to use DTMF CID signalling, listen for DTMF */
10514          if (p->cid_signalling == CID_SIG_DTMF) {
10515             int k = 0;
10516             int off_ms;
10517             struct timeval start = ast_tvnow();
10518             int ms;
10519             cs = NULL;
10520             ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
10521             dahdi_setlinear(p->subs[idx].dfd, 0);
10522             /*
10523              * We are the only party interested in the Rx stream since
10524              * we have not answered yet.  We don't need or even want DTMF
10525              * emulation.  The DTMF digits can come so fast that emulation
10526              * can drop some of them.
10527              */
10528             ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
10529             off_ms = 4000;/* This is a typical OFF time between rings. */
10530             for (;;) {
10531                struct ast_frame *f;
10532 
10533                ms = ast_remaining_ms(start, off_ms);
10534                res = ast_waitfor(chan, ms);
10535                if (res <= 0) {
10536                   /*
10537                    * We do not need to restore the dahdi_setlinear()
10538                    * or AST_FLAG_END_DTMF_ONLY flag settings since we
10539                    * are hanging up the channel.
10540                    */
10541                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10542                      "Exiting simple switch\n");
10543                   ast_hangup(chan);
10544                   goto quit;
10545                }
10546                f = ast_read(chan);
10547                if (!f)
10548                   break;
10549                if (f->frametype == AST_FRAME_DTMF) {
10550                   if (k < ARRAY_LEN(dtmfbuf) - 1) {
10551                      dtmfbuf[k++] = f->subclass.integer;
10552                   }
10553                   ast_debug(1, "CID got digit '%c'\n", f->subclass.integer);
10554                   start = ast_tvnow();
10555                }
10556                ast_frfree(f);
10557                if (chan->_state == AST_STATE_RING ||
10558                   chan->_state == AST_STATE_RINGING)
10559                   break; /* Got ring */
10560             }
10561             ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
10562             dtmfbuf[k] = '\0';
10563             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10564             /* Got cid and ring. */
10565             ast_debug(1, "CID got string '%s'\n", dtmfbuf);
10566             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10567             ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
10568             /* If first byte is NULL, we have no cid */
10569             if (!ast_strlen_zero(dtmfcid))
10570                number = dtmfcid;
10571             else
10572                number = NULL;
10573          /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10574          } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
10575             cs = callerid_new(p->cid_signalling);
10576             if (cs) {
10577                int off_ms;
10578                struct timeval start;
10579                int ms;
10580                samples = 0;
10581 #if 1
10582                bump_gains(p);
10583 #endif
10584                /* Take out of linear mode for Caller*ID processing */
10585                dahdi_setlinear(p->subs[idx].dfd, 0);
10586 
10587                /* First we wait and listen for the Caller*ID */
10588                for (;;) {
10589                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10590                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10591                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10592                      callerid_free(cs);
10593                      ast_hangup(chan);
10594                      goto quit;
10595                   }
10596                   if (i & DAHDI_IOMUX_SIGEVENT) {
10597                      res = dahdi_get_event(p->subs[idx].dfd);
10598                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10599                      if (res == DAHDI_EVENT_NOALARM) {
10600                         p->inalarm = 0;
10601                      }
10602 
10603                      if (p->cid_signalling == CID_SIG_V23_JP) {
10604                         if (res == DAHDI_EVENT_RINGBEGIN) {
10605                            res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10606                            usleep(1);
10607                         }
10608                      } else {
10609                         res = 0;
10610                         break;
10611                      }
10612                   } else if (i & DAHDI_IOMUX_READ) {
10613                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10614                      if (res < 0) {
10615                         if (errno != ELAST) {
10616                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10617                            callerid_free(cs);
10618                            ast_hangup(chan);
10619                            goto quit;
10620                         }
10621                         break;
10622                      }
10623                      samples += res;
10624 
10625                      if (p->cid_signalling == CID_SIG_V23_JP) {
10626                         res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
10627                      } else {
10628                         res = callerid_feed(cs, buf, res, AST_LAW(p));
10629                      }
10630                      if (res < 0) {
10631                         /*
10632                          * The previous diagnostic message output likely
10633                          * explains why it failed.
10634                          */
10635                         ast_log(LOG_WARNING,
10636                            "Failed to decode CallerID on channel '%s'\n",
10637                            chan->name);
10638                         break;
10639                      } else if (res)
10640                         break;
10641                      else if (samples > (8000 * 10))
10642                         break;
10643                   }
10644                }
10645                if (res == 1) {
10646                   callerid_get(cs, &name, &number, &flags);
10647                   ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10648                }
10649 
10650                if (p->cid_signalling == CID_SIG_V23_JP) {
10651                   res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
10652                   usleep(1);
10653                }
10654 
10655                /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
10656                start = ast_tvnow();
10657                off_ms = 4000;/* This is a typical OFF time between rings. */
10658                for (;;) {
10659                   struct ast_frame *f;
10660 
10661                   ms = ast_remaining_ms(start, off_ms);
10662                   res = ast_waitfor(chan, ms);
10663                   if (res <= 0) {
10664                      ast_log(LOG_WARNING, "CID timed out waiting for ring. "
10665                         "Exiting simple switch\n");
10666                      ast_hangup(chan);
10667                      goto quit;
10668                   }
10669                   if (!(f = ast_read(chan))) {
10670                      ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
10671                      ast_hangup(chan);
10672                      goto quit;
10673                   }
10674                   ast_frfree(f);
10675                   if (chan->_state == AST_STATE_RING ||
10676                      chan->_state == AST_STATE_RINGING)
10677                      break; /* Got ring */
10678                }
10679 
10680                /* We must have a ring by now, so, if configured, lets try to listen for
10681                 * distinctive ringing */
10682                if (p->usedistinctiveringdetection) {
10683                   len = 0;
10684                   distMatches = 0;
10685                   /* Clear the current ring data array so we don't have old data in it. */
10686                   for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10687                      curRingData[receivedRingT] = 0;
10688                   receivedRingT = 0;
10689                   counter = 0;
10690                   counter1 = 0;
10691                   /* Check to see if context is what it should be, if not set to be. */
10692                   if (strcmp(p->context,p->defcontext) != 0) {
10693                      ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10694                      ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10695                   }
10696 
10697                   for (;;) {
10698                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10699                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10700                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10701                         callerid_free(cs);
10702                         ast_hangup(chan);
10703                         goto quit;
10704                      }
10705                      if (i & DAHDI_IOMUX_SIGEVENT) {
10706                         res = dahdi_get_event(p->subs[idx].dfd);
10707                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10708                         if (res == DAHDI_EVENT_NOALARM) {
10709                            p->inalarm = 0;
10710                         }
10711                         res = 0;
10712                         /* Let us detect distinctive ring */
10713 
10714                         curRingData[receivedRingT] = p->ringt;
10715 
10716                         if (p->ringt < p->ringt_base/2)
10717                            break;
10718                         /* Increment the ringT counter so we can match it against
10719                            values in chan_dahdi.conf for distinctive ring */
10720                         if (++receivedRingT == ARRAY_LEN(curRingData))
10721                            break;
10722                      } else if (i & DAHDI_IOMUX_READ) {
10723                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10724                         if (res < 0) {
10725                            if (errno != ELAST) {
10726                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10727                               callerid_free(cs);
10728                               ast_hangup(chan);
10729                               goto quit;
10730                            }
10731                            break;
10732                         }
10733                         if (p->ringt > 0) {
10734                            if (!(--p->ringt)) {
10735                               res = -1;
10736                               break;
10737                            }
10738                         }
10739                      }
10740                   }
10741                      /* this only shows up if you have n of the dring patterns filled in */
10742                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10743                   for (counter = 0; counter < 3; counter++) {
10744                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10745                      channel */
10746                      distMatches = 0;
10747                      for (counter1 = 0; counter1 < 3; counter1++) {
10748                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10749                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10750                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10751                            curRingData[counter1]);
10752                            distMatches++;
10753                         } else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10754                               curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10755                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10756                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10757                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10758                            distMatches++;
10759                         }
10760                      }
10761 
10762                      if (distMatches == 3) {
10763                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10764                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10765                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10766                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10767                         break;
10768                      }
10769                   }
10770                }
10771                /* Restore linear mode (if appropriate) for Caller*ID processing */
10772                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10773 #if 1
10774                restore_gains(p);
10775 #endif
10776             } else
10777                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10778          } else {
10779             ast_log(LOG_WARNING, "Channel %s in prering "
10780                "state, but I have nothing to do. "
10781                "Terminating simple switch, should be "
10782                "restarted by the actual ring.\n",
10783                chan->name);
10784             ast_hangup(chan);
10785             goto quit;
10786          }
10787       } else if (p->use_callerid && p->cid_start == CID_START_RING) {
10788          if (p->cid_signalling == CID_SIG_DTMF) {
10789             int k = 0;
10790             int off_ms;
10791             struct timeval start;
10792             int ms;
10793             cs = NULL;
10794             dahdi_setlinear(p->subs[idx].dfd, 0);
10795             off_ms = 2000;
10796             start = ast_tvnow();
10797             for (;;) {
10798                struct ast_frame *f;
10799 
10800                ms = ast_remaining_ms(start, off_ms);
10801                res = ast_waitfor(chan, ms);
10802                if (res <= 0) {
10803                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10804                      "Exiting simple switch\n");
10805                   ast_hangup(chan);
10806                   goto quit;
10807                }
10808                f = ast_read(chan);
10809                if (!f) {
10810                   /* Hangup received waiting for DTMFCID. Exiting simple switch. */
10811                   ast_hangup(chan);
10812                   goto quit;
10813                }
10814                if (f->frametype == AST_FRAME_DTMF) {
10815                   dtmfbuf[k++] = f->subclass.integer;
10816                   ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass.integer);
10817                   start = ast_tvnow();
10818                }
10819                ast_frfree(f);
10820 
10821                if (p->ringt_base == p->ringt)
10822                   break;
10823             }
10824             dtmfbuf[k] = '\0';
10825             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10826             /* Got cid and ring. */
10827             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10828             ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
10829                dtmfcid, flags);
10830             /* If first byte is NULL, we have no cid */
10831             if (!ast_strlen_zero(dtmfcid))
10832                number = dtmfcid;
10833             else
10834                number = NULL;
10835             /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10836          } else {
10837             /* FSK Bell202 callerID */
10838             cs = callerid_new(p->cid_signalling);
10839             if (cs) {
10840 #if 1
10841                bump_gains(p);
10842 #endif
10843                samples = 0;
10844                len = 0;
10845                distMatches = 0;
10846                /* Clear the current ring data array so we don't have old data in it. */
10847                for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10848                   curRingData[receivedRingT] = 0;
10849                receivedRingT = 0;
10850                counter = 0;
10851                counter1 = 0;
10852                /* Check to see if context is what it should be, if not set to be. */
10853                if (strcmp(p->context,p->defcontext) != 0) {
10854                   ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10855                   ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10856                }
10857 
10858                /* Take out of linear mode for Caller*ID processing */
10859                dahdi_setlinear(p->subs[idx].dfd, 0);
10860                for (;;) {
10861                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10862                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10863                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10864                      callerid_free(cs);
10865                      ast_hangup(chan);
10866                      goto quit;
10867                   }
10868                   if (i & DAHDI_IOMUX_SIGEVENT) {
10869                      res = dahdi_get_event(p->subs[idx].dfd);
10870                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10871                      if (res == DAHDI_EVENT_NOALARM) {
10872                         p->inalarm = 0;
10873                      }
10874                      /* If we get a PR event, they hung up while processing calerid */
10875                      if ( res == DAHDI_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
10876                         ast_log(LOG_DEBUG, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
10877                         p->polarity = POLARITY_IDLE;
10878                         callerid_free(cs);
10879                         ast_hangup(chan);
10880                         goto quit;
10881                      }
10882                      res = 0;
10883                      /* Let us detect callerid when the telco uses distinctive ring */
10884 
10885                      curRingData[receivedRingT] = p->ringt;
10886 
10887                      if (p->ringt < p->ringt_base/2)
10888                         break;
10889                      /* Increment the ringT counter so we can match it against
10890                         values in chan_dahdi.conf for distinctive ring */
10891                      if (++receivedRingT == ARRAY_LEN(curRingData))
10892                         break;
10893                   } else if (i & DAHDI_IOMUX_READ) {
10894                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10895                      if (res < 0) {
10896                         if (errno != ELAST) {
10897                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10898                            callerid_free(cs);
10899                            ast_hangup(chan);
10900                            goto quit;
10901                         }
10902                         break;
10903                      }
10904                      if (p->ringt > 0) {
10905                         if (!(--p->ringt)) {
10906                            res = -1;
10907                            break;
10908                         }
10909                      }
10910                      samples += res;
10911                      res = callerid_feed(cs, buf, res, AST_LAW(p));
10912                      if (res < 0) {
10913                         /*
10914                          * The previous diagnostic message output likely
10915                          * explains why it failed.
10916                          */
10917                         ast_log(LOG_WARNING,
10918                            "Failed to decode CallerID on channel '%s'\n",
10919                            chan->name);
10920                         break;
10921                      } else if (res)
10922                         break;
10923                      else if (samples > (8000 * 10))
10924                         break;
10925                   }
10926                }
10927                if (res == 1) {
10928                   callerid_get(cs, &name, &number, &flags);
10929                   ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10930                }
10931                if (distinctiveringaftercid == 1) {
10932                   /* Clear the current ring data array so we don't have old data in it. */
10933                   for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
10934                      curRingData[receivedRingT] = 0;
10935                   }
10936                   receivedRingT = 0;
10937                   ast_verb(3, "Detecting post-CID distinctive ring\n");
10938                   for (;;) {
10939                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10940                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10941                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10942                         callerid_free(cs);
10943                         ast_hangup(chan);
10944                         goto quit;
10945                      }
10946                      if (i & DAHDI_IOMUX_SIGEVENT) {
10947                         res = dahdi_get_event(p->subs[idx].dfd);
10948                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10949                         if (res == DAHDI_EVENT_NOALARM) {
10950                            p->inalarm = 0;
10951                         }
10952                         res = 0;
10953                         /* Let us detect callerid when the telco uses distinctive ring */
10954 
10955                         curRingData[receivedRingT] = p->ringt;
10956 
10957                         if (p->ringt < p->ringt_base/2)
10958                            break;
10959                         /* Increment the ringT counter so we can match it against
10960                            values in chan_dahdi.conf for distinctive ring */
10961                         if (++receivedRingT == ARRAY_LEN(curRingData))
10962                            break;
10963                      } else if (i & DAHDI_IOMUX_READ) {
10964                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10965                         if (res < 0) {
10966                            if (errno != ELAST) {
10967                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10968                               callerid_free(cs);
10969                               ast_hangup(chan);
10970                               goto quit;
10971                            }
10972                            break;
10973                         }
10974                         if (p->ringt > 0) {
10975                            if (!(--p->ringt)) {
10976                               res = -1;
10977                               break;
10978                            }
10979                         }
10980                      }
10981                   }
10982                }
10983                if (p->usedistinctiveringdetection) {
10984                   /* this only shows up if you have n of the dring patterns filled in */
10985                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10986 
10987                   for (counter = 0; counter < 3; counter++) {
10988                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10989                      channel */
10990                      /* this only shows up if you have n of the dring patterns filled in */
10991                      ast_verb(3, "Checking %d,%d,%d\n",
10992                            p->drings.ringnum[counter].ring[0],
10993                            p->drings.ringnum[counter].ring[1],
10994                            p->drings.ringnum[counter].ring[2]);
10995                      distMatches = 0;
10996                      for (counter1 = 0; counter1 < 3; counter1++) {
10997                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10998                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10999                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
11000                            curRingData[counter1]);
11001                            distMatches++;
11002                         }
11003                         else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
11004                            curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
11005                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
11006                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
11007                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
11008                            distMatches++;
11009                         }
11010                      }
11011                      if (distMatches == 3) {
11012                         /* The ring matches, set the context to whatever is for distinctive ring.. */
11013                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
11014                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
11015                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
11016                         break;
11017                      }
11018                   }
11019                }
11020                /* Restore linear mode (if appropriate) for Caller*ID processing */
11021                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
11022 #if 1
11023                restore_gains(p);
11024 #endif
11025                if (res < 0) {
11026                   ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
11027                }
11028             } else
11029                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
11030          }
11031       } else
11032          cs = NULL;
11033 
11034       if (number)
11035          ast_shrink_phone_number(number);
11036       ast_set_callerid(chan, number, name, number);
11037 
11038       if (smdi_msg)
11039          ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
11040 
11041       if (cs)
11042          callerid_free(cs);
11043 
11044       my_handle_notify_message(chan, p, flags, -1);
11045 
11046       ast_setstate(chan, AST_STATE_RING);
11047       chan->rings = 1;
11048       p->ringt = p->ringt_base;
11049       res = ast_pbx_run(chan);
11050       if (res) {
11051          ast_hangup(chan);
11052          ast_log(LOG_WARNING, "PBX exited non-zero\n");
11053       }
11054       goto quit;
11055    default:
11056       ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
11057       res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
11058       if (res < 0)
11059             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
11060    }
11061    res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
11062    if (res < 0)
11063          ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
11064    ast_hangup(chan);
11065 quit:
11066    ast_mutex_lock(&ss_thread_lock);
11067    ss_thread_count--;
11068    ast_cond_signal(&ss_thread_complete);
11069    ast_mutex_unlock(&ss_thread_lock);
11070    return NULL;
11071 }
11072 
11073 struct mwi_thread_data {
11074    struct dahdi_pvt *pvt;
11075    unsigned char buf[READ_SIZE];
11076    size_t len;
11077 };
11078 
11079 static int calc_energy(const unsigned char *buf, int len, format_t law)
11080 {
11081    int x;
11082    int sum = 0;
11083 
11084    if (!len)
11085       return 0;
11086 
11087    for (x = 0; x < len; x++)
11088       sum += abs(law == AST_FORMAT_ULAW ? AST_MULAW(buf[x]) : AST_ALAW(buf[x]));
11089 
11090    return sum / len;
11091 }
11092 
11093 static void *mwi_thread(void *data)
11094 {
11095    struct mwi_thread_data *mtd = data;
11096    struct callerid_state *cs;
11097    pthread_t threadid;
11098    int samples = 0;
11099    char *name, *number;
11100    int flags;
11101    int i, res;
11102    unsigned int spill_done = 0;
11103    int spill_result = -1;
11104 
11105    if (!(cs = callerid_new(mtd->pvt->cid_signalling))) {
11106       goto quit_no_clean;
11107    }
11108 
11109    callerid_feed(cs, mtd->buf, mtd->len, AST_LAW(mtd->pvt));
11110 
11111    bump_gains(mtd->pvt);
11112 
11113    for (;;) {
11114       i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
11115       if ((res = ioctl(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_IOMUX, &i))) {
11116          ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
11117          goto quit;
11118       }
11119 
11120       if (i & DAHDI_IOMUX_SIGEVENT) {
11121          struct ast_channel *chan;
11122 
11123          /* If we get an event, screen out events that we do not act on.
11124           * Otherwise, cancel and go to the simple switch to let it deal with it.
11125           */
11126          res = dahdi_get_event(mtd->pvt->subs[SUB_REAL].dfd);
11127 
11128          switch (res) {
11129          case DAHDI_EVENT_NEONMWI_ACTIVE:
11130          case DAHDI_EVENT_NEONMWI_INACTIVE:
11131          case DAHDI_EVENT_NONE:
11132          case DAHDI_EVENT_BITSCHANGED:
11133             break;
11134          case DAHDI_EVENT_NOALARM:
11135             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11136                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
11137 
11138                analog_p->inalarm = 0;
11139             }
11140             mtd->pvt->inalarm = 0;
11141             handle_clear_alarms(mtd->pvt);
11142             break;
11143          case DAHDI_EVENT_ALARM:
11144             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11145                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
11146 
11147                analog_p->inalarm = 1;
11148             }
11149             mtd->pvt->inalarm = 1;
11150             res = get_alarms(mtd->pvt);
11151             handle_alarms(mtd->pvt, res);
11152             break; /* What to do on channel alarm ???? -- fall thru intentionally?? */
11153          default:
11154             ast_log(LOG_NOTICE, "Got event %d (%s)...  Passing along to analog_ss_thread\n", res, event2str(res));
11155             callerid_free(cs);
11156 
11157             restore_gains(mtd->pvt);
11158             mtd->pvt->ringt = mtd->pvt->ringt_base;
11159 
11160             if ((chan = dahdi_new(mtd->pvt, AST_STATE_RING, 0, SUB_REAL, 0, NULL))) {
11161                int result;
11162 
11163                if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
11164                   result = analog_ss_thread_start(mtd->pvt->sig_pvt, chan);
11165                } else {
11166                   result = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11167                }
11168                if (result) {
11169                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", mtd->pvt->channel);
11170                   res = tone_zone_play_tone(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11171                   if (res < 0)
11172                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", mtd->pvt->channel);
11173                   ast_hangup(chan);
11174                }
11175             } else {
11176                ast_log(LOG_WARNING, "Could not create channel to handle call\n");
11177             }
11178             goto quit_no_clean;
11179          }
11180       } else if (i & DAHDI_IOMUX_READ) {
11181          if ((res = read(mtd->pvt->subs[SUB_REAL].dfd, mtd->buf, sizeof(mtd->buf))) < 0) {
11182             if (errno != ELAST) {
11183                ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
11184                goto quit;
11185             }
11186             break;
11187          }
11188          samples += res;
11189          if (!spill_done) {
11190             if ((spill_result = callerid_feed(cs, mtd->buf, res, AST_LAW(mtd->pvt))) < 0) {
11191                /*
11192                 * The previous diagnostic message output likely
11193                 * explains why it failed.
11194                 */
11195                ast_log(LOG_WARNING, "Failed to decode CallerID\n");
11196                break;
11197             } else if (spill_result) {
11198                spill_done = 1;
11199             }
11200          } else {
11201             /* keep reading data until the energy level drops below the threshold
11202                so we don't get another 'trigger' on the remaining carrier signal
11203             */
11204             if (calc_energy(mtd->buf, res, AST_LAW(mtd->pvt)) <= mwilevel)
11205                break;
11206          }
11207          if (samples > (8000 * 4)) /*Termination case - time to give up*/
11208             break;
11209       }
11210    }
11211 
11212    if (spill_result == 1) {
11213       callerid_get(cs, &name, &number, &flags);
11214       if (flags & CID_MSGWAITING) {
11215          ast_log(LOG_NOTICE, "mwi: Have Messages on channel %d\n", mtd->pvt->channel);
11216          notify_message(mtd->pvt->mailbox, 1);
11217       } else if (flags & CID_NOMSGWAITING) {
11218          ast_log(LOG_NOTICE, "mwi: No Messages on channel %d\n", mtd->pvt->channel);
11219          notify_message(mtd->pvt->mailbox, 0);
11220       } else {
11221          ast_log(LOG_NOTICE, "mwi: Status unknown on channel %d\n", mtd->pvt->channel);
11222       }
11223    }
11224 
11225 
11226 quit:
11227    callerid_free(cs);
11228 
11229    restore_gains(mtd->pvt);
11230 
11231 quit_no_clean:
11232    mtd->pvt->mwimonitoractive = 0;
11233    ast_free(mtd);
11234 
11235    return NULL;
11236 }
11237 
11238 /*
11239 * The following three functions (mwi_send_init, mwi_send_process_buffer,
11240 * mwi_send_process_event) work with the do_monitor thread to generate mwi spills
11241 * that are sent out via FXS port on voicemail state change.  The execution of
11242 * the mwi send is state driven and can either generate a ring pulse prior to
11243 * sending the fsk spill or simply send an fsk spill.
11244 */
11245 static int mwi_send_init(struct dahdi_pvt * pvt)
11246 {
11247    int x;
11248 
11249 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11250    /* Determine how this spill is to be sent */
11251    if (pvt->mwisend_rpas) {
11252       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
11253       pvt->mwisendactive = 1;
11254    } else if (pvt->mwisend_fsk) {
11255       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11256       pvt->mwisendactive = 1;
11257    } else {
11258       pvt->mwisendactive = 0;
11259       return 0;
11260    }
11261 #else
11262    if (mwisend_rpas) {
11263       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
11264    } else {
11265       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11266    }
11267    pvt->mwisendactive = 1;
11268 #endif
11269 
11270    if (pvt->cidspill) {
11271       ast_log(LOG_WARNING, "cidspill already exists when trying to send FSK MWI\n");
11272       ast_free(pvt->cidspill);
11273       pvt->cidspill = NULL;
11274       pvt->cidpos = 0;
11275       pvt->cidlen = 0;
11276    }
11277    pvt->cidspill = ast_calloc(1, MAX_CALLERID_SIZE);
11278    if (!pvt->cidspill) {
11279       pvt->mwisendactive = 0;
11280       return -1;
11281    }
11282    x = DAHDI_FLUSH_BOTH;
11283    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
11284    x = 3000;
11285    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_ONHOOKTRANSFER, &x);
11286 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11287    if (pvt->mwisend_fsk) {
11288 #endif
11289       pvt->cidlen = ast_callerid_vmwi_generate(pvt->cidspill, has_voicemail(pvt), CID_MWI_TYPE_MDMF_FULL,
11290                       AST_LAW(pvt), pvt->cid_name, pvt->cid_num, 0);
11291       pvt->cidpos = 0;
11292 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11293    }
11294 #endif
11295    return 0;
11296 }
11297 
11298 static int mwi_send_process_buffer(struct dahdi_pvt * pvt, int num_read)
11299 {
11300    struct timeval    now;
11301    int         res;
11302 
11303    /* sanity check to catch if this had been interrupted previously
11304    *  i.e. state says there is more to do but there is no spill allocated
11305    */
11306    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current && !pvt->cidspill) {
11307       pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11308    } else if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
11309       /* Normal processing -- Perform mwi send action */
11310       switch ( pvt->mwisend_data.mwisend_current) {
11311       case MWI_SEND_SA:
11312          /* Send the Ring Pulse Signal Alert */
11313          res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &AS_RP_cadence);
11314          if (res) {
11315             ast_log(LOG_WARNING, "Unable to set RP-AS ring cadence: %s\n", strerror(errno));
11316             goto quit;
11317          }
11318          res = dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RING);
11319          pvt->mwisend_data.mwisend_current = MWI_SEND_SA_WAIT;
11320          break;
11321       case MWI_SEND_SA_WAIT:  /* do nothing until I get RINGEROFF event */
11322          break;
11323       case MWI_SEND_PAUSE:  /* Wait between alert and spill - min of 500 mS*/
11324 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11325          if (pvt->mwisend_fsk) {
11326 #endif
11327             gettimeofday(&now, NULL);
11328             if ((int)(now.tv_sec - pvt->mwisend_data.pause.tv_sec) * 1000000 + (int)now.tv_usec - (int)pvt->mwisend_data.pause.tv_usec > 500000) {
11329                pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
11330             }
11331 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
11332          } else { /* support for mwisendtype=nofsk */
11333             pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
11334          }
11335 #endif
11336          break;
11337       case MWI_SEND_SPILL:
11338          /* We read some number of bytes.  Write an equal amount of data */
11339          if(0 < num_read) {
11340             if (num_read > pvt->cidlen - pvt->cidpos)
11341                num_read = pvt->cidlen - pvt->cidpos;
11342             res = write(pvt->subs[SUB_REAL].dfd, pvt->cidspill + pvt->cidpos, num_read);
11343             if (res > 0) {
11344                pvt->cidpos += res;
11345                if (pvt->cidpos >= pvt->cidlen) {
11346                   pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
11347                }
11348             } else {
11349                ast_log(LOG_WARNING, "MWI FSK Send Write failed: %s\n", strerror(errno));
11350                goto quit;
11351             }
11352          }
11353          break;
11354       case MWI_SEND_CLEANUP:
11355          /* For now, do nothing */
11356          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11357          break;
11358       default:
11359          /* Should not get here, punt*/
11360          goto quit;
11361       }
11362    }
11363 
11364    if (MWI_SEND_DONE == pvt->mwisend_data.mwisend_current) {
11365       if (pvt->cidspill) {
11366          ast_free(pvt->cidspill);
11367          pvt->cidspill = NULL;
11368          pvt->cidpos = 0;
11369          pvt->cidlen = 0;
11370       }
11371       pvt->mwisendactive = 0;
11372    }
11373    return 0;
11374 quit:
11375    if (pvt->cidspill) {
11376       ast_free(pvt->cidspill);
11377       pvt->cidspill = NULL;
11378       pvt->cidpos = 0;
11379       pvt->cidlen = 0;
11380    }
11381    pvt->mwisendactive = 0;
11382    return -1;
11383 }
11384 
11385 static int mwi_send_process_event(struct dahdi_pvt * pvt, int event)
11386 {
11387    int handled = 0;
11388 
11389    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
11390       switch (event) {
11391       case DAHDI_EVENT_RINGEROFF:
11392          if(pvt->mwisend_data.mwisend_current == MWI_SEND_SA_WAIT) {
11393             handled = 1;
11394 
11395             if (dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RINGOFF) ) {
11396                ast_log(LOG_WARNING, "Unable to finish RP-AS: %s mwi send aborted\n", strerror(errno));
11397                ast_free(pvt->cidspill);
11398                pvt->cidspill = NULL;
11399                pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11400                pvt->mwisendactive = 0;
11401             } else {
11402                pvt->mwisend_data.mwisend_current = MWI_SEND_PAUSE;
11403                gettimeofday(&pvt->mwisend_data.pause, NULL);
11404             }
11405          }
11406          break;
11407       /* Going off hook, I need to punt this spill */
11408       case DAHDI_EVENT_RINGOFFHOOK:
11409          if (pvt->cidspill) {
11410             ast_free(pvt->cidspill);
11411             pvt->cidspill = NULL;
11412             pvt->cidpos = 0;
11413             pvt->cidlen = 0;
11414          }
11415          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
11416          pvt->mwisendactive = 0;
11417          break;
11418       case DAHDI_EVENT_RINGERON:
11419       case DAHDI_EVENT_HOOKCOMPLETE:
11420          break;
11421       default:
11422          break;
11423       }
11424    }
11425    return handled;
11426 }
11427 
11428 /* destroy a DAHDI channel, identified by its number */
11429 static int dahdi_destroy_channel_bynum(int channel)
11430 {
11431    struct dahdi_pvt *cur;
11432 
11433    ast_mutex_lock(&iflock);
11434    for (cur = iflist; cur; cur = cur->next) {
11435       if (cur->channel == channel) {
11436          int x = DAHDI_FLASH;
11437 
11438          /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
11439          ioctl(cur->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
11440 
11441          destroy_channel(cur, 1);
11442          ast_mutex_unlock(&iflock);
11443          ast_module_unref(ast_module_info->self);
11444          return RESULT_SUCCESS;
11445       }
11446    }
11447    ast_mutex_unlock(&iflock);
11448    return RESULT_FAILURE;
11449 }
11450 
11451 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
11452 {
11453    int res;
11454    pthread_t threadid;
11455    struct ast_channel *chan;
11456 
11457    /* Handle an event on a given channel for the monitor thread. */
11458 
11459    switch (event) {
11460    case DAHDI_EVENT_NONE:
11461    case DAHDI_EVENT_BITSCHANGED:
11462       break;
11463    case DAHDI_EVENT_WINKFLASH:
11464    case DAHDI_EVENT_RINGOFFHOOK:
11465       if (i->inalarm) break;
11466       if (i->radio) break;
11467       /* Got a ring/answer.  What kind of channel are we? */
11468       switch (i->sig) {
11469       case SIG_FXOLS:
11470       case SIG_FXOGS:
11471       case SIG_FXOKS:
11472          res = dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11473          if (res && (errno == EBUSY))
11474             break;
11475 
11476          /* Cancel VMWI spill */
11477          ast_free(i->cidspill);
11478          i->cidspill = NULL;
11479          restore_conference(i);
11480 
11481          if (i->immediate) {
11482             dahdi_enable_ec(i);
11483             /* The channel is immediately up.  Start right away */
11484             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
11485             chan = dahdi_new(i, AST_STATE_RING, 1, SUB_REAL, 0, NULL);
11486             if (!chan) {
11487                ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
11488                res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11489                if (res < 0)
11490                   ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11491             }
11492          } else {
11493             /* Check for callerid, digits, etc */
11494             chan = dahdi_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, NULL);
11495             if (chan) {
11496                if (has_voicemail(i))
11497                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
11498                else
11499                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
11500                if (res < 0)
11501                   ast_log(LOG_WARNING, "Unable to play dialtone on channel %d, do you have defaultzone and loadzone defined?\n", i->channel);
11502                if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11503                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11504                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11505                   if (res < 0)
11506                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11507                   ast_hangup(chan);
11508                }
11509             } else
11510                ast_log(LOG_WARNING, "Unable to create channel\n");
11511          }
11512          break;
11513       case SIG_FXSLS:
11514       case SIG_FXSGS:
11515       case SIG_FXSKS:
11516             i->ringt = i->ringt_base;
11517             /* Fall through */
11518       case SIG_EMWINK:
11519       case SIG_FEATD:
11520       case SIG_FEATDMF:
11521       case SIG_FEATDMF_TA:
11522       case SIG_E911:
11523       case SIG_FGC_CAMA:
11524       case SIG_FGC_CAMAMF:
11525       case SIG_FEATB:
11526       case SIG_EM:
11527       case SIG_EM_E1:
11528       case SIG_SFWINK:
11529       case SIG_SF_FEATD:
11530       case SIG_SF_FEATDMF:
11531       case SIG_SF_FEATB:
11532       case SIG_SF:
11533          /* Check for callerid, digits, etc */
11534          if (i->cid_start == CID_START_POLARITY_IN) {
11535             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11536          } else {
11537             chan = dahdi_new(i, AST_STATE_RING, 0, SUB_REAL, 0, NULL);
11538          }
11539 
11540          if (!chan) {
11541             ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11542          } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11543             ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11544             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11545             if (res < 0) {
11546                ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11547             }
11548             ast_hangup(chan);
11549          }
11550          break;
11551       default:
11552          ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11553          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11554          if (res < 0)
11555             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11556          return NULL;
11557       }
11558       break;
11559    case DAHDI_EVENT_NOALARM:
11560       switch (i->sig) {
11561 #if defined(HAVE_PRI)
11562       case SIG_PRI_LIB_HANDLE_CASES:
11563          ast_mutex_lock(&i->lock);
11564          sig_pri_chan_alarm_notify(i->sig_pvt, 1);
11565          ast_mutex_unlock(&i->lock);
11566          break;
11567 #endif   /* defined(HAVE_PRI) */
11568 #if defined(HAVE_SS7)
11569       case SIG_SS7:
11570          sig_ss7_set_alarm(i->sig_pvt, 0);
11571          break;
11572 #endif   /* defined(HAVE_SS7) */
11573       default:
11574          i->inalarm = 0;
11575          break;
11576       }
11577       handle_clear_alarms(i);
11578       break;
11579    case DAHDI_EVENT_ALARM:
11580       switch (i->sig) {
11581 #if defined(HAVE_PRI)
11582       case SIG_PRI_LIB_HANDLE_CASES:
11583          ast_mutex_lock(&i->lock);
11584          sig_pri_chan_alarm_notify(i->sig_pvt, 0);
11585          ast_mutex_unlock(&i->lock);
11586          break;
11587 #endif   /* defined(HAVE_PRI) */
11588 #if defined(HAVE_SS7)
11589       case SIG_SS7:
11590          sig_ss7_set_alarm(i->sig_pvt, 1);
11591          break;
11592 #endif   /* defined(HAVE_SS7) */
11593       default:
11594          i->inalarm = 1;
11595          break;
11596       }
11597       res = get_alarms(i);
11598       handle_alarms(i, res);
11599       /* fall thru intentionally */
11600    case DAHDI_EVENT_ONHOOK:
11601       if (i->radio)
11602          break;
11603       /* Back on hook.  Hang up. */
11604       switch (i->sig) {
11605       case SIG_FXOLS:
11606       case SIG_FXOGS:
11607       case SIG_FEATD:
11608       case SIG_FEATDMF:
11609       case SIG_FEATDMF_TA:
11610       case SIG_E911:
11611       case SIG_FGC_CAMA:
11612       case SIG_FGC_CAMAMF:
11613       case SIG_FEATB:
11614       case SIG_EM:
11615       case SIG_EM_E1:
11616       case SIG_EMWINK:
11617       case SIG_SF_FEATD:
11618       case SIG_SF_FEATDMF:
11619       case SIG_SF_FEATB:
11620       case SIG_SF:
11621       case SIG_SFWINK:
11622       case SIG_FXSLS:
11623       case SIG_FXSGS:
11624       case SIG_FXSKS:
11625       case SIG_FXOKS:
11626          dahdi_disable_ec(i);
11627          /* Diddle the battery for the zhone */
11628 #ifdef ZHONE_HACK
11629          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11630          usleep(1);
11631 #endif
11632          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11633          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
11634          break;
11635       case SIG_SS7:
11636       case SIG_PRI_LIB_HANDLE_CASES:
11637          dahdi_disable_ec(i);
11638          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11639          break;
11640       default:
11641          ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11642          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11643          return NULL;
11644       }
11645       break;
11646    case DAHDI_EVENT_POLARITY:
11647       switch (i->sig) {
11648       case SIG_FXSLS:
11649       case SIG_FXSKS:
11650       case SIG_FXSGS:
11651          /* We have already got a PR before the channel was
11652             created, but it wasn't handled. We need polarity
11653             to be REV for remote hangup detection to work.
11654             At least in Spain */
11655          if (i->hanguponpolarityswitch)
11656             i->polarity = POLARITY_REV;
11657          if (i->cid_start == CID_START_POLARITY || i->cid_start == CID_START_POLARITY_IN) {
11658             i->polarity = POLARITY_REV;
11659             ast_verb(2, "Starting post polarity "
11660                "CID detection on channel %d\n",
11661                i->channel);
11662             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11663             if (!chan) {
11664                ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11665             } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11666                ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11667                ast_hangup(chan);
11668             }
11669          }
11670          break;
11671       default:
11672          ast_log(LOG_WARNING, "handle_init_event detected "
11673             "polarity reversal on non-FXO (SIG_FXS) "
11674             "interface %d\n", i->channel);
11675       }
11676       break;
11677    case DAHDI_EVENT_REMOVED: /* destroy channel, will actually do so in do_monitor */
11678       ast_log(LOG_NOTICE,
11679             "Got DAHDI_EVENT_REMOVED. Destroying channel %d\n",
11680             i->channel);
11681       return i;
11682    case DAHDI_EVENT_NEONMWI_ACTIVE:
11683       if (i->mwimonitor_neon) {
11684          notify_message(i->mailbox, 1);
11685          ast_log(LOG_NOTICE, "NEON MWI set for channel %d, mailbox %s \n", i->channel, i->mailbox);
11686       }
11687       break;
11688    case DAHDI_EVENT_NEONMWI_INACTIVE:
11689       if (i->mwimonitor_neon) {
11690          notify_message(i->mailbox, 0);
11691          ast_log(LOG_NOTICE, "NEON MWI cleared for channel %d, mailbox %s\n", i->channel, i->mailbox);
11692       }
11693       break;
11694    }
11695    return NULL;
11696 }
11697 
11698 static void *do_monitor(void *data)
11699 {
11700    int count, res, res2, spoint, pollres=0;
11701    struct dahdi_pvt *i;
11702    struct dahdi_pvt *last = NULL;
11703    struct dahdi_pvt *doomed;
11704    time_t thispass = 0, lastpass = 0;
11705    int found;
11706    char buf[1024];
11707    struct pollfd *pfds=NULL;
11708    int lastalloc = -1;
11709    /* This thread monitors all the frame relay interfaces which are not yet in use
11710       (and thus do not have a separate thread) indefinitely */
11711    /* From here on out, we die whenever asked */
11712 #if 0
11713    if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
11714       ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
11715       return NULL;
11716    }
11717    ast_debug(1, "Monitor starting...\n");
11718 #endif
11719    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11720 
11721    for (;;) {
11722       /* Lock the interface list */
11723       ast_mutex_lock(&iflock);
11724       if (!pfds || (lastalloc != ifcount)) {
11725          if (pfds) {
11726             ast_free(pfds);
11727             pfds = NULL;
11728          }
11729          if (ifcount) {
11730             if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
11731                ast_mutex_unlock(&iflock);
11732                return NULL;
11733             }
11734          }
11735          lastalloc = ifcount;
11736       }
11737       /* Build the stuff we're going to poll on, that is the socket of every
11738          dahdi_pvt that does not have an associated owner channel */
11739       count = 0;
11740       for (i = iflist; i; i = i->next) {
11741          ast_mutex_lock(&i->lock);
11742          if (pfds && (i->subs[SUB_REAL].dfd > -1) && i->sig && (!i->radio) && !(i->sig & SIG_MFCR2)) {
11743             if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11744                struct analog_pvt *p = i->sig_pvt;
11745 
11746                if (!p) {
11747                   ast_log(LOG_ERROR, "No sig_pvt?\n");
11748                } else if (!p->owner && !p->subs[SUB_REAL].owner) {
11749                   /* This needs to be watched, as it lacks an owner */
11750                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11751                   pfds[count].events = POLLPRI;
11752                   pfds[count].revents = 0;
11753                   /* Message waiting or r2 channels also get watched for reading */
11754                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk || 
11755                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11756                      pfds[count].events |= POLLIN;
11757                   }
11758                   count++;
11759                }
11760             } else {
11761                if (!i->owner && !i->subs[SUB_REAL].owner && !i->mwimonitoractive ) {
11762                   /* This needs to be watched, as it lacks an owner */
11763                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11764                   pfds[count].events = POLLPRI;
11765                   pfds[count].revents = 0;
11766                   /* If we are monitoring for VMWI or sending CID, we need to
11767                      read from the channel as well */
11768                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk ||
11769                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11770                      pfds[count].events |= POLLIN;
11771                   }
11772                   count++;
11773                }
11774             }
11775          }
11776          ast_mutex_unlock(&i->lock);
11777       }
11778       /* Okay, now that we know what to do, release the interface lock */
11779       ast_mutex_unlock(&iflock);
11780 
11781       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
11782       pthread_testcancel();
11783       /* Wait at least a second for something to happen */
11784       res = poll(pfds, count, 1000);
11785       pthread_testcancel();
11786       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11787 
11788       /* Okay, poll has finished.  Let's see what happened.  */
11789       if (res < 0) {
11790          if ((errno != EAGAIN) && (errno != EINTR))
11791             ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
11792          continue;
11793       }
11794       /* Alright, lock the interface list again, and let's look and see what has
11795          happened */
11796       ast_mutex_lock(&iflock);
11797       found = 0;
11798       spoint = 0;
11799       lastpass = thispass;
11800       thispass = time(NULL);
11801       doomed = NULL;
11802       for (i = iflist;; i = i->next) {
11803          if (doomed) {
11804             int res;
11805             res = dahdi_destroy_channel_bynum(doomed->channel);
11806             if (res != RESULT_SUCCESS) {
11807                ast_log(LOG_WARNING, "Couldn't find channel to destroy, hopefully another destroy operation just happened.\n");
11808             }
11809             doomed = NULL;
11810          }
11811          if (!i) {
11812             break;
11813          }
11814 
11815          if (thispass != lastpass) {
11816             if (!found && ((i == last) || ((i == iflist) && !last))) {
11817                last = i;
11818                if (last) {
11819                   struct analog_pvt *analog_p = last->sig_pvt;
11820                   /* Only allow MWI to be initiated on a quiescent fxs port */
11821                   if (analog_p
11822                      && !last->mwisendactive
11823                      && (last->sig & __DAHDI_SIG_FXO)
11824                      && !analog_p->fxsoffhookstate
11825                      && !last->owner
11826                      && !ast_strlen_zero(last->mailbox)
11827                      && (thispass - analog_p->onhooktime > 3)) {
11828                      res = has_voicemail(last);
11829                      if (analog_p->msgstate != res) {
11830                         /* Set driver resources for signalling VMWI */
11831                         res2 = ioctl(last->subs[SUB_REAL].dfd, DAHDI_VMWI, &res);
11832                         if (res2) {
11833                            /* TODO: This message will ALWAYS be generated on some cards; any way to restrict it to those cards where it is interesting? */
11834                            ast_debug(3, "Unable to control message waiting led on channel %d: %s\n", last->channel, strerror(errno));
11835                         }
11836                         /* If enabled for FSK spill then initiate it */
11837                         if (mwi_send_init(last)) {
11838                            ast_log(LOG_WARNING, "Unable to initiate mwi send sequence on channel %d\n", last->channel);
11839                         }
11840                         analog_p->msgstate = res;
11841                         found ++;
11842                      }
11843                   }
11844                   last = last->next;
11845                }
11846             }
11847          }
11848          if ((i->subs[SUB_REAL].dfd > -1) && i->sig) {
11849             if (i->radio && !i->owner)
11850             {
11851                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11852                if (res)
11853                {
11854                   ast_debug(1, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
11855                   /* Don't hold iflock while handling init events */
11856                   ast_mutex_unlock(&iflock);
11857                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11858                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11859                   else
11860                      doomed = handle_init_event(i, res);
11861                   ast_mutex_lock(&iflock);
11862                }
11863                continue;
11864             }
11865             pollres = ast_fdisset(pfds, i->subs[SUB_REAL].dfd, count, &spoint);
11866             if (pollres & POLLIN) {
11867                if (i->owner || i->subs[SUB_REAL].owner) {
11868 #ifdef HAVE_PRI
11869                   if (!i->pri)
11870 #endif
11871                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].dfd);
11872                   continue;
11873                }
11874                if (!i->mwimonitor_fsk && !i->mwisendactive  && i->cid_start != CID_START_DTMF_NOALERT) {
11875                   ast_log(LOG_WARNING, "Whoa....  I'm not looking for MWI or sending MWI but am reading (%d)...\n", i->subs[SUB_REAL].dfd);
11876                   continue;
11877                }
11878                res = read(i->subs[SUB_REAL].dfd, buf, sizeof(buf));
11879                if (res > 0) {
11880                   if (i->mwimonitor_fsk) {
11881                      if (calc_energy((unsigned char *) buf, res, AST_LAW(i)) > mwilevel) {
11882                         pthread_attr_t attr;
11883                         pthread_t threadid;
11884                         struct mwi_thread_data *mtd;
11885 
11886                         pthread_attr_init(&attr);
11887                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
11888 
11889                         ast_log(LOG_DEBUG, "Maybe some MWI on port %d!\n", i->channel);
11890                         if ((mtd = ast_calloc(1, sizeof(*mtd)))) {
11891                            mtd->pvt = i;
11892                            memcpy(mtd->buf, buf, res);
11893                            mtd->len = res;
11894                            i->mwimonitoractive = 1;
11895                            if (ast_pthread_create_background(&threadid, &attr, mwi_thread, mtd)) {
11896                               ast_log(LOG_WARNING, "Unable to start mwi thread on channel %d\n", i->channel);
11897                               i->mwimonitoractive = 0;
11898                               ast_free(mtd);
11899                            }
11900                         }
11901                      }
11902                   /* If configured to check for a DTMF CID spill that comes without alert (e.g no polarity reversal) */
11903                   } else if (i->cid_start == CID_START_DTMF_NOALERT) {
11904                      int energy;
11905                      struct timeval now;
11906                      /* State machine dtmfcid_holdoff_state allows for the line to settle
11907                       * before checking agin for dtmf energy.  Presently waits for 500 mS before checking again 
11908                      */
11909                      if (1 == i->dtmfcid_holdoff_state) {
11910                         gettimeofday(&i->dtmfcid_delay, NULL);
11911                         i->dtmfcid_holdoff_state = 2;
11912                      } else if (2 == i->dtmfcid_holdoff_state) {
11913                         gettimeofday(&now, NULL);
11914                         if ((int)(now.tv_sec - i->dtmfcid_delay.tv_sec) * 1000000 + (int)now.tv_usec - (int)i->dtmfcid_delay.tv_usec > 500000) {
11915                            i->dtmfcid_holdoff_state = 0;
11916                         }
11917                      } else {
11918                         energy = calc_energy((unsigned char *) buf, res, AST_LAW(i));
11919                         if (!i->mwisendactive && energy > dtmfcid_level) {
11920                            pthread_t threadid;
11921                            struct ast_channel *chan;
11922                            ast_mutex_unlock(&iflock);
11923                            if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11924                               /* just in case this event changes or somehow destroys a channel, set doomed here too */
11925                               doomed = analog_handle_init_event(i->sig_pvt, ANALOG_EVENT_DTMFCID);  
11926                               i->dtmfcid_holdoff_state = 1;
11927                            } else {
11928                               chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11929                               if (!chan) {
11930                                  ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11931                               } else {
11932                                  res = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11933                                  if (res) {
11934                                     ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11935                                     ast_hangup(chan);
11936                                  } else {
11937                                     i->dtmfcid_holdoff_state = 1;
11938                                  }
11939                               }
11940                            }
11941                            ast_mutex_lock(&iflock);
11942                         }
11943                      }
11944                   }
11945                   if (i->mwisendactive) {
11946                      mwi_send_process_buffer(i, res);
11947                   }
11948                } else {
11949                   ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
11950                }
11951             }
11952             if (pollres & POLLPRI) {
11953                if (i->owner || i->subs[SUB_REAL].owner) {
11954 #ifdef HAVE_PRI
11955                   if (!i->pri)
11956 #endif
11957                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d)...\n", i->subs[SUB_REAL].dfd);
11958                   continue;
11959                }
11960                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11961                ast_debug(1, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
11962                /* Don't hold iflock while handling init events */
11963                ast_mutex_unlock(&iflock);
11964                if (0 == i->mwisendactive || 0 == mwi_send_process_event(i, res)) {
11965                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11966                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11967                   else
11968                      doomed = handle_init_event(i, res);
11969                }
11970                ast_mutex_lock(&iflock);
11971             }
11972          }
11973       }
11974       ast_mutex_unlock(&iflock);
11975    }
11976    /* Never reached */
11977    return NULL;
11978 
11979 }
11980 
11981 static int restart_monitor(void)
11982 {
11983    /* If we're supposed to be stopped -- stay stopped */
11984    if (monitor_thread == AST_PTHREADT_STOP)
11985       return 0;
11986    ast_mutex_lock(&monlock);
11987    if (monitor_thread == pthread_self()) {
11988       ast_mutex_unlock(&monlock);
11989       ast_log(LOG_WARNING, "Cannot kill myself\n");
11990       return -1;
11991    }
11992    if (monitor_thread != AST_PTHREADT_NULL) {
11993       /* Wake up the thread */
11994       pthread_kill(monitor_thread, SIGURG);
11995    } else {
11996       /* Start a new monitor */
11997       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
11998          ast_mutex_unlock(&monlock);
11999          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
12000          return -1;
12001       }
12002    }
12003    ast_mutex_unlock(&monlock);
12004    return 0;
12005 }
12006 
12007 #if defined(HAVE_PRI)
12008 static int pri_resolve_span(int *span, int channel, int offset, struct dahdi_spaninfo *si)
12009 {
12010    int x;
12011    int trunkgroup;
12012    /* Get appropriate trunk group if there is one */
12013    trunkgroup = pris[*span].mastertrunkgroup;
12014    if (trunkgroup) {
12015       /* Select a specific trunk group */
12016       for (x = 0; x < NUM_SPANS; x++) {
12017          if (pris[x].pri.trunkgroup == trunkgroup) {
12018             *span = x;
12019             return 0;
12020          }
12021       }
12022       ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
12023       *span = -1;
12024    } else {
12025       if (pris[*span].pri.trunkgroup) {
12026          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);
12027          *span = -1;
12028       } else if (pris[*span].mastertrunkgroup) {
12029          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
12030          *span = -1;
12031       } else {
12032          if (si->totalchans == 31) {
12033             /* E1 */
12034             pris[*span].dchannels[0] = 16 + offset;
12035          } else if (si->totalchans == 24) {
12036             /* T1 or J1 */
12037             pris[*span].dchannels[0] = 24 + offset;
12038          } else if (si->totalchans == 3) {
12039             /* BRI */
12040             pris[*span].dchannels[0] = 3 + offset;
12041          } else {
12042             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);
12043             *span = -1;
12044             return 0;
12045          }
12046          pris[*span].pri.span = *span + 1;
12047       }
12048    }
12049    return 0;
12050 }
12051 #endif   /* defined(HAVE_PRI) */
12052 
12053 #if defined(HAVE_PRI)
12054 static int pri_create_trunkgroup(int trunkgroup, int *channels)
12055 {
12056    struct dahdi_spaninfo si;
12057    struct dahdi_params p;
12058    int fd;
12059    int span;
12060    int ospan=0;
12061    int x,y;
12062    for (x = 0; x < NUM_SPANS; x++) {
12063       if (pris[x].pri.trunkgroup == trunkgroup) {
12064          ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
12065          return -1;
12066       }
12067    }
12068    for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
12069       if (!channels[y])
12070          break;
12071       memset(&si, 0, sizeof(si));
12072       memset(&p, 0, sizeof(p));
12073       fd = open("/dev/dahdi/channel", O_RDWR);
12074       if (fd < 0) {
12075          ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
12076          return -1;
12077       }
12078       x = channels[y];
12079       if (ioctl(fd, DAHDI_SPECIFY, &x)) {
12080          ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
12081          close(fd);
12082          return -1;
12083       }
12084       if (ioctl(fd, DAHDI_GET_PARAMS, &p)) {
12085          ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
12086          return -1;
12087       }
12088       if (ioctl(fd, DAHDI_SPANSTAT, &si)) {
12089          ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d): %s\n", channels[y], p.spanno, strerror(errno));
12090          close(fd);
12091          return -1;
12092       }
12093       span = p.spanno - 1;
12094       if (pris[span].pri.trunkgroup) {
12095          ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].pri.trunkgroup);
12096          close(fd);
12097          return -1;
12098       }
12099       if (pris[span].pri.pvts[0]) {
12100          ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
12101          close(fd);
12102          return -1;
12103       }
12104       if (!y) {
12105          pris[span].pri.trunkgroup = trunkgroup;
12106          ospan = span;
12107       }
12108       pris[ospan].dchannels[y] = channels[y];
12109       pris[span].pri.span = span + 1;
12110       close(fd);
12111    }
12112    return 0;
12113 }
12114 #endif   /* defined(HAVE_PRI) */
12115 
12116 #if defined(HAVE_PRI)
12117 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
12118 {
12119    if (pris[span].mastertrunkgroup) {
12120       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);
12121       return -1;
12122    }
12123    pris[span].mastertrunkgroup = trunkgroup;
12124    pris[span].prilogicalspan = logicalspan;
12125    return 0;
12126 }
12127 #endif   /* defined(HAVE_PRI) */
12128 
12129 #if defined(HAVE_SS7)
12130 static unsigned int parse_pointcode(const char *pcstring)
12131 {
12132    unsigned int code1, code2, code3;
12133    int numvals;
12134 
12135    numvals = sscanf(pcstring, "%30d-%30d-%30d", &code1, &code2, &code3);
12136    if (numvals == 1)
12137       return code1;
12138    if (numvals == 3)
12139       return (code1 << 16) | (code2 << 8) | code3;
12140 
12141    return 0;
12142 }
12143 #endif   /* defined(HAVE_SS7) */
12144 
12145 #if defined(HAVE_SS7)
12146 static struct dahdi_ss7 * ss7_resolve_linkset(int linkset)
12147 {
12148    if ((linkset < 0) || (linkset >= NUM_SPANS))
12149       return NULL;
12150    else
12151       return &linksets[linkset - 1];
12152 }
12153 #endif   /* defined(HAVE_SS7) */
12154 
12155 #ifdef HAVE_OPENR2
12156 static void dahdi_r2_destroy_links(void)
12157 {
12158    int i = 0;
12159    if (!r2links) {
12160       return;
12161    }
12162    for (; i < r2links_count; i++) {
12163       if (r2links[i]->r2master != AST_PTHREADT_NULL) {
12164          pthread_cancel(r2links[i]->r2master);
12165          pthread_join(r2links[i]->r2master, NULL);
12166          openr2_context_delete(r2links[i]->protocol_context);
12167       }
12168       ast_free(r2links[i]);
12169    }
12170    ast_free(r2links);
12171    r2links = NULL;
12172    r2links_count = 0;
12173 }
12174 
12175 #define R2_LINK_CAPACITY 10
12176 static struct dahdi_mfcr2 *dahdi_r2_get_link(void)
12177 {
12178    struct dahdi_mfcr2 *new_r2link = NULL;
12179    struct dahdi_mfcr2 **new_r2links = NULL;
12180    /* this function is called just when starting up and no monitor threads have been launched,
12181       no need to lock monitored_count member */
12182    if (!r2links_count || (r2links[r2links_count - 1]->monitored_count == R2_LINK_CAPACITY)) {
12183       new_r2link = ast_calloc(1, sizeof(**r2links));
12184       if (!new_r2link) {
12185          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
12186          return NULL;
12187       }
12188       new_r2links = ast_realloc(r2links, ((r2links_count + 1) * sizeof(*r2links)));
12189       if (!new_r2links) {
12190          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
12191          ast_free(new_r2link);
12192          return NULL;
12193       }
12194       r2links = new_r2links;
12195       new_r2link->r2master = AST_PTHREADT_NULL;
12196       r2links[r2links_count] = new_r2link;
12197       r2links_count++;
12198       ast_log(LOG_DEBUG, "Created new R2 link!\n");
12199    }
12200    return r2links[r2links_count - 1];
12201 }
12202 
12203 static int dahdi_r2_set_context(struct dahdi_mfcr2 *r2_link, const struct dahdi_chan_conf *conf)
12204 {
12205    char tmplogdir[] = "/tmp";
12206    char logdir[OR2_MAX_PATH];
12207    int threshold = 0;
12208    int snres = 0;
12209    r2_link->protocol_context = openr2_context_new(NULL, &dahdi_r2_event_iface,
12210          &dahdi_r2_transcode_iface, conf->mfcr2.variant, conf->mfcr2.max_ani,
12211          conf->mfcr2.max_dnis);
12212    if (!r2_link->protocol_context) {
12213       return -1;
12214    }
12215    openr2_context_set_log_level(r2_link->protocol_context, conf->mfcr2.loglevel);
12216    openr2_context_set_ani_first(r2_link->protocol_context, conf->mfcr2.get_ani_first);
12217 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
12218    openr2_context_set_skip_category_request(r2_link->protocol_context, conf->mfcr2.skip_category_request);
12219 #endif
12220    openr2_context_set_mf_threshold(r2_link->protocol_context, threshold);
12221    openr2_context_set_mf_back_timeout(r2_link->protocol_context, conf->mfcr2.mfback_timeout);
12222    openr2_context_set_metering_pulse_timeout(r2_link->protocol_context, conf->mfcr2.metering_pulse_timeout);
12223    openr2_context_set_double_answer(r2_link->protocol_context, conf->mfcr2.double_answer);
12224    openr2_context_set_immediate_accept(r2_link->protocol_context, conf->mfcr2.immediate_accept);
12225    if (ast_strlen_zero(conf->mfcr2.logdir)) {
12226       if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
12227          ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
12228       }
12229    } else {
12230       snres = snprintf(logdir, sizeof(logdir), "%s/%s/%s", ast_config_AST_LOG_DIR, "mfcr2", conf->mfcr2.logdir);
12231       if (snres >= sizeof(logdir)) {
12232          ast_log(LOG_ERROR, "MFC/R2 logging directory truncated, using %s\n", tmplogdir);
12233          if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
12234             ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
12235          }
12236       } else {
12237          if (openr2_context_set_log_directory(r2_link->protocol_context, logdir)) {
12238             ast_log(LOG_ERROR, "Failed setting MFC/R2 log directory %s\n", logdir);
12239          }
12240       }
12241    }
12242    if (!ast_strlen_zero(conf->mfcr2.r2proto_file)) {
12243       if (openr2_context_configure_from_advanced_file(r2_link->protocol_context, conf->mfcr2.r2proto_file)) {
12244          ast_log(LOG_ERROR, "Failed to configure r2context from advanced configuration file %s\n", conf->mfcr2.r2proto_file);
12245       }
12246    }
12247    r2_link->monitored_count = 0;
12248    return 0;
12249 }
12250 #endif
12251 
12252 /* converts a DAHDI sigtype to signalling as can be configured from
12253  * chan_dahdi.conf.
12254  * While both have basically the same values, this will later be the
12255  * place to add filters and sanity checks
12256  */
12257 static int sigtype_to_signalling(int sigtype)
12258 {
12259    return sigtype;
12260 }
12261 
12262 /*!
12263  * \internal
12264  * \brief Get file name and channel number from (subdir,number)
12265  *
12266  * \param subdir name of the subdirectory under /dev/dahdi/
12267  * \param channel name of device file under /dev/dahdi/<subdir>/
12268  * \param path buffer to put file name in
12269  * \param pathlen maximal length of path
12270  *
12271  * \retval minor number of dahdi channel.
12272  * \retval -errno on error.
12273  */
12274 static int device2chan(const char *subdir, int channel, char *path, int pathlen)
12275 {
12276    struct stat stbuf;
12277    int      num;
12278 
12279    snprintf(path, pathlen, "/dev/dahdi/%s/%d", subdir, channel);
12280    if (stat(path, &stbuf) < 0) {
12281       ast_log(LOG_ERROR, "stat(%s) failed: %s\n", path, strerror(errno));
12282       return -errno;
12283    }
12284    if (!S_ISCHR(stbuf.st_mode)) {
12285       ast_log(LOG_ERROR, "%s: Not a character device file\n", path);
12286       return -EINVAL;
12287    }
12288    num = minor(stbuf.st_rdev);
12289    ast_log(LOG_DEBUG, "%s -> %d\n", path, num);
12290    return num;
12291 
12292 }
12293 
12294 /*!
12295  * \internal
12296  * \brief Initialize/create a channel interface.
12297  *
12298  * \param channel Channel interface number to initialize/create.
12299  * \param conf Configuration parameters to initialize interface with.
12300  * \param reloading What we are doing now:
12301  * 0 - initial module load,
12302  * 1 - module reload,
12303  * 2 - module restart
12304  *
12305  * \retval Interface-pointer initialized/created
12306  * \retval NULL if error
12307  */
12308 static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf, int reloading)
12309 {
12310    /* Make a dahdi_pvt structure for this interface */
12311    struct dahdi_pvt *tmp;/*!< Current channel structure initializing */
12312    char fn[80];
12313    struct dahdi_bufferinfo bi;
12314 
12315    int res;
12316 #if defined(HAVE_PRI)
12317    int span = 0;
12318 #endif   /* defined(HAVE_PRI) */
12319    int here = 0;/*!< TRUE if the channel interface already exists. */
12320    int x;
12321    struct analog_pvt *analog_p = NULL;
12322    struct dahdi_params p;
12323 #if defined(HAVE_PRI)
12324    struct dahdi_spaninfo si;
12325    struct sig_pri_chan *pri_chan = NULL;
12326 #endif   /* defined(HAVE_PRI) */
12327 #if defined(HAVE_SS7)
12328    struct sig_ss7_chan *ss7_chan = NULL;
12329 #endif   /* defined(HAVE_SS7) */
12330 
12331    /* Search channel interface list to see if it already exists. */
12332    for (tmp = iflist; tmp; tmp = tmp->next) {
12333       if (!tmp->destroy) {
12334          if (tmp->channel == channel) {
12335             /* The channel interface already exists. */
12336             here = 1;
12337             break;
12338          }
12339          if (tmp->channel > channel) {
12340             /* No way it can be in the sorted list. */
12341             tmp = NULL;
12342             break;
12343          }
12344       }
12345    }
12346 
12347    if (!here && reloading != 1) {
12348       tmp = ast_calloc(1, sizeof(*tmp));
12349       if (!tmp) {
12350          return NULL;
12351       }
12352       tmp->cc_params = ast_cc_config_params_init();
12353       if (!tmp->cc_params) {
12354          ast_free(tmp);
12355          return NULL;
12356       }
12357       ast_mutex_init(&tmp->lock);
12358       ifcount++;
12359       for (x = 0; x < 3; x++)
12360          tmp->subs[x].dfd = -1;
12361       tmp->channel = channel;
12362       tmp->priindication_oob = conf->chan.priindication_oob;
12363    }
12364 
12365    if (tmp) {
12366       int chan_sig = conf->chan.sig;
12367 
12368       /* If there are variables in tmp before it is updated to match the new config, clear them */
12369       if (reloading && tmp->vars) {
12370          ast_variables_destroy(tmp->vars);
12371          tmp->vars = NULL;
12372       }
12373 
12374 
12375       if (!here) {
12376          /* Can only get here if this is a new channel interface being created. */
12377          if ((channel != CHAN_PSEUDO)) {
12378             int count = 0;
12379 
12380             snprintf(fn, sizeof(fn), "%d", channel);
12381             /* Open non-blocking */
12382             tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
12383             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 */
12384                usleep(1);
12385                tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
12386                count++;
12387             }
12388             /* Allocate a DAHDI structure */
12389             if (tmp->subs[SUB_REAL].dfd < 0) {
12390                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);
12391                destroy_dahdi_pvt(tmp);
12392                return NULL;
12393             }
12394             memset(&p, 0, sizeof(p));
12395             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12396             if (res < 0) {
12397                ast_log(LOG_ERROR, "Unable to get parameters: %s\n", strerror(errno));
12398                destroy_dahdi_pvt(tmp);
12399                return NULL;
12400             }
12401             if (conf->is_sig_auto)
12402                chan_sig = sigtype_to_signalling(p.sigtype);
12403             if (p.sigtype != (chan_sig & 0x3ffff)) {
12404                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));
12405                destroy_dahdi_pvt(tmp);
12406                return NULL;
12407             }
12408             tmp->law_default = p.curlaw;
12409             tmp->law = p.curlaw;
12410             tmp->span = p.spanno;
12411 #if defined(HAVE_PRI)
12412             span = p.spanno - 1;
12413 #endif   /* defined(HAVE_PRI) */
12414          } else {
12415             chan_sig = 0;
12416          }
12417          tmp->sig = chan_sig;
12418          tmp->outsigmod = conf->chan.outsigmod;
12419 
12420          if (analog_lib_handles(chan_sig, tmp->radio, tmp->oprmode)) {
12421             analog_p = analog_new(dahdisig_to_analogsig(chan_sig), &dahdi_analog_callbacks, tmp);
12422             if (!analog_p) {
12423                destroy_dahdi_pvt(tmp);
12424                return NULL;
12425             }
12426             tmp->sig_pvt = analog_p;
12427          }
12428 #if defined(HAVE_SS7)
12429          if (chan_sig == SIG_SS7) {
12430             struct dahdi_ss7 *ss7;
12431             int clear = 0;
12432 
12433             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &clear)) {
12434                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
12435                destroy_dahdi_pvt(tmp);
12436                return NULL;
12437             }
12438 
12439             ss7 = ss7_resolve_linkset(cur_linkset);
12440             if (!ss7) {
12441                ast_log(LOG_ERROR, "Unable to find linkset %d\n", cur_linkset);
12442                destroy_dahdi_pvt(tmp);
12443                return NULL;
12444             }
12445             ss7->ss7.span = cur_linkset;
12446             if (cur_cicbeginswith < 0) {
12447                ast_log(LOG_ERROR, "Need to set cicbeginswith for the channels!\n");
12448                destroy_dahdi_pvt(tmp);
12449                return NULL;
12450             }
12451             ss7_chan = sig_ss7_chan_new(tmp, &dahdi_ss7_callbacks, &ss7->ss7);
12452             if (!ss7_chan) {
12453                destroy_dahdi_pvt(tmp);
12454                return NULL;
12455             }
12456             tmp->sig_pvt = ss7_chan;
12457             tmp->ss7 = &ss7->ss7;
12458 
12459             ss7_chan->channel = tmp->channel;
12460             ss7_chan->cic = cur_cicbeginswith++;
12461 
12462             /* DB: Add CIC's DPC information */
12463             ss7_chan->dpc = cur_defaultdpc;
12464 
12465             ss7->ss7.pvts[ss7->ss7.numchans++] = ss7_chan;
12466 
12467             ast_copy_string(ss7->ss7.internationalprefix, conf->ss7.ss7.internationalprefix, sizeof(ss7->ss7.internationalprefix));
12468             ast_copy_string(ss7->ss7.nationalprefix, conf->ss7.ss7.nationalprefix, sizeof(ss7->ss7.nationalprefix));
12469             ast_copy_string(ss7->ss7.subscriberprefix, conf->ss7.ss7.subscriberprefix, sizeof(ss7->ss7.subscriberprefix));
12470             ast_copy_string(ss7->ss7.unknownprefix, conf->ss7.ss7.unknownprefix, sizeof(ss7->ss7.unknownprefix));
12471 
12472             ss7->ss7.called_nai = conf->ss7.ss7.called_nai;
12473             ss7->ss7.calling_nai = conf->ss7.ss7.calling_nai;
12474          }
12475 #endif   /* defined(HAVE_SS7) */
12476 #ifdef HAVE_OPENR2
12477          if (chan_sig == SIG_MFCR2) {
12478             struct dahdi_mfcr2 *r2_link;
12479             r2_link = dahdi_r2_get_link();
12480             if (!r2_link) {
12481                ast_log(LOG_WARNING, "Cannot get another R2 DAHDI context!\n");
12482                destroy_dahdi_pvt(tmp);
12483                return NULL;
12484             }
12485             if (!r2_link->protocol_context && dahdi_r2_set_context(r2_link, conf)) {
12486                ast_log(LOG_ERROR, "Cannot create OpenR2 protocol context.\n");
12487                destroy_dahdi_pvt(tmp);
12488                return NULL;
12489             }
12490             if (r2_link->numchans == ARRAY_LEN(r2_link->pvts)) {
12491                ast_log(LOG_ERROR, "Cannot add more channels to this link!\n");
12492                destroy_dahdi_pvt(tmp);
12493                return NULL;
12494             }
12495             r2_link->pvts[r2_link->numchans++] = tmp;
12496             tmp->r2chan = openr2_chan_new_from_fd(r2_link->protocol_context,
12497                                         tmp->subs[SUB_REAL].dfd,
12498                                         NULL, NULL);
12499             if (!tmp->r2chan) {
12500                openr2_liberr_t err = openr2_context_get_last_error(r2_link->protocol_context);
12501                ast_log(LOG_ERROR, "Cannot create OpenR2 channel: %s\n", openr2_context_error_string(err));
12502                destroy_dahdi_pvt(tmp);
12503                return NULL;
12504             }
12505             tmp->mfcr2 = r2_link;
12506             if (conf->mfcr2.call_files) {
12507                openr2_chan_enable_call_files(tmp->r2chan);
12508             }
12509             openr2_chan_set_client_data(tmp->r2chan, tmp);
12510             /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
12511             openr2_chan_set_logging_func(tmp->r2chan, (openr2_logging_func_t)dahdi_r2_on_chan_log);
12512             openr2_chan_set_log_level(tmp->r2chan, conf->mfcr2.loglevel);
12513             tmp->mfcr2_category = conf->mfcr2.category;
12514             tmp->mfcr2_charge_calls = conf->mfcr2.charge_calls;
12515             tmp->mfcr2_allow_collect_calls = conf->mfcr2.allow_collect_calls;
12516             tmp->mfcr2_forced_release = conf->mfcr2.forced_release;
12517             tmp->mfcr2_accept_on_offer = conf->mfcr2.accept_on_offer;
12518             tmp->mfcr2call = 0;
12519             tmp->mfcr2_dnis_index = 0;
12520             tmp->mfcr2_ani_index = 0;
12521             r2_link->monitored_count++;
12522          }
12523 #endif
12524 #ifdef HAVE_PRI
12525          if (dahdi_sig_pri_lib_handles(chan_sig)) {
12526             int offset;
12527             int matchesdchan;
12528             int x,y;
12529             int myswitchtype = 0;
12530 
12531             offset = 0;
12532             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &offset)) {
12533                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
12534                destroy_dahdi_pvt(tmp);
12535                return NULL;
12536             }
12537             if (span >= NUM_SPANS) {
12538                ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
12539                destroy_dahdi_pvt(tmp);
12540                return NULL;
12541             } else {
12542                si.spanno = 0;
12543                if (ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SPANSTAT,&si) == -1) {
12544                   ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
12545                   destroy_dahdi_pvt(tmp);
12546                   return NULL;
12547                }
12548                /* Store the logical span first based upon the real span */
12549                tmp->logicalspan = pris[span].prilogicalspan;
12550                pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
12551                if (span < 0) {
12552                   ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
12553                   destroy_dahdi_pvt(tmp);
12554                   return NULL;
12555                }
12556                myswitchtype = conf->pri.pri.switchtype;
12557                /* Make sure this isn't a d-channel */
12558                matchesdchan=0;
12559                for (x = 0; x < NUM_SPANS; x++) {
12560                   for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
12561                      if (pris[x].dchannels[y] == tmp->channel) {
12562                         matchesdchan = 1;
12563                         break;
12564                      }
12565                   }
12566                }
12567                if (!matchesdchan) {
12568                   if (pris[span].pri.nodetype && (pris[span].pri.nodetype != conf->pri.pri.nodetype)) {
12569                      ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].pri.nodetype));
12570                      destroy_dahdi_pvt(tmp);
12571                      return NULL;
12572                   }
12573                   if (pris[span].pri.switchtype && (pris[span].pri.switchtype != myswitchtype)) {
12574                      ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].pri.switchtype));
12575                      destroy_dahdi_pvt(tmp);
12576                      return NULL;
12577                   }
12578                   if ((pris[span].pri.dialplan) && (pris[span].pri.dialplan != conf->pri.pri.dialplan)) {
12579                      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));
12580                      destroy_dahdi_pvt(tmp);
12581                      return NULL;
12582                   }
12583                   if (!ast_strlen_zero(pris[span].pri.idledial) && strcmp(pris[span].pri.idledial, conf->pri.pri.idledial)) {
12584                      ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf->pri.pri.idledial);
12585                      destroy_dahdi_pvt(tmp);
12586                      return NULL;
12587                   }
12588                   if (!ast_strlen_zero(pris[span].pri.idleext) && strcmp(pris[span].pri.idleext, conf->pri.pri.idleext)) {
12589                      ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf->pri.pri.idleext);
12590                      destroy_dahdi_pvt(tmp);
12591                      return NULL;
12592                   }
12593                   if (pris[span].pri.minunused && (pris[span].pri.minunused != conf->pri.pri.minunused)) {
12594                      ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf->pri.pri.minunused);
12595                      destroy_dahdi_pvt(tmp);
12596                      return NULL;
12597                   }
12598                   if (pris[span].pri.minidle && (pris[span].pri.minidle != conf->pri.pri.minidle)) {
12599                      ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf->pri.pri.minidle);
12600                      destroy_dahdi_pvt(tmp);
12601                      return NULL;
12602                   }
12603                   if (pris[span].pri.numchans >= ARRAY_LEN(pris[span].pri.pvts)) {
12604                      ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
12605                         pris[span].pri.trunkgroup);
12606                      destroy_dahdi_pvt(tmp);
12607                      return NULL;
12608                   }
12609 
12610                   ast_debug(4, "Adding callbacks %p to chan %d\n", &dahdi_pri_callbacks, tmp->channel);
12611                   pri_chan = sig_pri_chan_new(tmp, &dahdi_pri_callbacks, &pris[span].pri, tmp->logicalspan, p.chanpos, pris[span].mastertrunkgroup);
12612                   if (!pri_chan) {
12613                      destroy_dahdi_pvt(tmp);
12614                      return NULL;
12615                   }
12616                   tmp->sig_pvt = pri_chan;
12617                   tmp->pri = &pris[span].pri;
12618 
12619                   tmp->priexclusive = conf->chan.priexclusive;
12620 
12621                   if (!tmp->pri->cc_params) {
12622                      tmp->pri->cc_params = ast_cc_config_params_init();
12623                      if (!tmp->pri->cc_params) {
12624                         destroy_dahdi_pvt(tmp);
12625                         return NULL;
12626                      }
12627                   }
12628                   ast_cc_copy_config_params(tmp->pri->cc_params,
12629                      conf->chan.cc_params);
12630 
12631                   pris[span].pri.sig = chan_sig;
12632                   pris[span].pri.nodetype = conf->pri.pri.nodetype;
12633                   pris[span].pri.switchtype = myswitchtype;
12634                   pris[span].pri.nsf = conf->pri.pri.nsf;
12635                   pris[span].pri.dialplan = conf->pri.pri.dialplan;
12636                   pris[span].pri.localdialplan = conf->pri.pri.localdialplan;
12637                   pris[span].pri.pvts[pris[span].pri.numchans++] = tmp->sig_pvt;
12638                   pris[span].pri.minunused = conf->pri.pri.minunused;
12639                   pris[span].pri.minidle = conf->pri.pri.minidle;
12640                   pris[span].pri.overlapdial = conf->pri.pri.overlapdial;
12641                   pris[span].pri.qsigchannelmapping = conf->pri.pri.qsigchannelmapping;
12642                   pris[span].pri.discardremoteholdretrieval = conf->pri.pri.discardremoteholdretrieval;
12643 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12644                   pris[span].pri.enable_service_message_support = conf->pri.pri.enable_service_message_support;
12645 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
12646 #ifdef HAVE_PRI_INBANDDISCONNECT
12647                   pris[span].pri.inbanddisconnect = conf->pri.pri.inbanddisconnect;
12648 #endif
12649 #if defined(HAVE_PRI_CALL_HOLD)
12650                   pris[span].pri.hold_disconnect_transfer =
12651                      conf->pri.pri.hold_disconnect_transfer;
12652 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
12653 #if defined(HAVE_PRI_CCSS)
12654                   pris[span].pri.cc_ptmp_recall_mode =
12655                      conf->pri.pri.cc_ptmp_recall_mode;
12656                   pris[span].pri.cc_qsig_signaling_link_req =
12657                      conf->pri.pri.cc_qsig_signaling_link_req;
12658                   pris[span].pri.cc_qsig_signaling_link_rsp =
12659                      conf->pri.pri.cc_qsig_signaling_link_rsp;
12660 #endif   /* defined(HAVE_PRI_CCSS) */
12661 #if defined(HAVE_PRI_CALL_WAITING)
12662                   pris[span].pri.max_call_waiting_calls =
12663                      conf->pri.pri.max_call_waiting_calls;
12664                   pris[span].pri.allow_call_waiting_calls =
12665                      conf->pri.pri.allow_call_waiting_calls;
12666 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12667                   pris[span].pri.transfer = conf->chan.transfer;
12668                   pris[span].pri.facilityenable = conf->pri.pri.facilityenable;
12669 #if defined(HAVE_PRI_L2_PERSISTENCE)
12670                   pris[span].pri.l2_persistence = conf->pri.pri.l2_persistence;
12671 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
12672 #if defined(HAVE_PRI_AOC_EVENTS)
12673                   pris[span].pri.aoc_passthrough_flag = conf->pri.pri.aoc_passthrough_flag;
12674                   pris[span].pri.aoce_delayhangup = conf->pri.pri.aoce_delayhangup;
12675 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
12676                   if (chan_sig == SIG_BRI_PTMP) {
12677                      pris[span].pri.layer1_ignored = conf->pri.pri.layer1_ignored;
12678                   } else {
12679                      /* Option does not apply to this line type. */
12680                      pris[span].pri.layer1_ignored = 0;
12681                   }
12682                   pris[span].pri.append_msn_to_user_tag = conf->pri.pri.append_msn_to_user_tag;
12683                   ast_copy_string(pris[span].pri.initial_user_tag, conf->chan.cid_tag, sizeof(pris[span].pri.initial_user_tag));
12684                   ast_copy_string(pris[span].pri.msn_list, conf->pri.pri.msn_list, sizeof(pris[span].pri.msn_list));
12685 #if defined(HAVE_PRI_MWI)
12686                   ast_copy_string(pris[span].pri.mwi_mailboxes,
12687                      conf->pri.pri.mwi_mailboxes,
12688                      sizeof(pris[span].pri.mwi_mailboxes));
12689 #endif   /* defined(HAVE_PRI_MWI) */
12690                   ast_copy_string(pris[span].pri.idledial, conf->pri.pri.idledial, sizeof(pris[span].pri.idledial));
12691                   ast_copy_string(pris[span].pri.idleext, conf->pri.pri.idleext, sizeof(pris[span].pri.idleext));
12692                   ast_copy_string(pris[span].pri.internationalprefix, conf->pri.pri.internationalprefix, sizeof(pris[span].pri.internationalprefix));
12693                   ast_copy_string(pris[span].pri.nationalprefix, conf->pri.pri.nationalprefix, sizeof(pris[span].pri.nationalprefix));
12694                   ast_copy_string(pris[span].pri.localprefix, conf->pri.pri.localprefix, sizeof(pris[span].pri.localprefix));
12695                   ast_copy_string(pris[span].pri.privateprefix, conf->pri.pri.privateprefix, sizeof(pris[span].pri.privateprefix));
12696                   ast_copy_string(pris[span].pri.unknownprefix, conf->pri.pri.unknownprefix, sizeof(pris[span].pri.unknownprefix));
12697                   pris[span].pri.resetinterval = conf->pri.pri.resetinterval;
12698 
12699                   for (x = 0; x < PRI_MAX_TIMERS; x++) {
12700                      pris[span].pri.pritimers[x] = conf->pri.pri.pritimers[x];
12701                   }
12702 
12703 #if defined(HAVE_PRI_CALL_WAITING)
12704                   /* Channel initial config parameters. */
12705                   pris[span].pri.ch_cfg.stripmsd = conf->chan.stripmsd;
12706                   pris[span].pri.ch_cfg.hidecallerid = conf->chan.hidecallerid;
12707                   pris[span].pri.ch_cfg.hidecalleridname = conf->chan.hidecalleridname;
12708                   pris[span].pri.ch_cfg.immediate = conf->chan.immediate;
12709                   pris[span].pri.ch_cfg.priexclusive = conf->chan.priexclusive;
12710                   pris[span].pri.ch_cfg.priindication_oob = conf->chan.priindication_oob;
12711                   pris[span].pri.ch_cfg.use_callerid = conf->chan.use_callerid;
12712                   pris[span].pri.ch_cfg.use_callingpres = conf->chan.use_callingpres;
12713                   ast_copy_string(pris[span].pri.ch_cfg.context, conf->chan.context, sizeof(pris[span].pri.ch_cfg.context));
12714                   ast_copy_string(pris[span].pri.ch_cfg.mohinterpret, conf->chan.mohinterpret, sizeof(pris[span].pri.ch_cfg.mohinterpret));
12715 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12716                } else {
12717                   ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", p.chanpos);
12718                   destroy_dahdi_pvt(tmp);
12719                   return NULL;
12720                }
12721             }
12722          }
12723 #endif
12724       } else {
12725          /* already exists in interface list */
12726          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));
12727          chan_sig = tmp->sig;
12728          if (tmp->subs[SUB_REAL].dfd > -1) {
12729             memset(&p, 0, sizeof(p));
12730             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12731          }
12732       }
12733       /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
12734       switch (chan_sig) {
12735       case SIG_FXSKS:
12736       case SIG_FXSLS:
12737       case SIG_EM:
12738       case SIG_EM_E1:
12739       case SIG_EMWINK:
12740       case SIG_FEATD:
12741       case SIG_FEATDMF:
12742       case SIG_FEATDMF_TA:
12743       case SIG_FEATB:
12744       case SIG_E911:
12745       case SIG_SF:
12746       case SIG_SFWINK:
12747       case SIG_FGC_CAMA:
12748       case SIG_FGC_CAMAMF:
12749       case SIG_SF_FEATD:
12750       case SIG_SF_FEATDMF:
12751       case SIG_SF_FEATB:
12752          p.starttime = 250;
12753          break;
12754       }
12755 
12756       if (tmp->radio) {
12757          /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
12758          p.channo = channel;
12759          p.rxwinktime = 1;
12760          p.rxflashtime = 1;
12761          p.starttime = 1;
12762          p.debouncetime = 5;
12763       } else {
12764          p.channo = channel;
12765          /* Override timing settings based on config file */
12766          if (conf->timing.prewinktime >= 0)
12767             p.prewinktime = conf->timing.prewinktime;
12768          if (conf->timing.preflashtime >= 0)
12769             p.preflashtime = conf->timing.preflashtime;
12770          if (conf->timing.winktime >= 0)
12771             p.winktime = conf->timing.winktime;
12772          if (conf->timing.flashtime >= 0)
12773             p.flashtime = conf->timing.flashtime;
12774          if (conf->timing.starttime >= 0)
12775             p.starttime = conf->timing.starttime;
12776          if (conf->timing.rxwinktime >= 0)
12777             p.rxwinktime = conf->timing.rxwinktime;
12778          if (conf->timing.rxflashtime >= 0)
12779             p.rxflashtime = conf->timing.rxflashtime;
12780          if (conf->timing.debouncetime >= 0)
12781             p.debouncetime = conf->timing.debouncetime;
12782       }
12783 
12784       /* don't set parms on a pseudo-channel */
12785       if (tmp->subs[SUB_REAL].dfd >= 0)
12786       {
12787          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_PARAMS, &p);
12788          if (res < 0) {
12789             ast_log(LOG_ERROR, "Unable to set parameters: %s\n", strerror(errno));
12790             destroy_dahdi_pvt(tmp);
12791             return NULL;
12792          }
12793       }
12794 #if 1
12795       if (!here && (tmp->subs[SUB_REAL].dfd > -1)) {
12796          memset(&bi, 0, sizeof(bi));
12797          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
12798          if (!res) {
12799             bi.txbufpolicy = conf->chan.buf_policy;
12800             bi.rxbufpolicy = conf->chan.buf_policy;
12801             bi.numbufs = conf->chan.buf_no;
12802             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
12803             if (res < 0) {
12804                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", channel, strerror(errno));
12805             }
12806          } else {
12807             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", channel, strerror(errno));
12808          }
12809          tmp->buf_policy = conf->chan.buf_policy;
12810          tmp->buf_no = conf->chan.buf_no;
12811          tmp->usefaxbuffers = conf->chan.usefaxbuffers;
12812          tmp->faxbuf_policy = conf->chan.faxbuf_policy;
12813          tmp->faxbuf_no = conf->chan.faxbuf_no;
12814          /* This is not as gnarly as it may first appear.  If the ioctl above failed, we'd be setting
12815           * tmp->bufsize to zero which would cause subsequent faxbuffer-related ioctl calls to fail.
12816           * The reason the ioctl call above failed should to be determined before worrying about the
12817           * faxbuffer-related ioctl calls */
12818          tmp->bufsize = bi.bufsize;
12819       }
12820 #endif
12821       tmp->immediate = conf->chan.immediate;
12822       tmp->transfertobusy = conf->chan.transfertobusy;
12823       if (chan_sig & __DAHDI_SIG_FXS) {
12824          tmp->mwimonitor_fsk = conf->chan.mwimonitor_fsk;
12825          tmp->mwimonitor_neon = conf->chan.mwimonitor_neon;
12826          tmp->mwimonitor_rpas = conf->chan.mwimonitor_rpas;
12827       }
12828       tmp->ringt_base = ringt_base;
12829       tmp->firstradio = 0;
12830       if ((chan_sig == SIG_FXOKS) || (chan_sig == SIG_FXOLS) || (chan_sig == SIG_FXOGS))
12831          tmp->permcallwaiting = conf->chan.callwaiting;
12832       else
12833          tmp->permcallwaiting = 0;
12834       /* Flag to destroy the channel must be cleared on new mkif.  Part of changes for reload to work */
12835       tmp->destroy = 0;
12836       tmp->drings = conf->chan.drings;
12837 
12838       /* 10 is a nice default. */
12839       if (tmp->drings.ringnum[0].range == 0)
12840          tmp->drings.ringnum[0].range = 10;
12841       if (tmp->drings.ringnum[1].range == 0)
12842          tmp->drings.ringnum[1].range = 10;
12843       if (tmp->drings.ringnum[2].range == 0)
12844          tmp->drings.ringnum[2].range = 10;
12845 
12846       tmp->usedistinctiveringdetection = usedistinctiveringdetection;
12847       tmp->callwaitingcallerid = conf->chan.callwaitingcallerid;
12848       tmp->threewaycalling = conf->chan.threewaycalling;
12849       tmp->adsi = conf->chan.adsi;
12850       tmp->use_smdi = conf->chan.use_smdi;
12851       tmp->permhidecallerid = conf->chan.hidecallerid;
12852       tmp->hidecalleridname = conf->chan.hidecalleridname;
12853       tmp->callreturn = conf->chan.callreturn;
12854       tmp->echocancel = conf->chan.echocancel;
12855       tmp->echotraining = conf->chan.echotraining;
12856       tmp->pulse = conf->chan.pulse;
12857       if (tmp->echocancel.head.tap_length) {
12858          tmp->echocanbridged = conf->chan.echocanbridged;
12859       } else {
12860          if (conf->chan.echocanbridged)
12861             ast_log(LOG_NOTICE, "echocancelwhenbridged requires echocancel to be enabled; ignoring\n");
12862          tmp->echocanbridged = 0;
12863       }
12864       tmp->busydetect = conf->chan.busydetect;
12865       tmp->busycount = conf->chan.busycount;
12866       tmp->busy_tonelength = conf->chan.busy_tonelength;
12867       tmp->busy_quietlength = conf->chan.busy_quietlength;
12868       tmp->callprogress = conf->chan.callprogress;
12869       tmp->waitfordialtone = conf->chan.waitfordialtone;
12870       tmp->cancallforward = conf->chan.cancallforward;
12871       tmp->dtmfrelax = conf->chan.dtmfrelax;
12872       tmp->callwaiting = tmp->permcallwaiting;
12873       tmp->hidecallerid = tmp->permhidecallerid;
12874       tmp->channel = channel;
12875       tmp->stripmsd = conf->chan.stripmsd;
12876       tmp->use_callerid = conf->chan.use_callerid;
12877       tmp->cid_signalling = conf->chan.cid_signalling;
12878       tmp->cid_start = conf->chan.cid_start;
12879       tmp->dahditrcallerid = conf->chan.dahditrcallerid;
12880       tmp->restrictcid = conf->chan.restrictcid;
12881       tmp->use_callingpres = conf->chan.use_callingpres;
12882       if (tmp->usedistinctiveringdetection) {
12883          if (!tmp->use_callerid) {
12884             ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
12885             tmp->use_callerid = 1;
12886          }
12887       }
12888 
12889       if (tmp->cid_signalling == CID_SIG_SMDI) {
12890          if (!tmp->use_smdi) {
12891             ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
12892             tmp->use_smdi = 1;
12893          }
12894       }
12895       if (tmp->use_smdi) {
12896          tmp->smdi_iface = ast_smdi_interface_find(conf->smdi_port);
12897          if (!(tmp->smdi_iface)) {
12898             ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
12899             tmp->use_smdi = 0;
12900          }
12901       }
12902 
12903       ast_copy_string(tmp->accountcode, conf->chan.accountcode, sizeof(tmp->accountcode));
12904       tmp->amaflags = conf->chan.amaflags;
12905       if (!here) {
12906          tmp->confno = -1;
12907          tmp->propconfno = -1;
12908       }
12909       tmp->canpark = conf->chan.canpark;
12910       tmp->transfer = conf->chan.transfer;
12911       ast_copy_string(tmp->defcontext,conf->chan.context,sizeof(tmp->defcontext));
12912       ast_copy_string(tmp->language, conf->chan.language, sizeof(tmp->language));
12913       ast_copy_string(tmp->mohinterpret, conf->chan.mohinterpret, sizeof(tmp->mohinterpret));
12914       ast_copy_string(tmp->mohsuggest, conf->chan.mohsuggest, sizeof(tmp->mohsuggest));
12915       ast_copy_string(tmp->context, conf->chan.context, sizeof(tmp->context));
12916       ast_copy_string(tmp->parkinglot, conf->chan.parkinglot, sizeof(tmp->parkinglot));
12917       tmp->cid_ton = 0;
12918       if (analog_lib_handles(tmp->sig, tmp->radio, tmp->oprmode)) {
12919          ast_copy_string(tmp->cid_num, conf->chan.cid_num, sizeof(tmp->cid_num));
12920          ast_copy_string(tmp->cid_name, conf->chan.cid_name, sizeof(tmp->cid_name));
12921       } else {
12922          tmp->cid_num[0] = '\0';
12923          tmp->cid_name[0] = '\0';
12924       }
12925 #if defined(HAVE_PRI)
12926       if (dahdi_sig_pri_lib_handles(tmp->sig)) {
12927          tmp->cid_tag[0] = '\0';
12928       } else
12929 #endif   /* defined(HAVE_PRI) */
12930       {
12931          ast_copy_string(tmp->cid_tag, conf->chan.cid_tag, sizeof(tmp->cid_tag));
12932       }
12933       tmp->cid_subaddr[0] = '\0';
12934       ast_copy_string(tmp->mailbox, conf->chan.mailbox, sizeof(tmp->mailbox));
12935       if (channel != CHAN_PSEUDO && !ast_strlen_zero(tmp->mailbox)) {
12936          char *mailbox, *context;
12937          mailbox = context = ast_strdupa(tmp->mailbox);
12938          strsep(&context, "@");
12939          if (ast_strlen_zero(context))
12940             context = "default";
12941          tmp->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "Dahdi MWI subscription", NULL,
12942             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12943             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12944             AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
12945             AST_EVENT_IE_END);
12946       }
12947 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
12948       tmp->mwisend_setting = conf->chan.mwisend_setting;
12949       tmp->mwisend_fsk  = conf->chan.mwisend_fsk;
12950       tmp->mwisend_rpas = conf->chan.mwisend_rpas;
12951 #endif
12952 
12953       tmp->group = conf->chan.group;
12954       tmp->callgroup = conf->chan.callgroup;
12955       tmp->pickupgroup= conf->chan.pickupgroup;
12956       if (conf->chan.vars) {
12957          struct ast_variable *v, *tmpvar;
12958                    for (v = conf->chan.vars ; v ; v = v->next) {
12959                          if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
12960                                   tmpvar->next = tmp->vars;
12961                                    tmp->vars = tmpvar;
12962                            }
12963                   }
12964       }
12965       tmp->cid_rxgain = conf->chan.cid_rxgain;
12966       tmp->rxgain = conf->chan.rxgain;
12967       tmp->txgain = conf->chan.txgain;
12968       tmp->txdrc = conf->chan.txdrc;
12969       tmp->rxdrc = conf->chan.rxdrc;
12970       tmp->tonezone = conf->chan.tonezone;
12971       if (tmp->subs[SUB_REAL].dfd > -1) {
12972          set_actual_gain(tmp->subs[SUB_REAL].dfd, tmp->rxgain, tmp->txgain, tmp->rxdrc, tmp->txdrc, tmp->law);
12973          if (tmp->dsp)
12974             ast_dsp_set_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
12975          update_conf(tmp);
12976          if (!here) {
12977             switch (chan_sig) {
12978             case SIG_PRI_LIB_HANDLE_CASES:
12979             case SIG_SS7:
12980             case SIG_MFCR2:
12981                break;
12982             default:
12983                /* Hang it up to be sure it's good */
12984                dahdi_set_hook(tmp->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
12985                break;
12986             }
12987          }
12988          ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SETTONEZONE,&tmp->tonezone);
12989          if ((res = get_alarms(tmp)) != DAHDI_ALARM_NONE) {
12990             /* the dchannel is down so put the channel in alarm */
12991             switch (tmp->sig) {
12992 #ifdef HAVE_PRI
12993             case SIG_PRI_LIB_HANDLE_CASES:
12994                sig_pri_set_alarm(tmp->sig_pvt, 1);
12995                break;
12996 #endif
12997 #if defined(HAVE_SS7)
12998             case SIG_SS7:
12999                sig_ss7_set_alarm(tmp->sig_pvt, 1);
13000                break;
13001 #endif   /* defined(HAVE_SS7) */
13002             default:
13003                /* The only sig submodule left should be sig_analog. */
13004                analog_p = tmp->sig_pvt;
13005                if (analog_p) {
13006                   analog_p->inalarm = 1;
13007                }
13008                tmp->inalarm = 1;
13009                break;
13010             }
13011             handle_alarms(tmp, res);
13012          }
13013       }
13014 
13015       tmp->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
13016       tmp->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
13017       tmp->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
13018       tmp->sendcalleridafter = conf->chan.sendcalleridafter;
13019       ast_cc_copy_config_params(tmp->cc_params, conf->chan.cc_params);
13020 
13021       if (!here) {
13022          tmp->locallyblocked = 0;
13023          tmp->remotelyblocked = 0;
13024          switch (tmp->sig) {
13025 #if defined(HAVE_PRI)
13026          case SIG_PRI_LIB_HANDLE_CASES:
13027             tmp->inservice = 1;/* Inservice until actually implemented. */
13028 #if defined(HAVE_PRI_SERVICE_MESSAGES)
13029             ((struct sig_pri_chan *) tmp->sig_pvt)->service_status = 0;
13030             if (chan_sig == SIG_PRI) {
13031                char db_chan_name[20];
13032                char db_answer[5];
13033 
13034                /*
13035                 * Initialize the active out-of-service status
13036                 * and delete any record if the feature is not enabled.
13037                 */
13038                snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, tmp->channel);
13039                if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
13040                   unsigned *why;
13041 
13042                   why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
13043                   if (tmp->pri->enable_service_message_support) {
13044                      char state;
13045 
13046                      sscanf(db_answer, "%1c:%30u", &state, why);
13047 
13048                      /* Ensure that only the implemented bits could be set.*/
13049                      *why &= (SRVST_NEAREND | SRVST_FAREND);
13050                   }
13051                   if (!*why) {
13052                      ast_db_del(db_chan_name, SRVST_DBKEY);
13053                   }
13054                }
13055             }
13056 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
13057             break;
13058 #endif   /* defined(HAVE_PRI) */
13059 #if defined(HAVE_SS7)
13060          case SIG_SS7:
13061             tmp->inservice = 0;
13062             break;
13063 #endif   /* defined(HAVE_SS7) */
13064          default:
13065              /* We default to in service on protocols that don't have a reset */
13066             tmp->inservice = 1;
13067             break;
13068          }
13069       }
13070 
13071       switch (tmp->sig) {
13072 #if defined(HAVE_PRI)
13073       case SIG_PRI_LIB_HANDLE_CASES:
13074          if (pri_chan) {
13075             pri_chan->channel = tmp->channel;
13076             pri_chan->hidecallerid = tmp->hidecallerid;
13077             pri_chan->hidecalleridname = tmp->hidecalleridname;
13078             pri_chan->immediate = tmp->immediate;
13079             pri_chan->inalarm = tmp->inalarm;
13080             pri_chan->priexclusive = tmp->priexclusive;
13081             pri_chan->priindication_oob = tmp->priindication_oob;
13082             pri_chan->use_callerid = tmp->use_callerid;
13083             pri_chan->use_callingpres = tmp->use_callingpres;
13084             ast_copy_string(pri_chan->context, tmp->context,
13085                sizeof(pri_chan->context));
13086             ast_copy_string(pri_chan->mohinterpret, tmp->mohinterpret,
13087                sizeof(pri_chan->mohinterpret));
13088             pri_chan->stripmsd = tmp->stripmsd;
13089          }
13090          break;
13091 #endif   /* defined(HAVE_PRI) */
13092 #if defined(HAVE_SS7)
13093       case SIG_SS7:
13094          if (ss7_chan) {
13095             ss7_chan->inalarm = tmp->inalarm;
13096 
13097             ss7_chan->stripmsd = tmp->stripmsd;
13098             ss7_chan->hidecallerid = tmp->hidecallerid;
13099             ss7_chan->use_callerid = tmp->use_callerid;
13100             ss7_chan->use_callingpres = tmp->use_callingpres;
13101             ss7_chan->immediate = tmp->immediate;
13102             ss7_chan->locallyblocked = tmp->locallyblocked;
13103             ss7_chan->remotelyblocked = tmp->remotelyblocked;
13104             ast_copy_string(ss7_chan->context, tmp->context,
13105                sizeof(ss7_chan->context));
13106             ast_copy_string(ss7_chan->mohinterpret, tmp->mohinterpret,
13107                sizeof(ss7_chan->mohinterpret));
13108          }
13109          break;
13110 #endif   /* defined(HAVE_SS7) */
13111       default:
13112          /* The only sig submodule left should be sig_analog. */
13113          analog_p = tmp->sig_pvt;
13114          if (analog_p) {
13115             analog_p->channel = tmp->channel;
13116             analog_p->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
13117             analog_p->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
13118             analog_p->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
13119             analog_p->permcallwaiting = conf->chan.callwaiting; /* permcallwaiting possibly modified in analog_config_complete */
13120             analog_p->callreturn = conf->chan.callreturn;
13121             analog_p->cancallforward = conf->chan.cancallforward;
13122             analog_p->canpark = conf->chan.canpark;
13123             analog_p->dahditrcallerid = conf->chan.dahditrcallerid;
13124             analog_p->immediate = conf->chan.immediate;
13125             analog_p->permhidecallerid = conf->chan.permhidecallerid;
13126             analog_p->pulse = conf->chan.pulse;
13127             analog_p->threewaycalling = conf->chan.threewaycalling;
13128             analog_p->transfer = conf->chan.transfer;
13129             analog_p->transfertobusy = conf->chan.transfertobusy;
13130             analog_p->use_callerid = tmp->use_callerid;
13131             analog_p->use_smdi = tmp->use_smdi;
13132             analog_p->smdi_iface = tmp->smdi_iface;
13133             analog_p->outsigmod = ANALOG_SIG_NONE;
13134             analog_p->echotraining = conf->chan.echotraining;
13135             analog_p->cid_signalling = conf->chan.cid_signalling;
13136             analog_p->stripmsd = conf->chan.stripmsd;
13137             switch (conf->chan.cid_start) {
13138             case CID_START_POLARITY:
13139                analog_p->cid_start = ANALOG_CID_START_POLARITY;
13140                break;
13141             case CID_START_POLARITY_IN:
13142                analog_p->cid_start = ANALOG_CID_START_POLARITY_IN;
13143                break;
13144             case CID_START_DTMF_NOALERT:
13145                analog_p->cid_start = ANALOG_CID_START_DTMF_NOALERT;
13146                break;
13147             default:
13148                analog_p->cid_start = ANALOG_CID_START_RING;
13149                break;
13150             }
13151             analog_p->callwaitingcallerid = conf->chan.callwaitingcallerid;
13152             analog_p->ringt = conf->chan.ringt;
13153             analog_p->ringt_base = ringt_base;
13154             analog_p->onhooktime = time(NULL);
13155             if (chan_sig & __DAHDI_SIG_FXO) {
13156                memset(&p, 0, sizeof(p));
13157                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
13158                if (!res) {
13159                   analog_p->fxsoffhookstate = p.rxisoffhook;
13160                }
13161 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
13162                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_VMWI_CONFIG, &tmp->mwisend_setting);
13163 #endif
13164             }
13165             analog_p->msgstate = -1;
13166 
13167             ast_copy_string(analog_p->mohsuggest, conf->chan.mohsuggest, sizeof(analog_p->mohsuggest));
13168             ast_copy_string(analog_p->cid_num, conf->chan.cid_num, sizeof(analog_p->cid_num));
13169             ast_copy_string(analog_p->cid_name, conf->chan.cid_name, sizeof(analog_p->cid_name));
13170 
13171             analog_config_complete(analog_p);
13172          }
13173          break;
13174       }
13175 #if defined(HAVE_PRI)
13176       if (tmp->channel == CHAN_PSEUDO) {
13177          /*
13178           * Save off pseudo channel buffer policy values for dynamic creation of
13179           * no B channel interfaces.
13180           */
13181          dahdi_pseudo_parms.buf_no = tmp->buf_no;
13182          dahdi_pseudo_parms.buf_policy = tmp->buf_policy;
13183          dahdi_pseudo_parms.faxbuf_no = tmp->faxbuf_no;
13184          dahdi_pseudo_parms.faxbuf_policy = tmp->faxbuf_policy;
13185       }
13186 #endif   /* defined(HAVE_PRI) */
13187    }
13188    if (tmp && !here) {
13189       /* Add the new channel interface to the sorted channel interface list. */
13190       dahdi_iflist_insert(tmp);
13191    }
13192    return tmp;
13193 }
13194 
13195 static int is_group_or_channel_match(struct dahdi_pvt *p, int span, ast_group_t groupmatch, int *groupmatched, int channelmatch, int *channelmatched)
13196 {
13197 #if defined(HAVE_PRI)
13198    if (0 < span) {
13199       /* The channel must be on the specified PRI span. */
13200       if (!p->pri || p->pri->span != span) {
13201          return 0;
13202       }
13203       if (!groupmatch && channelmatch == -1) {
13204          /* Match any group since it only needs to be on the PRI span. */
13205          *groupmatched = 1;
13206          return 1;
13207       }
13208    }
13209 #endif   /* defined(HAVE_PRI) */
13210    /* check group matching */
13211    if (groupmatch) {
13212       if ((p->group & groupmatch) != groupmatch)
13213          /* Doesn't match the specified group, try the next one */
13214          return 0;
13215       *groupmatched = 1;
13216    }
13217    /* Check to see if we have a channel match */
13218    if (channelmatch != -1) {
13219       if (p->channel != channelmatch)
13220          /* Doesn't match the specified channel, try the next one */
13221          return 0;
13222       *channelmatched = 1;
13223    }
13224 
13225    return 1;
13226 }
13227 
13228 static int available(struct dahdi_pvt **pvt, int is_specific_channel)
13229 {
13230    struct dahdi_pvt *p = *pvt;
13231 
13232    if (p->inalarm)
13233       return 0;
13234 
13235    if (analog_lib_handles(p->sig, p->radio, p->oprmode))
13236       return analog_available(p->sig_pvt);
13237 
13238    switch (p->sig) {
13239 #if defined(HAVE_PRI)
13240    case SIG_PRI_LIB_HANDLE_CASES:
13241       {
13242          struct sig_pri_chan *pvt_chan;
13243          int res;
13244 
13245          pvt_chan = p->sig_pvt;
13246          res = sig_pri_available(&pvt_chan, is_specific_channel);
13247          *pvt = pvt_chan->chan_pvt;
13248          return res;
13249       }
13250 #endif   /* defined(HAVE_PRI) */
13251 #if defined(HAVE_SS7)
13252    case SIG_SS7:
13253       return sig_ss7_available(p->sig_pvt);
13254 #endif   /* defined(HAVE_SS7) */
13255    default:
13256       break;
13257    }
13258 
13259    if (p->locallyblocked || p->remotelyblocked) {
13260       return 0;
13261    }
13262 
13263    /* If no owner definitely available */
13264    if (!p->owner) {
13265 #ifdef HAVE_OPENR2
13266       /* Trust MFC/R2 */
13267       if (p->mfcr2) {
13268          if (p->mfcr2call) {
13269             return 0;
13270          } else {
13271             return 1;
13272          }
13273       }
13274 #endif
13275       return 1;
13276    }
13277 
13278    return 0;
13279 }
13280 
13281 #if defined(HAVE_PRI)
13282 #if defined(HAVE_PRI_CALL_WAITING)
13283 /*!
13284  * \internal
13285  * \brief Init the private channel configuration using the span controller.
13286  * \since 1.8
13287  *
13288  * \param priv Channel to init the configuration.
13289  * \param pri sig_pri PRI control structure.
13290  *
13291  * \note Assumes the pri->lock is already obtained.
13292  *
13293  * \return Nothing
13294  */
13295 static void my_pri_init_config(void *priv, struct sig_pri_span *pri)
13296 {
13297    struct dahdi_pvt *pvt = priv;
13298 
13299    pvt->stripmsd = pri->ch_cfg.stripmsd;
13300    pvt->hidecallerid = pri->ch_cfg.hidecallerid;
13301    pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
13302    pvt->immediate = pri->ch_cfg.immediate;
13303    pvt->priexclusive = pri->ch_cfg.priexclusive;
13304    pvt->priindication_oob = pri->ch_cfg.priindication_oob;
13305    pvt->use_callerid = pri->ch_cfg.use_callerid;
13306    pvt->use_callingpres = pri->ch_cfg.use_callingpres;
13307    ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
13308    ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
13309 }
13310 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13311 #endif   /* defined(HAVE_PRI) */
13312 
13313 #if defined(HAVE_PRI)
13314 /*!
13315  * \internal
13316  * \brief Create a no B channel interface.
13317  * \since 1.8
13318  *
13319  * \param pri sig_pri span controller to add interface.
13320  *
13321  * \note Assumes the pri->lock is already obtained.
13322  *
13323  * \retval array-index into private pointer array on success.
13324  * \retval -1 on error.
13325  */
13326 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri)
13327 {
13328    int pvt_idx;
13329    int res;
13330    unsigned idx;
13331    struct dahdi_pvt *pvt;
13332    struct sig_pri_chan *chan;
13333    struct dahdi_bufferinfo bi;
13334 
13335    static int nobch_channel = CHAN_PSEUDO;
13336 
13337    /* Find spot in the private pointer array for new interface. */
13338    for (pvt_idx = 0; pvt_idx < pri->numchans; ++pvt_idx) {
13339       if (!pri->pvts[pvt_idx]) {
13340          break;
13341       }
13342    }
13343    if (pri->numchans == pvt_idx) {
13344       if (ARRAY_LEN(pri->pvts) <= pvt_idx) {
13345          ast_log(LOG_ERROR, "Unable to add a no-B-channel interface!\n");
13346          return -1;
13347       }
13348 
13349       /* Add new spot to the private pointer array. */
13350       pri->pvts[pvt_idx] = NULL;
13351       ++pri->numchans;
13352    }
13353 
13354    pvt = ast_calloc(1, sizeof(*pvt));
13355    if (!pvt) {
13356       return -1;
13357    }
13358    pvt->cc_params = ast_cc_config_params_init();
13359    if (!pvt->cc_params) {
13360       ast_free(pvt);
13361       return -1;
13362    }
13363    ast_mutex_init(&pvt->lock);
13364    for (idx = 0; idx < ARRAY_LEN(pvt->subs); ++idx) {
13365       pvt->subs[idx].dfd = -1;
13366    }
13367    pvt->buf_no = dahdi_pseudo_parms.buf_no;
13368    pvt->buf_policy = dahdi_pseudo_parms.buf_policy;
13369    pvt->faxbuf_no = dahdi_pseudo_parms.faxbuf_no;
13370    pvt->faxbuf_policy = dahdi_pseudo_parms.faxbuf_policy;
13371 
13372    chan = sig_pri_chan_new(pvt, &dahdi_pri_callbacks, pri, 0, 0, 0);
13373    if (!chan) {
13374       destroy_dahdi_pvt(pvt);
13375       return -1;
13376    }
13377    chan->no_b_channel = 1;
13378 
13379    /*
13380     * Pseudo channel companding law.
13381     * Needed for outgoing call waiting calls.
13382     * XXX May need to make this determined by switchtype or user option.
13383     */
13384    pvt->law_default = DAHDI_LAW_ALAW;
13385 
13386    pvt->sig = pri->sig;
13387    pvt->outsigmod = -1;
13388    pvt->pri = pri;
13389    pvt->sig_pvt = chan;
13390    pri->pvts[pvt_idx] = chan;
13391 
13392    pvt->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
13393    if (pvt->subs[SUB_REAL].dfd < 0) {
13394       ast_log(LOG_ERROR, "Unable to open no B channel interface pseudo channel: %s\n",
13395          strerror(errno));
13396       destroy_dahdi_pvt(pvt);
13397       return -1;
13398    }
13399    memset(&bi, 0, sizeof(bi));
13400    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
13401    if (!res) {
13402       pvt->bufsize = bi.bufsize;
13403       bi.txbufpolicy = pvt->buf_policy;
13404       bi.rxbufpolicy = pvt->buf_policy;
13405       bi.numbufs = pvt->buf_no;
13406       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
13407       if (res < 0) {
13408          ast_log(LOG_WARNING,
13409             "Unable to set buffer policy on no B channel interface: %s\n",
13410             strerror(errno));
13411       }
13412    } else
13413       ast_log(LOG_WARNING,
13414          "Unable to check buffer policy on no B channel interface: %s\n",
13415          strerror(errno));
13416 
13417    --nobch_channel;
13418    if (CHAN_PSEUDO < nobch_channel) {
13419       nobch_channel = CHAN_PSEUDO - 1;
13420    }
13421    pvt->channel = nobch_channel;
13422    pvt->span = pri->span;
13423    chan->channel = pvt->channel;
13424 
13425    dahdi_nobch_insert(pri, pvt);
13426 
13427    return pvt_idx;
13428 }
13429 #endif   /* defined(HAVE_PRI) */
13430 
13431 /* This function can *ONLY* be used for copying pseudo (CHAN_PSEUDO) private
13432    structures; it makes no attempt to safely copy regular channel private
13433    structures that might contain reference-counted object pointers and other
13434    scary bits
13435 */
13436 static struct dahdi_pvt *duplicate_pseudo(struct dahdi_pvt *src)
13437 {
13438    struct dahdi_pvt *p;
13439    struct dahdi_bufferinfo bi;
13440    int res;
13441 
13442    p = ast_malloc(sizeof(*p));
13443    if (!p) {
13444       return NULL;
13445    }
13446    *p = *src;
13447 
13448    /* Must deep copy the cc_params. */
13449    p->cc_params = ast_cc_config_params_init();
13450    if (!p->cc_params) {
13451       ast_free(p);
13452       return NULL;
13453    }
13454    ast_cc_copy_config_params(p->cc_params, src->cc_params);
13455 
13456    p->which_iflist = DAHDI_IFLIST_NONE;
13457    p->next = NULL;
13458    p->prev = NULL;
13459    ast_mutex_init(&p->lock);
13460    p->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
13461    if (p->subs[SUB_REAL].dfd < 0) {
13462       ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
13463       destroy_dahdi_pvt(p);
13464       return NULL;
13465    }
13466    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
13467    if (!res) {
13468       bi.txbufpolicy = src->buf_policy;
13469       bi.rxbufpolicy = src->buf_policy;
13470       bi.numbufs = src->buf_no;
13471       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
13472       if (res < 0) {
13473          ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel: %s\n", strerror(errno));
13474       }
13475    } else
13476       ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel: %s\n", strerror(errno));
13477    p->destroy = 1;
13478    dahdi_iflist_insert(p);
13479    return p;
13480 }
13481 
13482 struct dahdi_starting_point {
13483    /*! Group matching mask.  Zero if not specified. */
13484    ast_group_t groupmatch;
13485    /*! DAHDI channel to match with.  -1 if not specified. */
13486    int channelmatch;
13487    /*! Round robin saved search location index. (Valid if roundrobin TRUE) */
13488    int rr_starting_point;
13489    /*! ISDN span where channels can be picked (Zero if not specified) */
13490    int span;
13491    /*! Analog channel distinctive ring cadance index. */
13492    int cadance;
13493    /*! Dialing option. c/r/d if present and valid. */
13494    char opt;
13495    /*! TRUE if to search the channel list backwards. */
13496    char backwards;
13497    /*! TRUE if search is done with round robin sequence. */
13498    char roundrobin;
13499 };
13500 static struct dahdi_pvt *determine_starting_point(const char *data, struct dahdi_starting_point *param)
13501 {
13502    char *dest;
13503    char *s;
13504    int x;
13505    int res = 0;
13506    struct dahdi_pvt *p;
13507    char *subdir = NULL;
13508    AST_DECLARE_APP_ARGS(args,
13509       AST_APP_ARG(group);  /* channel/group token */
13510       //AST_APP_ARG(ext);  /* extension token */
13511       //AST_APP_ARG(opts); /* options token */
13512       AST_APP_ARG(other);  /* Any remining unused arguments */
13513    );
13514 
13515    /*
13516     * data is ---v
13517     * Dial(DAHDI/pseudo[/extension[/options]])
13518     * Dial(DAHDI/<channel#>[c|r<cadance#>|d][/extension[/options]])
13519     * Dial(DAHDI/<subdir>!<channel#>[c|r<cadance#>|d][/extension[/options]])
13520     * Dial(DAHDI/i<span>[/extension[/options]])
13521     * Dial(DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]])
13522     *
13523     * i - ISDN span channel restriction.
13524     *     Used by CC to ensure that the CC recall goes out the same span.
13525     *     Also to make ISDN channel names dialable when the sequence number
13526     *     is stripped off.  (Used by DTMF attended transfer feature.)
13527     *
13528     * g - channel group allocation search forward
13529     * G - channel group allocation search backward
13530     * r - channel group allocation round robin search forward
13531     * R - channel group allocation round robin search backward
13532     *
13533     * c - Wait for DTMF digit to confirm answer
13534     * r<cadance#> - Set distintive ring cadance number
13535     * d - Force bearer capability for ISDN/SS7 call to digital.
13536     */
13537 
13538    if (data) {
13539       dest = ast_strdupa(data);
13540    } else {
13541       ast_log(LOG_WARNING, "Channel requested with no data\n");
13542       return NULL;
13543    }
13544    AST_NONSTANDARD_APP_ARGS(args, dest, '/');
13545    if (!args.argc || ast_strlen_zero(args.group)) {
13546       ast_log(LOG_WARNING, "No channel/group specified\n");
13547       return NULL;
13548    }
13549 
13550    /* Initialize the output parameters */
13551    memset(param, 0, sizeof(*param));
13552    param->channelmatch = -1;
13553 
13554    if (strchr(args.group, '!') != NULL) {
13555       char *prev = args.group;
13556       while ((s = strchr(prev, '!')) != NULL) {
13557          *s++ = '/';
13558          prev = s;
13559       }
13560       *(prev - 1) = '\0';
13561       subdir = args.group;
13562       args.group = prev;
13563    } else if (args.group[0] == 'i') {
13564       /* Extract the ISDN span channel restriction specifier. */
13565       res = sscanf(args.group + 1, "%30d", &x);
13566       if (res < 1) {
13567          ast_log(LOG_WARNING, "Unable to determine ISDN span for data %s\n", data);
13568          return NULL;
13569       }
13570       param->span = x;
13571 
13572       /* Remove the ISDN span channel restriction specifier. */
13573       s = strchr(args.group, '-');
13574       if (!s) {
13575          /* Search all groups since we are ISDN span restricted. */
13576          return iflist;
13577       }
13578       args.group = s + 1;
13579       res = 0;
13580    }
13581    if (toupper(args.group[0]) == 'G' || toupper(args.group[0])=='R') {
13582       /* Retrieve the group number */
13583       s = args.group + 1;
13584       res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13585       if (res < 1) {
13586          ast_log(LOG_WARNING, "Unable to determine group for data %s\n", data);
13587          return NULL;
13588       }
13589       param->groupmatch = ((ast_group_t) 1 << x);
13590 
13591       if (toupper(args.group[0]) == 'G') {
13592          if (args.group[0] == 'G') {
13593             param->backwards = 1;
13594             p = ifend;
13595          } else
13596             p = iflist;
13597       } else {
13598          if (ARRAY_LEN(round_robin) <= x) {
13599             ast_log(LOG_WARNING, "Round robin index %d out of range for data %s\n",
13600                x, data);
13601             return NULL;
13602          }
13603          if (args.group[0] == 'R') {
13604             param->backwards = 1;
13605             p = round_robin[x] ? round_robin[x]->prev : ifend;
13606             if (!p)
13607                p = ifend;
13608          } else {
13609             p = round_robin[x] ? round_robin[x]->next : iflist;
13610             if (!p)
13611                p = iflist;
13612          }
13613          param->roundrobin = 1;
13614          param->rr_starting_point = x;
13615       }
13616    } else {
13617       s = args.group;
13618       if (!strcasecmp(s, "pseudo")) {
13619          /* Special case for pseudo */
13620          x = CHAN_PSEUDO;
13621          param->channelmatch = x;
13622       } else {
13623          res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13624          if (res < 1) {
13625             ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", data);
13626             return NULL;
13627          } else {
13628             param->channelmatch = x;
13629          }
13630       }
13631       if (subdir) {
13632          char path[PATH_MAX];
13633          struct stat stbuf;
13634 
13635          snprintf(path, sizeof(path), "/dev/dahdi/%s/%d",
13636                subdir, param->channelmatch);
13637          if (stat(path, &stbuf) < 0) {
13638             ast_log(LOG_WARNING, "stat(%s) failed: %s\n",
13639                   path, strerror(errno));
13640             return NULL;
13641          }
13642          if (!S_ISCHR(stbuf.st_mode)) {
13643             ast_log(LOG_ERROR, "%s: Not a character device file\n",
13644                   path);
13645             return NULL;
13646          }
13647          param->channelmatch = minor(stbuf.st_rdev);
13648       }
13649 
13650       p = iflist;
13651    }
13652 
13653    if (param->opt == 'r' && res < 3) {
13654       ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", data);
13655       param->opt = '\0';
13656    }
13657 
13658    return p;
13659 }
13660 
13661 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
13662 {
13663    int callwait = 0;
13664    struct dahdi_pvt *p;
13665    struct ast_channel *tmp = NULL;
13666    struct dahdi_pvt *exitpvt;
13667    int channelmatched = 0;
13668    int groupmatched = 0;
13669 #if defined(HAVE_PRI) || defined(HAVE_SS7)
13670    int transcapdigital = 0;
13671 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
13672    struct dahdi_starting_point start;
13673 
13674    ast_mutex_lock(&iflock);
13675    p = determine_starting_point(data, &start);
13676    if (!p) {
13677       /* We couldn't determine a starting point, which likely means badly-formatted channel name. Abort! */
13678       ast_mutex_unlock(&iflock);
13679       return NULL;
13680    }
13681 
13682    /* Search for an unowned channel */
13683    exitpvt = p;
13684    while (p && !tmp) {
13685       if (start.roundrobin)
13686          round_robin[start.rr_starting_point] = p;
13687 
13688       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)
13689          && available(&p, channelmatched)) {
13690          ast_debug(1, "Using channel %d\n", p->channel);
13691 
13692          callwait = (p->owner != NULL);
13693 #ifdef HAVE_OPENR2
13694          if (p->mfcr2) {
13695             ast_mutex_lock(&p->lock);
13696             if (p->mfcr2call) {
13697                ast_mutex_unlock(&p->lock);
13698                ast_log(LOG_DEBUG, "Yay!, someone just beat us in the race for channel %d.\n", p->channel);
13699                goto next;
13700             }
13701             p->mfcr2call = 1;
13702             ast_mutex_unlock(&p->lock);
13703          }
13704 #endif
13705          if (p->channel == CHAN_PSEUDO) {
13706             p = duplicate_pseudo(p);
13707             if (!p) {
13708                break;
13709             }
13710          }
13711 
13712          p->distinctivering = 0;
13713          /* Make special notes */
13714          switch (start.opt) {
13715          case '\0':
13716             /* No option present. */
13717             break;
13718          case 'c':
13719             /* Confirm answer */
13720             p->confirmanswer = 1;
13721             break;
13722          case 'r':
13723             /* Distinctive ring */
13724             p->distinctivering = start.cadance;
13725             break;
13726          case 'd':
13727 #if defined(HAVE_PRI) || defined(HAVE_SS7)
13728             /* If this is an ISDN call, make it digital */
13729             transcapdigital = AST_TRANS_CAP_DIGITAL;
13730 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
13731             break;
13732          default:
13733             ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", start.opt, (char *)data);
13734             break;
13735          }
13736 
13737          p->outgoing = 1;
13738          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
13739             tmp = analog_request(p->sig_pvt, &callwait, requestor);
13740 #ifdef HAVE_PRI
13741          } else if (dahdi_sig_pri_lib_handles(p->sig)) {
13742             /*
13743              * We already have the B channel reserved for this call.  We
13744              * just need to make sure that dahdi_hangup() has completed
13745              * cleaning up before continuing.
13746              */
13747             ast_mutex_lock(&p->lock);
13748             ast_mutex_unlock(&p->lock);
13749 
13750             sig_pri_extract_called_num_subaddr(p->sig_pvt, data, p->dnid,
13751                sizeof(p->dnid));
13752             tmp = sig_pri_request(p->sig_pvt, SIG_PRI_DEFLAW, requestor, transcapdigital);
13753 #endif
13754 #if defined(HAVE_SS7)
13755          } else if (p->sig == SIG_SS7) {
13756             tmp = sig_ss7_request(p->sig_pvt, SIG_SS7_DEFLAW, requestor, transcapdigital);
13757 #endif   /* defined(HAVE_SS7) */
13758          } else {
13759             tmp = dahdi_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, requestor ? requestor->linkedid : "");
13760          }
13761          if (!tmp) {
13762             p->outgoing = 0;
13763 #if defined(HAVE_PRI)
13764             switch (p->sig) {
13765             case SIG_PRI_LIB_HANDLE_CASES:
13766 #if defined(HAVE_PRI_CALL_WAITING)
13767                if (((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting) {
13768                   ((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting = 0;
13769                   ast_atomic_fetchadd_int(&p->pri->num_call_waiting_calls, -1);
13770                }
13771 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13772                /*
13773                 * This should be the last thing to clear when we are done with
13774                 * the channel.
13775                 */
13776                ((struct sig_pri_chan *) p->sig_pvt)->allocated = 0;
13777                break;
13778             default:
13779                break;
13780             }
13781 #endif   /* defined(HAVE_PRI) */
13782          } else {
13783             snprintf(p->dialstring, sizeof(p->dialstring), "DAHDI/%s", (char *) data);
13784          }
13785          break;
13786       }
13787 #ifdef HAVE_OPENR2
13788 next:
13789 #endif
13790       if (start.backwards) {
13791          p = p->prev;
13792          if (!p)
13793             p = ifend;
13794       } else {
13795          p = p->next;
13796          if (!p)
13797             p = iflist;
13798       }
13799       /* stop when you roll to the one that we started from */
13800       if (p == exitpvt)
13801          break;
13802    }
13803    ast_mutex_unlock(&iflock);
13804    restart_monitor();
13805    if (cause && !tmp) {
13806       if (callwait || channelmatched) {
13807          *cause = AST_CAUSE_BUSY;
13808       } else if (groupmatched) {
13809          *cause = AST_CAUSE_CONGESTION;
13810       } else {
13811          /*
13812           * We did not match any channel requested.
13813           * Dialplan error requesting non-existant channel?
13814           */
13815       }
13816    }
13817 
13818    return tmp;
13819 }
13820 
13821 /*!
13822  * \internal
13823  * \brief Determine the device state for a given DAHDI device if we can.
13824  * \since 1.8
13825  *
13826  * \param data DAHDI device name after "DAHDI/".
13827  *
13828  * \retval device_state enum ast_device_state value.
13829  * \retval AST_DEVICE_UNKNOWN if we could not determine the device's state.
13830  */
13831 static int dahdi_devicestate(void *data)
13832 {
13833 #if defined(HAVE_PRI)
13834    char *device;
13835    unsigned span;
13836    int res;
13837 
13838    device = data;
13839 
13840    if (*device != 'I') {
13841       /* The request is not for an ISDN span device. */
13842       return AST_DEVICE_UNKNOWN;
13843    }
13844    res = sscanf(device, "I%30u", &span);
13845    if (res != 1 || !span || NUM_SPANS < span) {
13846       /* Bad format for ISDN span device name. */
13847       return AST_DEVICE_UNKNOWN;
13848    }
13849    device = strchr(device, '/');
13850    if (!device) {
13851       /* Bad format for ISDN span device name. */
13852       return AST_DEVICE_UNKNOWN;
13853    }
13854 
13855    /*
13856     * Since there are currently no other span devstate's defined,
13857     * it must be congestion.
13858     */
13859 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13860    ++device;
13861    if (!strcmp(device, "congestion"))
13862 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13863    {
13864       return pris[span - 1].pri.congestion_devstate;
13865    }
13866 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13867    else if (!strcmp(device, "threshold")) {
13868       return pris[span - 1].pri.threshold_devstate;
13869    }
13870    return AST_DEVICE_UNKNOWN;
13871 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13872 #else
13873    return AST_DEVICE_UNKNOWN;
13874 #endif   /* defined(HAVE_PRI) */
13875 }
13876 
13877 /*!
13878  * \brief Callback made when dial failed to get a channel out of dahdi_request().
13879  * \since 1.8
13880  *
13881  * \param inbound Incoming asterisk channel.
13882  * \param dest Same dial string passed to dahdi_request().
13883  * \param callback Callback into CC core to announce a busy channel available for CC.
13884  *
13885  * \details
13886  * This callback acts like a forked dial with all prongs of the fork busy.
13887  * Essentially, for each channel that could have taken the call, indicate that
13888  * it is busy.
13889  *
13890  * \retval 0 on success.
13891  * \retval -1 on error.
13892  */
13893 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback)
13894 {
13895    struct dahdi_pvt *p;
13896    struct dahdi_pvt *exitpvt;
13897    struct dahdi_starting_point start;
13898    int groupmatched = 0;
13899    int channelmatched = 0;
13900 
13901    ast_mutex_lock(&iflock);
13902    p = determine_starting_point(dest, &start);
13903    if (!p) {
13904       ast_mutex_unlock(&iflock);
13905       return -1;
13906    }
13907    exitpvt = p;
13908    for (;;) {
13909       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)) {
13910          /* We found a potential match. call the callback */
13911          struct ast_str *device_name;
13912          char *dash;
13913          const char *monitor_type;
13914          char dialstring[AST_CHANNEL_NAME];
13915          char full_device_name[AST_CHANNEL_NAME];
13916 
13917          switch (ast_get_cc_monitor_policy(p->cc_params)) {
13918          case AST_CC_MONITOR_NEVER:
13919             break;
13920          case AST_CC_MONITOR_NATIVE:
13921          case AST_CC_MONITOR_ALWAYS:
13922          case AST_CC_MONITOR_GENERIC:
13923 #if defined(HAVE_PRI)
13924             if (dahdi_sig_pri_lib_handles(p->sig)) {
13925                /*
13926                 * ISDN is in a trunk busy condition so we need to monitor
13927                 * the span congestion device state.
13928                 */
13929                snprintf(full_device_name, sizeof(full_device_name),
13930                   "DAHDI/I%d/congestion", p->pri->span);
13931             } else
13932 #endif   /* defined(HAVE_PRI) */
13933             {
13934 #if defined(HAVE_PRI)
13935                device_name = create_channel_name(p, 1, "");
13936 #else
13937                device_name = create_channel_name(p);
13938 #endif   /* defined(HAVE_PRI) */
13939                snprintf(full_device_name, sizeof(full_device_name), "DAHDI/%s",
13940                   device_name ? ast_str_buffer(device_name) : "");
13941                ast_free(device_name);
13942                /*
13943                 * The portion after the '-' in the channel name is either a random
13944                 * number, a sequence number, or a subchannel number. None are
13945                 * necessary so strip them off.
13946                 */
13947                dash = strrchr(full_device_name, '-');
13948                if (dash) {
13949                   *dash = '\0';
13950                }
13951             }
13952             snprintf(dialstring, sizeof(dialstring), "DAHDI/%s", dest);
13953 
13954             /*
13955              * Analog can only do generic monitoring.
13956              * ISDN is in a trunk busy condition and any "device" is going
13957              * to be busy until a B channel becomes available.  The generic
13958              * monitor can do this task.
13959              */
13960             monitor_type = AST_CC_GENERIC_MONITOR_TYPE;
13961             callback(inbound,
13962 #if defined(HAVE_PRI)
13963                p->pri ? p->pri->cc_params : p->cc_params,
13964 #else
13965                p->cc_params,
13966 #endif   /* defined(HAVE_PRI) */
13967                monitor_type, full_device_name, dialstring, NULL);
13968             break;
13969          }
13970       }
13971       p = start.backwards ? p->prev : p->next;
13972       if (!p) {
13973          p = start.backwards ? ifend : iflist;
13974       }
13975       if (p == exitpvt) {
13976          break;
13977       }
13978    }
13979    ast_mutex_unlock(&iflock);
13980    return 0;
13981 }
13982 
13983 #if defined(HAVE_SS7)
13984 static void dahdi_ss7_message(struct ss7 *ss7, char *s)
13985 {
13986    int i;
13987 
13988    if (ss7) {
13989       for (i = 0; i < NUM_SPANS; i++) {
13990          if (linksets[i].ss7.ss7 == ss7) {
13991             ast_verbose("[%d] %s", i + 1, s);
13992             return;
13993          }
13994       }
13995    }
13996    ast_verbose("%s", s);
13997 }
13998 #endif   /* defined(HAVE_SS7) */
13999 
14000 #if defined(HAVE_SS7)
14001 static void dahdi_ss7_error(struct ss7 *ss7, char *s)
14002 {
14003    int i;
14004 
14005    if (ss7) {
14006       for (i = 0; i < NUM_SPANS; i++) {
14007          if (linksets[i].ss7.ss7 == ss7) {
14008             ast_log(LOG_ERROR, "[%d] %s", i + 1, s);
14009             return;
14010          }
14011       }
14012    }
14013    ast_log(LOG_ERROR, "%s", s);
14014 }
14015 #endif   /* defined(HAVE_SS7) */
14016 
14017 #if defined(HAVE_OPENR2)
14018 static void *mfcr2_monitor(void *data)
14019 {
14020    struct dahdi_mfcr2 *mfcr2 = data;
14021    /* we should be using pthread_key_create
14022       and allocate pollers dynamically.
14023       I think do_monitor() could be leaking, since it
14024       could be cancelled at any time and is not
14025       using thread keys, why?, */
14026    struct pollfd pollers[ARRAY_LEN(mfcr2->pvts)];
14027    int res = 0;
14028    int i = 0;
14029    int oldstate = 0;
14030    int quit_loop = 0;
14031    int maxsleep = 20;
14032    int was_idle = 0;
14033    int pollsize = 0;
14034    /* now that we're ready to get calls, unblock our side and
14035       get current line state */
14036    for (i = 0; i < mfcr2->numchans; i++) {
14037       openr2_chan_set_idle(mfcr2->pvts[i]->r2chan);
14038       openr2_chan_handle_cas(mfcr2->pvts[i]->r2chan);
14039    }
14040    while (1) {
14041       /* we trust here that the mfcr2 channel list will not ever change once
14042          the module is loaded */
14043       pollsize = 0;
14044       for (i = 0; i < mfcr2->numchans; i++) {
14045          pollers[i].revents = 0;
14046          pollers[i].events = 0;
14047          if (mfcr2->pvts[i]->owner) {
14048             continue;
14049          }
14050          if (!mfcr2->pvts[i]->r2chan) {
14051             ast_log(LOG_DEBUG, "Wow, no r2chan on channel %d\n", mfcr2->pvts[i]->channel);
14052             quit_loop = 1;
14053             break;
14054          }
14055          openr2_chan_enable_read(mfcr2->pvts[i]->r2chan);
14056          pollers[i].events = POLLIN | POLLPRI;
14057          pollers[i].fd = mfcr2->pvts[i]->subs[SUB_REAL].dfd;
14058          pollsize++;
14059       }
14060       if (quit_loop) {
14061          break;
14062       }
14063       if (pollsize == 0) {
14064          if (!was_idle) {
14065             ast_log(LOG_DEBUG, "Monitor thread going idle since everybody has an owner\n");
14066             was_idle = 1;
14067          }
14068          poll(NULL, 0, maxsleep);
14069          continue;
14070       }
14071       was_idle = 0;
14072       /* probably poll() is a valid cancel point, lets just be on the safe side
14073          by calling pthread_testcancel */
14074       pthread_testcancel();
14075       res = poll(pollers, mfcr2->numchans, maxsleep);
14076       pthread_testcancel();
14077       if ((res < 0) && (errno != EINTR)) {
14078          ast_log(LOG_ERROR, "going out, poll failed: %s\n", strerror(errno));
14079          break;
14080       }
14081       /* do we want to allow to cancel while processing events? */
14082       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
14083       for (i = 0; i < mfcr2->numchans; i++) {
14084          if (pollers[i].revents & POLLPRI || pollers[i].revents & POLLIN) {
14085             openr2_chan_process_event(mfcr2->pvts[i]->r2chan);
14086          }
14087       }
14088       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
14089    }
14090    ast_log(LOG_NOTICE, "Quitting MFC/R2 monitor thread\n");
14091    return 0;
14092 }
14093 #endif /* HAVE_OPENR2 */
14094 
14095 #if defined(HAVE_PRI)
14096 static void dahdi_pri_message(struct pri *pri, char *s)
14097 {
14098    int x;
14099    int y;
14100    int dchan = -1;
14101    int span = -1;
14102    int dchancount = 0;
14103 
14104    if (pri) {
14105       for (x = 0; x < NUM_SPANS; x++) {
14106          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14107             if (pris[x].pri.dchans[y]) {
14108                dchancount++;
14109             }
14110 
14111             if (pris[x].pri.dchans[y] == pri) {
14112                dchan = y;
14113             }
14114          }
14115          if (dchan >= 0) {
14116             span = x;
14117             break;
14118          }
14119          dchancount = 0;
14120       }
14121       if (-1 < span) {
14122          if (1 < dchancount) {
14123             ast_verbose("[PRI Span: %d D-Channel: %d] %s", span + 1, dchan, s);
14124          } else {
14125             ast_verbose("PRI Span: %d %s", span + 1, s);
14126          }
14127       } else {
14128          ast_verbose("PRI Span: ? %s", s);
14129       }
14130    } else {
14131       ast_verbose("PRI Span: ? %s", s);
14132    }
14133 
14134    ast_mutex_lock(&pridebugfdlock);
14135 
14136    if (pridebugfd >= 0) {
14137       if (write(pridebugfd, s, strlen(s)) < 0) {
14138          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14139       }
14140    }
14141 
14142    ast_mutex_unlock(&pridebugfdlock);
14143 }
14144 #endif   /* defined(HAVE_PRI) */
14145 
14146 #if defined(HAVE_PRI)
14147 static void dahdi_pri_error(struct pri *pri, char *s)
14148 {
14149    int x;
14150    int y;
14151    int dchan = -1;
14152    int span = -1;
14153    int dchancount = 0;
14154 
14155    if (pri) {
14156       for (x = 0; x < NUM_SPANS; x++) {
14157          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14158             if (pris[x].pri.dchans[y]) {
14159                dchancount++;
14160             }
14161 
14162             if (pris[x].pri.dchans[y] == pri) {
14163                dchan = y;
14164             }
14165          }
14166          if (dchan >= 0) {
14167             span = x;
14168             break;
14169          }
14170          dchancount = 0;
14171       }
14172       if (-1 < span) {
14173          if (1 < dchancount) {
14174             ast_log(LOG_ERROR, "[PRI Span: %d D-Channel: %d] %s", span + 1, dchan, s);
14175          } else {
14176             ast_log(LOG_ERROR, "PRI Span: %d %s", span + 1, s);
14177          }
14178       } else {
14179          ast_log(LOG_ERROR, "PRI Span: ? %s", s);
14180       }
14181    } else {
14182       ast_log(LOG_ERROR, "PRI Span: ? %s", s);
14183    }
14184 
14185    ast_mutex_lock(&pridebugfdlock);
14186 
14187    if (pridebugfd >= 0) {
14188       if (write(pridebugfd, s, strlen(s)) < 0) {
14189          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
14190       }
14191    }
14192 
14193    ast_mutex_unlock(&pridebugfdlock);
14194 }
14195 #endif   /* defined(HAVE_PRI) */
14196 
14197 #if defined(HAVE_PRI)
14198 static int prepare_pri(struct dahdi_pri *pri)
14199 {
14200    int i, res, x;
14201    struct dahdi_params p;
14202    struct dahdi_bufferinfo bi;
14203    struct dahdi_spaninfo si;
14204 
14205    pri->pri.calls = &dahdi_pri_callbacks;
14206 
14207    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
14208       if (!pri->dchannels[i])
14209          break;
14210       pri->pri.fds[i] = open("/dev/dahdi/channel", O_RDWR);
14211       x = pri->dchannels[i];
14212       if ((pri->pri.fds[i] < 0) || (ioctl(pri->pri.fds[i],DAHDI_SPECIFY,&x) == -1)) {
14213          ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
14214          return -1;
14215       }
14216       memset(&p, 0, sizeof(p));
14217       res = ioctl(pri->pri.fds[i], DAHDI_GET_PARAMS, &p);
14218       if (res) {
14219          dahdi_close_pri_fd(pri, i);
14220          ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
14221          return -1;
14222       }
14223       if ((p.sigtype != DAHDI_SIG_HDLCFCS) && (p.sigtype != DAHDI_SIG_HARDHDLC)) {
14224          dahdi_close_pri_fd(pri, i);
14225          ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode.\n", x);
14226          return -1;
14227       }
14228       memset(&si, 0, sizeof(si));
14229       res = ioctl(pri->pri.fds[i], DAHDI_SPANSTAT, &si);
14230       if (res) {
14231          dahdi_close_pri_fd(pri, i);
14232          ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
14233       }
14234       if (!si.alarms) {
14235          pri_event_noalarm(&pri->pri, i, 1);
14236       } else {
14237          pri_event_alarm(&pri->pri, i, 1);
14238       }
14239       memset(&bi, 0, sizeof(bi));
14240       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
14241       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
14242       bi.numbufs = 32;
14243       bi.bufsize = 1024;
14244       if (ioctl(pri->pri.fds[i], DAHDI_SET_BUFINFO, &bi)) {
14245          ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n", x, strerror(errno));
14246          dahdi_close_pri_fd(pri, i);
14247          return -1;
14248       }
14249       pri->pri.dchan_logical_span[i] = pris[p.spanno - 1].prilogicalspan;
14250    }
14251    return 0;
14252 }
14253 #endif   /* defined(HAVE_PRI) */
14254 
14255 #if defined(HAVE_PRI)
14256 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
14257 {
14258    int which, span;
14259    char *ret = NULL;
14260 
14261    if (pos != rpos)
14262       return ret;
14263 
14264    for (which = span = 0; span < NUM_SPANS; span++) {
14265       if (pris[span].pri.pri && ++which > state) {
14266          if (ast_asprintf(&ret, "%d", span + 1) < 0) {   /* user indexes start from 1 */
14267             ret = NULL;
14268          }
14269          break;
14270       }
14271    }
14272    return ret;
14273 }
14274 #endif   /* defined(HAVE_PRI) */
14275 
14276 #if defined(HAVE_PRI)
14277 static char *complete_span_4(const char *line, const char *word, int pos, int state)
14278 {
14279    return complete_span_helper(line,word,pos,state,3);
14280 }
14281 #endif   /* defined(HAVE_PRI) */
14282 
14283 #if defined(HAVE_PRI)
14284 static char *handle_pri_set_debug_file(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14285 {
14286    int myfd;
14287    switch (cmd) {
14288    case CLI_INIT:
14289       e->command = "pri set debug file";
14290       e->usage = "Usage: pri set debug file [output-file]\n"
14291          "       Sends PRI debug output to the specified output file\n";
14292       return NULL;
14293    case CLI_GENERATE:
14294       return NULL;
14295    }
14296    if (a->argc < 5)
14297       return CLI_SHOWUSAGE;
14298 
14299    if (ast_strlen_zero(a->argv[4]))
14300       return CLI_SHOWUSAGE;
14301 
14302    myfd = open(a->argv[4], O_CREAT|O_WRONLY, AST_FILE_MODE);
14303    if (myfd < 0) {
14304       ast_cli(a->fd, "Unable to open '%s' for writing\n", a->argv[4]);
14305       return CLI_SUCCESS;
14306    }
14307 
14308    ast_mutex_lock(&pridebugfdlock);
14309 
14310    if (pridebugfd >= 0)
14311       close(pridebugfd);
14312 
14313    pridebugfd = myfd;
14314    ast_copy_string(pridebugfilename,a->argv[4],sizeof(pridebugfilename));
14315    ast_mutex_unlock(&pridebugfdlock);
14316    ast_cli(a->fd, "PRI debug output will be sent to '%s'\n", a->argv[4]);
14317    return CLI_SUCCESS;
14318 }
14319 #endif   /* defined(HAVE_PRI) */
14320 
14321 #if defined(HAVE_PRI)
14322 static char *handle_pri_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14323 {
14324    int span;
14325    int x;
14326    int level = 0;
14327    switch (cmd) {
14328    case CLI_INIT:
14329       e->command = "pri set debug {on|off|0|1|2} span";
14330       e->usage =
14331          "Usage: pri set debug {<level>|on|off} span <span>\n"
14332          "       Enables debugging on a given PRI span\n";
14333       return NULL;
14334    case CLI_GENERATE:
14335       return complete_span_4(a->line, a->word, a->pos, a->n);
14336    }
14337    if (a->argc < 6) {
14338       return CLI_SHOWUSAGE;
14339    }
14340 
14341    if (!strcasecmp(a->argv[3], "on")) {
14342       level = 1;
14343    } else if (!strcasecmp(a->argv[3], "off")) {
14344       level = 0;
14345    } else {
14346       level = atoi(a->argv[3]);
14347    }
14348    span = atoi(a->argv[5]);
14349    if ((span < 1) || (span > NUM_SPANS)) {
14350       ast_cli(a->fd, "Invalid span %s.  Should be a number %d to %d\n", a->argv[5], 1, NUM_SPANS);
14351       return CLI_SUCCESS;
14352    }
14353    if (!pris[span-1].pri.pri) {
14354       ast_cli(a->fd, "No PRI running on span %d\n", span);
14355       return CLI_SUCCESS;
14356    }
14357 
14358    /* Set debug level in libpri */
14359    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14360       if (pris[span - 1].pri.dchans[x]) {
14361          switch (level) {
14362          case 0:
14363             pri_set_debug(pris[span - 1].pri.dchans[x], 0);
14364             break;
14365          case 1:
14366             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_NORMAL);
14367             break;
14368          default:
14369             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_INTENSE);
14370             break;
14371          }
14372       }
14373    }
14374    if (level == 0) {
14375       /* Close the debugging file if it's set */
14376       ast_mutex_lock(&pridebugfdlock);
14377       if (0 <= pridebugfd) {
14378          close(pridebugfd);
14379          pridebugfd = -1;
14380          ast_cli(a->fd, "Disabled PRI debug output to file '%s'\n",
14381             pridebugfilename);
14382       }
14383       ast_mutex_unlock(&pridebugfdlock);
14384    }
14385    pris[span - 1].pri.debug = (level) ? 1 : 0;
14386    ast_cli(a->fd, "%s debugging on span %d\n", (level) ? "Enabled" : "Disabled", span);
14387    return CLI_SUCCESS;
14388 }
14389 #endif   /* defined(HAVE_PRI) */
14390 
14391 #if defined(HAVE_PRI)
14392 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14393 static char *handle_pri_service_generic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a, int changestatus)
14394 {
14395    unsigned *why;
14396    int channel;
14397    int trunkgroup;
14398    int x, y, fd = a->fd;
14399    int interfaceid = 0;
14400    char db_chan_name[20], db_answer[5];
14401    struct dahdi_pvt *tmp;
14402    struct dahdi_pri *pri;
14403 
14404    if (a->argc < 5 || a->argc > 6)
14405       return CLI_SHOWUSAGE;
14406    if (strchr(a->argv[4], ':')) {
14407       if (sscanf(a->argv[4], "%30d:%30d", &trunkgroup, &channel) != 2)
14408          return CLI_SHOWUSAGE;
14409       if ((trunkgroup < 1) || (channel < 1))
14410          return CLI_SHOWUSAGE;
14411       pri = NULL;
14412       for (x=0;x<NUM_SPANS;x++) {
14413          if (pris[x].pri.trunkgroup == trunkgroup) {
14414             pri = pris + x;
14415             break;
14416          }
14417       }
14418       if (!pri) {
14419          ast_cli(fd, "No such trunk group %d\n", trunkgroup);
14420          return CLI_FAILURE;
14421       }
14422    } else
14423       channel = atoi(a->argv[4]);
14424 
14425    if (a->argc == 6)
14426       interfaceid = atoi(a->argv[5]);
14427 
14428    /* either servicing a D-Channel */
14429    for (x = 0; x < NUM_SPANS; x++) {
14430       for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
14431          if (pris[x].dchannels[y] == channel) {
14432             pri = pris + x;
14433             if (pri->pri.enable_service_message_support) {
14434                ast_mutex_lock(&pri->pri.lock);
14435                pri_maintenance_service(pri->pri.pri, interfaceid, -1, changestatus);
14436                ast_mutex_unlock(&pri->pri.lock);
14437             } else {
14438                ast_cli(fd,
14439                   "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
14440                   "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
14441             }
14442             return CLI_SUCCESS;
14443          }
14444       }
14445    }
14446 
14447    /* or servicing a B-Channel */
14448    ast_mutex_lock(&iflock);
14449    for (tmp = iflist; tmp; tmp = tmp->next) {
14450       if (tmp->pri && tmp->channel == channel) {
14451          ast_mutex_unlock(&iflock);
14452          ast_mutex_lock(&tmp->pri->lock);
14453          if (!tmp->pri->enable_service_message_support) {
14454             ast_mutex_unlock(&tmp->pri->lock);
14455             ast_cli(fd,
14456                "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
14457                "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
14458             return CLI_SUCCESS;
14459          }
14460          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, channel);
14461          why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
14462          switch(changestatus) {
14463          case 0: /* enable */
14464             /* Near end wants to be in service now. */
14465             ast_db_del(db_chan_name, SRVST_DBKEY);
14466             *why &= ~SRVST_NEAREND;
14467             if (*why) {
14468                snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
14469                ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
14470             } else {
14471                dahdi_pri_update_span_devstate(tmp->pri);
14472             }
14473             break;
14474          /* case 1:  -- loop */
14475          case 2: /* disable */
14476             /* Near end wants to be out-of-service now. */
14477             ast_db_del(db_chan_name, SRVST_DBKEY);
14478             *why |= SRVST_NEAREND;
14479             snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
14480             ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
14481             dahdi_pri_update_span_devstate(tmp->pri);
14482             break;
14483          /* case 3:  -- continuity */
14484          /* case 4:  -- shutdown */
14485          default:
14486             ast_log(LOG_WARNING, "Unsupported changestatus: '%d'\n", changestatus);
14487             break;
14488          }
14489          pri_maintenance_bservice(tmp->pri->pri, tmp->sig_pvt, changestatus);
14490          ast_mutex_unlock(&tmp->pri->lock);
14491          return CLI_SUCCESS;
14492       }
14493    }
14494    ast_mutex_unlock(&iflock);
14495 
14496    ast_cli(fd, "Unable to find given channel %d, possibly not a PRI\n", channel);
14497    return CLI_FAILURE;
14498 }
14499 
14500 static char *handle_pri_service_enable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14501 {
14502    switch (cmd) {
14503    case CLI_INIT:
14504       e->command = "pri service enable channel";
14505       e->usage =
14506          "Usage: pri service enable channel <channel> [<interface id>]\n"
14507          "       Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
14508          "  to restore a channel to service, with optional interface id\n"
14509          "  as agreed upon with remote switch operator\n";
14510       return NULL;
14511    case CLI_GENERATE:
14512       return NULL;
14513    }
14514    return handle_pri_service_generic(e, cmd, a, 0);
14515 }
14516 
14517 static char *handle_pri_service_disable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14518 {
14519    switch (cmd) {
14520    case CLI_INIT:
14521       e->command = "pri service disable channel";
14522       e->usage =
14523          "Usage: pri service disable channel <chan num> [<interface id>]\n"
14524          "  Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
14525          "  to remove a channel from service, with optional interface id\n"
14526          "  as agreed upon with remote switch operator\n";
14527       return NULL;
14528    case CLI_GENERATE:
14529       return NULL;
14530    }
14531    return handle_pri_service_generic(e, cmd, a, 2);
14532 }
14533 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14534 #endif   /* defined(HAVE_PRI) */
14535 
14536 #if defined(HAVE_PRI)
14537 static char *handle_pri_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14538 {
14539    int span;
14540 
14541    switch (cmd) {
14542    case CLI_INIT:
14543       e->command = "pri show channels";
14544       e->usage =
14545          "Usage: pri show channels\n"
14546          "       Displays PRI channel information such as the current mapping\n"
14547          "       of DAHDI B channels to Asterisk channel names and which calls\n"
14548          "       are on hold or call-waiting.  Calls on hold or call-waiting\n"
14549          "       are not associated with any B channel.\n";
14550       return NULL;
14551    case CLI_GENERATE:
14552       return NULL;
14553    }
14554 
14555    if (a->argc != 3)
14556       return CLI_SHOWUSAGE;
14557 
14558    sig_pri_cli_show_channels_header(a->fd);
14559    for (span = 0; span < NUM_SPANS; ++span) {
14560       if (pris[span].pri.pri) {
14561          sig_pri_cli_show_channels(a->fd, &pris[span].pri);
14562       }
14563    }
14564    return CLI_SUCCESS;
14565 }
14566 #endif   /* defined(HAVE_PRI) */
14567 
14568 #if defined(HAVE_PRI)
14569 static char *handle_pri_show_spans(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14570 {
14571    int span;
14572 
14573    switch (cmd) {
14574    case CLI_INIT:
14575       e->command = "pri show spans";
14576       e->usage =
14577          "Usage: pri show spans\n"
14578          "       Displays PRI span information\n";
14579       return NULL;
14580    case CLI_GENERATE:
14581       return NULL;
14582    }
14583 
14584    if (a->argc != 3)
14585       return CLI_SHOWUSAGE;
14586 
14587    for (span = 0; span < NUM_SPANS; span++) {
14588       if (pris[span].pri.pri) {
14589          sig_pri_cli_show_spans(a->fd, span + 1, &pris[span].pri);
14590       }
14591    }
14592    return CLI_SUCCESS;
14593 }
14594 #endif   /* defined(HAVE_PRI) */
14595 
14596 #if defined(HAVE_PRI)
14597 static char *handle_pri_show_span(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14598 {
14599    int span;
14600 
14601    switch (cmd) {
14602    case CLI_INIT:
14603       e->command = "pri show span";
14604       e->usage =
14605          "Usage: pri show span <span>\n"
14606          "       Displays PRI Information on a given PRI span\n";
14607       return NULL;
14608    case CLI_GENERATE:
14609       return complete_span_4(a->line, a->word, a->pos, a->n);
14610    }
14611 
14612    if (a->argc < 4)
14613       return CLI_SHOWUSAGE;
14614    span = atoi(a->argv[3]);
14615    if ((span < 1) || (span > NUM_SPANS)) {
14616       ast_cli(a->fd, "Invalid span '%s'.  Should be a number from %d to %d\n", a->argv[3], 1, NUM_SPANS);
14617       return CLI_SUCCESS;
14618    }
14619    if (!pris[span-1].pri.pri) {
14620       ast_cli(a->fd, "No PRI running on span %d\n", span);
14621       return CLI_SUCCESS;
14622    }
14623 
14624    sig_pri_cli_show_span(a->fd, pris[span-1].dchannels, &pris[span-1].pri);
14625 
14626    return CLI_SUCCESS;
14627 }
14628 #endif   /* defined(HAVE_PRI) */
14629 
14630 #if defined(HAVE_PRI)
14631 static char *handle_pri_show_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14632 {
14633    int x;
14634    int span;
14635    int count=0;
14636    int debug;
14637 
14638    switch (cmd) {
14639    case CLI_INIT:
14640       e->command = "pri show debug";
14641       e->usage =
14642          "Usage: pri show debug\n"
14643          "  Show the debug state of pri spans\n";
14644       return NULL;
14645    case CLI_GENERATE:
14646       return NULL;
14647    }
14648 
14649    for (span = 0; span < NUM_SPANS; span++) {
14650       if (pris[span].pri.pri) {
14651          for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14652             if (pris[span].pri.dchans[x]) {
14653                debug = pri_get_debug(pris[span].pri.dchans[x]);
14654                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" );
14655                count++;
14656             }
14657          }
14658       }
14659 
14660    }
14661    ast_mutex_lock(&pridebugfdlock);
14662    if (pridebugfd >= 0)
14663       ast_cli(a->fd, "Logging PRI debug to file %s\n", pridebugfilename);
14664    ast_mutex_unlock(&pridebugfdlock);
14665 
14666    if (!count)
14667       ast_cli(a->fd, "No PRI running\n");
14668    return CLI_SUCCESS;
14669 }
14670 #endif   /* defined(HAVE_PRI) */
14671 
14672 #if defined(HAVE_PRI)
14673 static char *handle_pri_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14674 {
14675    switch (cmd) {
14676    case CLI_INIT:
14677       e->command = "pri show version";
14678       e->usage =
14679          "Usage: pri show version\n"
14680          "Show libpri version information\n";
14681       return NULL;
14682    case CLI_GENERATE:
14683       return NULL;
14684    }
14685 
14686    ast_cli(a->fd, "libpri version: %s\n", pri_get_version());
14687 
14688    return CLI_SUCCESS;
14689 }
14690 #endif   /* defined(HAVE_PRI) */
14691 
14692 #if defined(HAVE_PRI)
14693 static struct ast_cli_entry dahdi_pri_cli[] = {
14694    AST_CLI_DEFINE(handle_pri_debug, "Enables PRI debugging on a span"),
14695 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14696    AST_CLI_DEFINE(handle_pri_service_enable_channel, "Return a channel to service"),
14697    AST_CLI_DEFINE(handle_pri_service_disable_channel, "Remove a channel from service"),
14698 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14699    AST_CLI_DEFINE(handle_pri_show_channels, "Displays PRI channel information"),
14700    AST_CLI_DEFINE(handle_pri_show_spans, "Displays PRI span information"),
14701    AST_CLI_DEFINE(handle_pri_show_span, "Displays PRI span information"),
14702    AST_CLI_DEFINE(handle_pri_show_debug, "Displays current PRI debug settings"),
14703    AST_CLI_DEFINE(handle_pri_set_debug_file, "Sends PRI debug output to the specified file"),
14704    AST_CLI_DEFINE(handle_pri_version, "Displays libpri version"),
14705 };
14706 #endif   /* defined(HAVE_PRI) */
14707 
14708 #ifdef HAVE_OPENR2
14709 
14710 static char *handle_mfcr2_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14711 {
14712    switch (cmd) {
14713    case CLI_INIT:
14714       e->command = "mfcr2 show version";
14715       e->usage =
14716          "Usage: mfcr2 show version\n"
14717          "       Shows the version of the OpenR2 library being used.\n";
14718       return NULL;
14719    case CLI_GENERATE:
14720       return NULL;
14721    }
14722    ast_cli(a->fd, "OpenR2 version: %s, revision: %s\n", openr2_get_version(), openr2_get_revision());
14723    return CLI_SUCCESS;
14724 }
14725 
14726 static char *handle_mfcr2_show_variants(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14727 {
14728 #define FORMAT "%4s %40s\n"
14729    int i = 0;
14730    int numvariants = 0;
14731    const openr2_variant_entry_t *variants;
14732    switch (cmd) {
14733    case CLI_INIT:
14734       e->command = "mfcr2 show variants";
14735       e->usage =
14736          "Usage: mfcr2 show variants\n"
14737          "       Shows the list of MFC/R2 variants supported.\n";
14738       return NULL;
14739    case CLI_GENERATE:
14740       return NULL;
14741    }
14742    if (!(variants = openr2_proto_get_variant_list(&numvariants))) {
14743       ast_cli(a->fd, "Failed to get list of variants.\n");
14744       return CLI_FAILURE;
14745    }
14746    ast_cli(a->fd, FORMAT, "Variant Code", "Country");
14747    for (i = 0; i < numvariants; i++) {
14748       ast_cli(a->fd, FORMAT, variants[i].name, variants[i].country);
14749    }
14750    return CLI_SUCCESS;
14751 #undef FORMAT
14752 }
14753 
14754 static char *handle_mfcr2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14755 {
14756 #define FORMAT "%4s %-7.7s %-7.7s %-8.8s %-9.9s %-16.16s %-8.8s %-8.8s\n"
14757    int filtertype = 0;
14758    int targetnum = 0;
14759    char channo[5];
14760    char anino[5];
14761    char dnisno[5];
14762    struct dahdi_pvt *p;
14763    openr2_context_t *r2context;
14764    openr2_variant_t r2variant;
14765    switch (cmd) {
14766    case CLI_INIT:
14767       e->command = "mfcr2 show channels [group|context]";
14768       e->usage =
14769          "Usage: mfcr2 show channels [group <group> | context <context>]\n"
14770          "       Shows the DAHDI channels configured with MFC/R2 signaling.\n";
14771       return NULL;
14772    case CLI_GENERATE:
14773       return NULL;
14774    }
14775    if (!((a->argc == 3) || (a->argc == 5))) {
14776       return CLI_SHOWUSAGE;
14777    }
14778    if (a->argc == 5) {
14779       if (!strcasecmp(a->argv[3], "group")) {
14780          targetnum = atoi(a->argv[4]);
14781          if ((targetnum < 0) || (targetnum > 63))
14782             return CLI_SHOWUSAGE;
14783          targetnum = 1 << targetnum;
14784          filtertype = 1;
14785       } else if (!strcasecmp(a->argv[3], "context")) {
14786          filtertype = 2;
14787       } else {
14788          return CLI_SHOWUSAGE;
14789       }
14790    }
14791    ast_cli(a->fd, FORMAT, "Chan", "Variant", "Max ANI", "Max DNIS", "ANI First", "Immediate Accept", "Tx CAS", "Rx CAS");
14792    ast_mutex_lock(&iflock);
14793    for (p = iflist; p; p = p->next) {
14794       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14795          continue;
14796       }
14797       if (filtertype) {
14798          switch(filtertype) {
14799          case 1: /* mfcr2 show channels group <group> */
14800             if (p->group != targetnum) {
14801                continue;
14802             }
14803             break;
14804          case 2: /* mfcr2 show channels context <context> */
14805             if (strcasecmp(p->context, a->argv[4])) {
14806                continue;
14807             }
14808             break;
14809          default:
14810             ;
14811          }
14812       }
14813       r2context = openr2_chan_get_context(p->r2chan);
14814       r2variant = openr2_context_get_variant(r2context);
14815       snprintf(channo, sizeof(channo), "%d", p->channel);
14816       snprintf(anino, sizeof(anino), "%d", openr2_context_get_max_ani(r2context));
14817       snprintf(dnisno, sizeof(dnisno), "%d", openr2_context_get_max_dnis(r2context));
14818       ast_cli(a->fd, FORMAT, channo, openr2_proto_get_variant_string(r2variant),
14819             anino, dnisno, openr2_context_get_ani_first(r2context) ? "Yes" : "No",
14820             openr2_context_get_immediate_accept(r2context) ? "Yes" : "No",
14821             openr2_chan_get_tx_cas_string(p->r2chan), openr2_chan_get_rx_cas_string(p->r2chan));
14822    }
14823    ast_mutex_unlock(&iflock);
14824    return CLI_SUCCESS;
14825 #undef FORMAT
14826 }
14827 
14828 static char *handle_mfcr2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14829 {
14830    struct dahdi_pvt *p = NULL;
14831    int channo = 0;
14832    char *toklevel = NULL;
14833    char *saveptr = NULL;
14834    char *logval = NULL;
14835    openr2_log_level_t loglevel = OR2_LOG_NOTHING;
14836    openr2_log_level_t tmplevel = OR2_LOG_NOTHING;
14837    switch (cmd) {
14838    case CLI_INIT:
14839       e->command = "mfcr2 set debug";
14840       e->usage =
14841          "Usage: mfcr2 set debug <loglevel> <channel>\n"
14842          "       Set a new logging level for the specified channel.\n"
14843          "       If no channel is specified the logging level will be applied to all channels.\n";
14844       return NULL;
14845    case CLI_GENERATE:
14846       return NULL;
14847    }
14848    if (a->argc < 4) {
14849       return CLI_SHOWUSAGE;
14850    }
14851    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14852    logval = ast_strdupa(a->argv[3]);
14853    toklevel = strtok_r(logval, ",", &saveptr);
14854    if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14855       ast_cli(a->fd, "Invalid MFC/R2 logging level '%s'.\n", a->argv[3]);
14856       return CLI_FAILURE;
14857    } else if (OR2_LOG_NOTHING == tmplevel) {
14858       loglevel = tmplevel;
14859    } else {
14860       loglevel |= tmplevel;
14861       while ((toklevel = strtok_r(NULL, ",", &saveptr))) {
14862          if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14863             ast_cli(a->fd, "Ignoring invalid logging level: '%s'.\n", toklevel);
14864             continue;
14865          }
14866          loglevel |= tmplevel;
14867       }
14868    }
14869    ast_mutex_lock(&iflock);
14870    for (p = iflist; p; p = p->next) {
14871       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14872          continue;
14873       }
14874       if ((channo != -1) && (p->channel != channo )) {
14875          continue;
14876       }
14877       openr2_chan_set_log_level(p->r2chan, loglevel);
14878       if (channo != -1) {
14879          ast_cli(a->fd, "MFC/R2 debugging set to '%s' for channel %d.\n", a->argv[3], p->channel);
14880          break;
14881       }
14882    }
14883    if ((channo != -1) && !p) {
14884       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14885    }
14886    if (channo == -1) {
14887       ast_cli(a->fd, "MFC/R2 debugging set to '%s' for all channels.\n", a->argv[3]);
14888    }
14889    ast_mutex_unlock(&iflock);
14890    return CLI_SUCCESS;
14891 }
14892 
14893 static char *handle_mfcr2_call_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14894 {
14895    struct dahdi_pvt *p = NULL;
14896    int channo = 0;
14897    switch (cmd) {
14898    case CLI_INIT:
14899       e->command = "mfcr2 call files [on|off]";
14900       e->usage =
14901          "Usage: mfcr2 call files [on|off] <channel>\n"
14902          "       Enable call files creation on the specified channel.\n"
14903          "       If no channel is specified call files creation policy will be applied to all channels.\n";
14904       return NULL;
14905    case CLI_GENERATE:
14906       return NULL;
14907    }
14908    if (a->argc < 4) {
14909       return CLI_SHOWUSAGE;
14910    }
14911    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14912    ast_mutex_lock(&iflock);
14913    for (p = iflist; p; p = p->next) {
14914       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14915          continue;
14916       }
14917       if ((channo != -1) && (p->channel != channo )) {
14918          continue;
14919       }
14920       if (ast_true(a->argv[3])) {
14921          openr2_chan_enable_call_files(p->r2chan);
14922       } else {
14923          openr2_chan_disable_call_files(p->r2chan);
14924       }
14925       if (channo != -1) {
14926          if (ast_true(a->argv[3])) {
14927             ast_cli(a->fd, "MFC/R2 call files enabled for channel %d.\n", p->channel);
14928          } else {
14929             ast_cli(a->fd, "MFC/R2 call files disabled for channel %d.\n", p->channel);
14930          }
14931          break;
14932       }
14933    }
14934    if ((channo != -1) && !p) {
14935       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14936    }
14937    if (channo == -1) {
14938       if (ast_true(a->argv[3])) {
14939          ast_cli(a->fd, "MFC/R2 Call files enabled for all channels.\n");
14940       } else {
14941          ast_cli(a->fd, "MFC/R2 Call files disabled for all channels.\n");
14942       }
14943    }
14944    ast_mutex_unlock(&iflock);
14945    return CLI_SUCCESS;
14946 }
14947 
14948 static char *handle_mfcr2_set_idle(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14949 {
14950    struct dahdi_pvt *p = NULL;
14951    int channo = 0;
14952    switch (cmd) {
14953    case CLI_INIT:
14954       e->command = "mfcr2 set idle";
14955       e->usage =
14956          "Usage: mfcr2 set idle <channel>\n"
14957          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14958          "       Force the given channel into IDLE state.\n"
14959          "       If no channel is specified, all channels will be set to IDLE.\n";
14960       return NULL;
14961    case CLI_GENERATE:
14962       return NULL;
14963    }
14964    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14965    ast_mutex_lock(&iflock);
14966    for (p = iflist; p; p = p->next) {
14967       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14968          continue;
14969       }
14970       if ((channo != -1) && (p->channel != channo )) {
14971          continue;
14972       }
14973       openr2_chan_set_idle(p->r2chan);
14974       ast_mutex_lock(&p->lock);
14975       p->locallyblocked = 0;
14976       p->mfcr2call = 0;
14977       ast_mutex_unlock(&p->lock);
14978       if (channo != -1) {
14979          break;
14980       }
14981    }
14982    if ((channo != -1) && !p) {
14983       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14984    }
14985    ast_mutex_unlock(&iflock);
14986    return CLI_SUCCESS;
14987 }
14988 
14989 static char *handle_mfcr2_set_blocked(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14990 {
14991    struct dahdi_pvt *p = NULL;
14992    int channo = 0;
14993    switch (cmd) {
14994    case CLI_INIT:
14995       e->command = "mfcr2 set blocked";
14996       e->usage =
14997          "Usage: mfcr2 set blocked <channel>\n"
14998          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14999          "       Force the given channel into BLOCKED state.\n"
15000          "       If no channel is specified, all channels will be set to BLOCKED.\n";
15001       return NULL;
15002    case CLI_GENERATE:
15003       return NULL;
15004    }
15005    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
15006    ast_mutex_lock(&iflock);
15007    for (p = iflist; p; p = p->next) {
15008       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
15009          continue;
15010       }
15011       if ((channo != -1) && (p->channel != channo )) {
15012          continue;
15013       }
15014       openr2_chan_set_blocked(p->r2chan);
15015       ast_mutex_lock(&p->lock);
15016       p->locallyblocked = 1;
15017       ast_mutex_unlock(&p->lock);
15018       if (channo != -1) {
15019          break;
15020       }
15021    }
15022    if ((channo != -1) && !p) {
15023       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
15024    }
15025    ast_mutex_unlock(&iflock);
15026    return CLI_SUCCESS;
15027 }
15028 
15029 static struct ast_cli_entry dahdi_mfcr2_cli[] = {
15030    AST_CLI_DEFINE(handle_mfcr2_version, "Show OpenR2 library version"),
15031    AST_CLI_DEFINE(handle_mfcr2_show_variants, "Show supported MFC/R2 variants"),
15032    AST_CLI_DEFINE(handle_mfcr2_show_channels, "Show MFC/R2 channels"),
15033    AST_CLI_DEFINE(handle_mfcr2_set_debug, "Set MFC/R2 channel logging level"),
15034    AST_CLI_DEFINE(handle_mfcr2_call_files, "Enable/Disable MFC/R2 call files"),
15035    AST_CLI_DEFINE(handle_mfcr2_set_idle, "Reset MFC/R2 channel forcing it to IDLE"),
15036    AST_CLI_DEFINE(handle_mfcr2_set_blocked, "Reset MFC/R2 channel forcing it to BLOCKED"),
15037 };
15038 
15039 #endif /* HAVE_OPENR2 */
15040 
15041 static char *dahdi_destroy_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15042 {
15043    int channel;
15044    int ret;
15045    switch (cmd) {
15046    case CLI_INIT:
15047       e->command = "dahdi destroy channel";
15048       e->usage =
15049          "Usage: dahdi destroy channel <chan num>\n"
15050          "  DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.  Immediately removes a given channel, whether it is in use or not\n";
15051       return NULL;
15052    case CLI_GENERATE:
15053       return NULL;
15054    }
15055    if (a->argc != 4)
15056       return CLI_SHOWUSAGE;
15057 
15058    channel = atoi(a->argv[3]);
15059    ret = dahdi_destroy_channel_bynum(channel);
15060    return ( RESULT_SUCCESS == ret ) ? CLI_SUCCESS : CLI_FAILURE;
15061 }
15062 
15063 static void dahdi_softhangup_all(void)
15064 {
15065    struct dahdi_pvt *p;
15066 retry:
15067    ast_mutex_lock(&iflock);
15068    for (p = iflist; p; p = p->next) {
15069       ast_mutex_lock(&p->lock);
15070       if (p->owner && !p->restartpending) {
15071          if (ast_channel_trylock(p->owner)) {
15072             if (option_debug > 2)
15073                ast_verbose("Avoiding deadlock\n");
15074             /* Avoid deadlock since you're not supposed to lock iflock or pvt before a channel */
15075             ast_mutex_unlock(&p->lock);
15076             ast_mutex_unlock(&iflock);
15077             goto retry;
15078          }
15079          if (option_debug > 2)
15080             ast_verbose("Softhanging up on %s\n", p->owner->name);
15081          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_EXPLICIT);
15082          p->restartpending = 1;
15083          num_restart_pending++;
15084          ast_channel_unlock(p->owner);
15085       }
15086       ast_mutex_unlock(&p->lock);
15087    }
15088    ast_mutex_unlock(&iflock);
15089 }
15090 
15091 static int setup_dahdi(int reload);
15092 static int dahdi_restart(void)
15093 {
15094 #if defined(HAVE_PRI) || defined(HAVE_SS7)
15095    int i, j;
15096 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
15097    int cancel_code;
15098    struct dahdi_pvt *p;
15099 
15100    ast_mutex_lock(&restart_lock);
15101    ast_verb(1, "Destroying channels and reloading DAHDI configuration.\n");
15102    dahdi_softhangup_all();
15103    ast_verb(4, "Initial softhangup of all DAHDI channels complete.\n");
15104 #ifdef HAVE_OPENR2
15105    dahdi_r2_destroy_links();
15106 #endif
15107 
15108 #if defined(HAVE_PRI)
15109    for (i = 0; i < NUM_SPANS; i++) {
15110       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL)) {
15111          cancel_code = pthread_cancel(pris[i].pri.master);
15112          pthread_kill(pris[i].pri.master, SIGURG);
15113          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);
15114          pthread_join(pris[i].pri.master, NULL);
15115          ast_debug(4, "Joined thread of span %d\n", i);
15116       }
15117    }
15118 #endif
15119 
15120 #if defined(HAVE_SS7)
15121    for (i = 0; i < NUM_SPANS; i++) {
15122       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL)) {
15123          cancel_code = pthread_cancel(linksets[i].ss7.master);
15124          pthread_kill(linksets[i].ss7.master, SIGURG);
15125          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);
15126          pthread_join(linksets[i].ss7.master, NULL);
15127          ast_debug(4, "Joined thread of span %d\n", i);
15128       }
15129    }
15130 #endif   /* defined(HAVE_SS7) */
15131 
15132    ast_mutex_lock(&monlock);
15133    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
15134       cancel_code = pthread_cancel(monitor_thread);
15135       pthread_kill(monitor_thread, SIGURG);
15136       ast_debug(4, "Waiting to join monitor thread with pid=%p, cancel_code=%d\n", (void *) monitor_thread, cancel_code);
15137       pthread_join(monitor_thread, NULL);
15138       ast_debug(4, "Joined monitor thread\n");
15139    }
15140    monitor_thread = AST_PTHREADT_NULL; /* prepare to restart thread in setup_dahdi once channels are reconfigured */
15141 
15142    ast_mutex_lock(&ss_thread_lock);
15143    while (ss_thread_count > 0) { /* let ss_threads finish and run dahdi_hangup before dahvi_pvts are destroyed */
15144       int x = DAHDI_FLASH;
15145       ast_debug(3, "Waiting on %d analog_ss_thread(s) to finish\n", ss_thread_count);
15146 
15147       ast_mutex_lock(&iflock);
15148       for (p = iflist; p; p = p->next) {
15149          if (p->owner) {
15150             /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
15151             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
15152          }
15153       }
15154       ast_mutex_unlock(&iflock);
15155       ast_cond_wait(&ss_thread_complete, &ss_thread_lock);
15156    }
15157 
15158    /* ensure any created channels before monitor threads were stopped are hungup */
15159    dahdi_softhangup_all();
15160    ast_verb(4, "Final softhangup of all DAHDI channels complete.\n");
15161    destroy_all_channels();
15162    ast_debug(1, "Channels destroyed. Now re-reading config. %d active channels remaining.\n", ast_active_channels());
15163 
15164    ast_mutex_unlock(&monlock);
15165 
15166 #ifdef HAVE_PRI
15167    for (i = 0; i < NUM_SPANS; i++) {
15168       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++)
15169          dahdi_close_pri_fd(&(pris[i]), j);
15170    }
15171 
15172    memset(pris, 0, sizeof(pris));
15173    for (i = 0; i < NUM_SPANS; i++) {
15174       sig_pri_init_pri(&pris[i].pri);
15175    }
15176    pri_set_error(dahdi_pri_error);
15177    pri_set_message(dahdi_pri_message);
15178 #endif
15179 #if defined(HAVE_SS7)
15180    for (i = 0; i < NUM_SPANS; i++) {
15181       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++)
15182          dahdi_close_ss7_fd(&(linksets[i]), j);
15183    }
15184 
15185    memset(linksets, 0, sizeof(linksets));
15186    for (i = 0; i < NUM_SPANS; i++) {
15187       sig_ss7_init_linkset(&linksets[i].ss7);
15188    }
15189    ss7_set_error(dahdi_ss7_error);
15190    ss7_set_message(dahdi_ss7_message);
15191 #endif   /* defined(HAVE_SS7) */
15192 
15193    if (setup_dahdi(2) != 0) {
15194       ast_log(LOG_WARNING, "Reload channels from dahdi config failed!\n");
15195       ast_mutex_unlock(&ss_thread_lock);
15196       return 1;
15197    }
15198    ast_mutex_unlock(&ss_thread_lock);
15199    ast_mutex_unlock(&restart_lock);
15200    return 0;
15201 }
15202 
15203 static char *dahdi_restart_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15204 {
15205    switch (cmd) {
15206    case CLI_INIT:
15207       e->command = "dahdi restart";
15208       e->usage =
15209          "Usage: dahdi restart\n"
15210          "  Restarts the DAHDI channels: destroys them all and then\n"
15211          "  re-reads them from chan_dahdi.conf.\n"
15212          "  Note that this will STOP any running CALL on DAHDI channels.\n"
15213          "";
15214       return NULL;
15215    case CLI_GENERATE:
15216       return NULL;
15217    }
15218    if (a->argc != 2)
15219       return CLI_SHOWUSAGE;
15220 
15221    if (dahdi_restart() != 0)
15222       return CLI_FAILURE;
15223    return CLI_SUCCESS;
15224 }
15225 
15226 static int action_dahdirestart(struct mansession *s, const struct message *m)
15227 {
15228    if (dahdi_restart() != 0) {
15229       astman_send_error(s, m, "Failed rereading DAHDI configuration");
15230       return 1;
15231    }
15232    astman_send_ack(s, m, "DAHDIRestart: Success");
15233    return 0;
15234 }
15235 
15236 static char *dahdi_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15237 {
15238 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
15239 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
15240    unsigned int targetnum = 0;
15241    int filtertype = 0;
15242    struct dahdi_pvt *tmp = NULL;
15243    char tmps[20] = "";
15244    char statestr[20] = "";
15245    char blockstr[20] = "";
15246 
15247    switch (cmd) {
15248    case CLI_INIT:
15249       e->command = "dahdi show channels [group|context]";
15250       e->usage =
15251          "Usage: dahdi show channels [ group <group> | context <context> ]\n"
15252          "  Shows a list of available channels with optional filtering\n"
15253          "  <group> must be a number between 0 and 63\n";
15254       return NULL;
15255    case CLI_GENERATE:
15256       return NULL;
15257    }
15258 
15259    /* syntax: dahdi show channels [ group <group> | context <context> ] */
15260 
15261    if (!((a->argc == 3) || (a->argc == 5)))
15262       return CLI_SHOWUSAGE;
15263 
15264    if (a->argc == 5) {
15265       if (!strcasecmp(a->argv[3], "group")) {
15266          targetnum = atoi(a->argv[4]);
15267          if ((targetnum < 0) || (targetnum > 63))
15268             return CLI_SHOWUSAGE;
15269          targetnum = 1 << targetnum;
15270          filtertype = 1;
15271       } else if (!strcasecmp(a->argv[3], "context")) {
15272          filtertype = 2;
15273       }
15274    }
15275 
15276    ast_cli(a->fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret", "Blocked", "State");
15277    ast_mutex_lock(&iflock);
15278    for (tmp = iflist; tmp; tmp = tmp->next) {
15279       if (filtertype) {
15280          switch(filtertype) {
15281          case 1: /* dahdi show channels group <group> */
15282             if (!(tmp->group & targetnum)) {
15283                continue;
15284             }
15285             break;
15286          case 2: /* dahdi show channels context <context> */
15287             if (strcasecmp(tmp->context, a->argv[4])) {
15288                continue;
15289             }
15290             break;
15291          default:
15292             break;
15293          }
15294       }
15295       if (tmp->channel > 0) {
15296          snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
15297       } else
15298          ast_copy_string(tmps, "pseudo", sizeof(tmps));
15299 
15300       if (tmp->locallyblocked)
15301          blockstr[0] = 'L';
15302       else
15303          blockstr[0] = ' ';
15304 
15305       if (tmp->remotelyblocked)
15306          blockstr[1] = 'R';
15307       else
15308          blockstr[1] = ' ';
15309 
15310       blockstr[2] = '\0';
15311 
15312       snprintf(statestr, sizeof(statestr), "%s", "In Service");
15313 
15314       ast_cli(a->fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret, blockstr, statestr);
15315    }
15316    ast_mutex_unlock(&iflock);
15317    return CLI_SUCCESS;
15318 #undef FORMAT
15319 #undef FORMAT2
15320 }
15321 
15322 static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15323 {
15324    int channel;
15325    struct dahdi_pvt *tmp = NULL;
15326    struct dahdi_confinfo ci;
15327    struct dahdi_params ps;
15328    int x;
15329 
15330    switch (cmd) {
15331    case CLI_INIT:
15332       e->command = "dahdi show channel";
15333       e->usage =
15334          "Usage: dahdi show channel <chan num>\n"
15335          "  Detailed information about a given channel\n";
15336       return NULL;
15337    case CLI_GENERATE:
15338       return NULL;
15339    }
15340 
15341    if (a->argc != 4)
15342       return CLI_SHOWUSAGE;
15343 
15344    channel = atoi(a->argv[3]);
15345 
15346    ast_mutex_lock(&iflock);
15347    for (tmp = iflist; tmp; tmp = tmp->next) {
15348       if (tmp->channel == channel) {
15349          ast_cli(a->fd, "Channel: %d\n", tmp->channel);
15350          ast_cli(a->fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].dfd);
15351          ast_cli(a->fd, "Span: %d\n", tmp->span);
15352          ast_cli(a->fd, "Extension: %s\n", tmp->exten);
15353          ast_cli(a->fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
15354          ast_cli(a->fd, "Context: %s\n", tmp->context);
15355          ast_cli(a->fd, "Caller ID: %s\n", tmp->cid_num);
15356          ast_cli(a->fd, "Calling TON: %d\n", tmp->cid_ton);
15357 #if defined(HAVE_PRI)
15358 #if defined(HAVE_PRI_SUBADDR)
15359          ast_cli(a->fd, "Caller ID subaddress: %s\n", tmp->cid_subaddr);
15360 #endif   /* defined(HAVE_PRI_SUBADDR) */
15361 #endif   /* defined(HAVE_PRI) */
15362          ast_cli(a->fd, "Caller ID name: %s\n", tmp->cid_name);
15363          ast_cli(a->fd, "Mailbox: %s\n", S_OR(tmp->mailbox, "none"));
15364          if (tmp->vars) {
15365             struct ast_variable *v;
15366             ast_cli(a->fd, "Variables:\n");
15367             for (v = tmp->vars ; v ; v = v->next)
15368                ast_cli(a->fd, "       %s = %s\n", v->name, v->value);
15369          }
15370          ast_cli(a->fd, "Destroy: %d\n", tmp->destroy);
15371          ast_cli(a->fd, "InAlarm: %d\n", tmp->inalarm);
15372          ast_cli(a->fd, "Signalling Type: %s\n", sig2str(tmp->sig));
15373          ast_cli(a->fd, "Radio: %d\n", tmp->radio);
15374          ast_cli(a->fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
15375          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)" : "");
15376          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)" : "");
15377          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)" : "");
15378          ast_cli(a->fd, "Confno: %d\n", tmp->confno);
15379          ast_cli(a->fd, "Propagated Conference: %d\n", tmp->propconfno);
15380          ast_cli(a->fd, "Real in conference: %d\n", tmp->inconference);
15381          ast_cli(a->fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
15382          ast_cli(a->fd, "Busy Detection: %s\n", tmp->busydetect ? "yes" : "no");
15383          if (tmp->busydetect) {
15384 #if defined(BUSYDETECT_TONEONLY)
15385             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_TONEONLY\n");
15386 #elif defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
15387             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_COMPARE_TONE_AND_SILENCE\n");
15388 #endif
15389 #ifdef BUSYDETECT_DEBUG
15390             ast_cli(a->fd, "    Busy Detector Debug: Enabled\n");
15391 #endif
15392             ast_cli(a->fd, "    Busy Count: %d\n", tmp->busycount);
15393             ast_cli(a->fd, "    Busy Pattern: %d,%d\n", tmp->busy_tonelength, tmp->busy_quietlength);
15394          }
15395          ast_cli(a->fd, "TDD: %s\n", tmp->tdd ? "yes" : "no");
15396          ast_cli(a->fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
15397          ast_cli(a->fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
15398          ast_cli(a->fd, "Default law: %s\n", tmp->law_default == DAHDI_LAW_MULAW ? "ulaw" : tmp->law_default == DAHDI_LAW_ALAW ? "alaw" : "unknown");
15399          ast_cli(a->fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
15400          ast_cli(a->fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
15401          ast_cli(a->fd, "Gains (RX/TX): %.2f/%.2f\n", tmp->rxgain, tmp->txgain);
15402          ast_cli(a->fd, "Dynamic Range Compression (RX/TX): %.2f/%.2f\n", tmp->rxdrc, tmp->txdrc);
15403          ast_cli(a->fd, "DND: %s\n", dahdi_dnd(tmp, -1) ? "yes" : "no");
15404          ast_cli(a->fd, "Echo Cancellation:\n");
15405 
15406          if (tmp->echocancel.head.tap_length) {
15407             ast_cli(a->fd, "\t%d taps\n", tmp->echocancel.head.tap_length);
15408             for (x = 0; x < tmp->echocancel.head.param_count; x++) {
15409                ast_cli(a->fd, "\t\t%s: %ud\n", tmp->echocancel.params[x].name, tmp->echocancel.params[x].value);
15410             }
15411             ast_cli(a->fd, "\t%scurrently %s\n", tmp->echocanbridged ? "" : "(unless TDM bridged) ", tmp->echocanon ? "ON" : "OFF");
15412          } else {
15413             ast_cli(a->fd, "\tnone\n");
15414          }
15415          ast_cli(a->fd, "Wait for dialtone: %dms\n", tmp->waitfordialtone);
15416          if (tmp->master)
15417             ast_cli(a->fd, "Master Channel: %d\n", tmp->master->channel);
15418          for (x = 0; x < MAX_SLAVES; x++) {
15419             if (tmp->slaves[x])
15420                ast_cli(a->fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
15421          }
15422 #ifdef HAVE_OPENR2
15423          if (tmp->mfcr2) {
15424             char calldir[OR2_MAX_PATH];
15425             openr2_context_t *r2context = openr2_chan_get_context(tmp->r2chan);
15426             openr2_variant_t r2variant = openr2_context_get_variant(r2context);
15427             ast_cli(a->fd, "MFC/R2 MF State: %s\n", openr2_chan_get_mf_state_string(tmp->r2chan));
15428             ast_cli(a->fd, "MFC/R2 MF Group: %s\n", openr2_chan_get_mf_group_string(tmp->r2chan));
15429             ast_cli(a->fd, "MFC/R2 State: %s\n", openr2_chan_get_r2_state_string(tmp->r2chan));
15430             ast_cli(a->fd, "MFC/R2 Call State: %s\n", openr2_chan_get_call_state_string(tmp->r2chan));
15431             ast_cli(a->fd, "MFC/R2 Call Files Enabled: %s\n", openr2_chan_get_call_files_enabled(tmp->r2chan) ? "Yes" : "No");
15432             ast_cli(a->fd, "MFC/R2 Variant: %s\n", openr2_proto_get_variant_string(r2variant));
15433             ast_cli(a->fd, "MFC/R2 Max ANI: %d\n", openr2_context_get_max_ani(r2context));
15434             ast_cli(a->fd, "MFC/R2 Max DNIS: %d\n", openr2_context_get_max_dnis(r2context));
15435             ast_cli(a->fd, "MFC/R2 Get ANI First: %s\n", openr2_context_get_ani_first(r2context) ? "Yes" : "No");
15436 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
15437             ast_cli(a->fd, "MFC/R2 Skip Category Request: %s\n", openr2_context_get_skip_category_request(r2context) ? "Yes" : "No");
15438 #endif
15439             ast_cli(a->fd, "MFC/R2 Immediate Accept: %s\n", openr2_context_get_immediate_accept(r2context) ? "Yes" : "No");
15440             ast_cli(a->fd, "MFC/R2 Accept on Offer: %s\n", tmp->mfcr2_accept_on_offer ? "Yes" : "No");
15441             ast_cli(a->fd, "MFC/R2 Charge Calls: %s\n", tmp->mfcr2_charge_calls ? "Yes" : "No");
15442             ast_cli(a->fd, "MFC/R2 Allow Collect Calls: %s\n", tmp->mfcr2_allow_collect_calls ? "Yes" : "No");
15443             ast_cli(a->fd, "MFC/R2 Forced Release: %s\n", tmp->mfcr2_forced_release ? "Yes" : "No");
15444             ast_cli(a->fd, "MFC/R2 MF Back Timeout: %dms\n", openr2_context_get_mf_back_timeout(r2context));
15445             ast_cli(a->fd, "MFC/R2 R2 Metering Pulse Timeout: %dms\n", openr2_context_get_metering_pulse_timeout(r2context));
15446             ast_cli(a->fd, "MFC/R2 Rx CAS: %s\n", openr2_chan_get_rx_cas_string(tmp->r2chan));
15447             ast_cli(a->fd, "MFC/R2 Tx CAS: %s\n", openr2_chan_get_tx_cas_string(tmp->r2chan));
15448             ast_cli(a->fd, "MFC/R2 MF Tx Signal: %d\n", openr2_chan_get_tx_mf_signal(tmp->r2chan));
15449             ast_cli(a->fd, "MFC/R2 MF Rx Signal: %d\n", openr2_chan_get_rx_mf_signal(tmp->r2chan));
15450             ast_cli(a->fd, "MFC/R2 Call Files Directory: %s\n", openr2_context_get_log_directory(r2context, calldir, sizeof(calldir)));
15451          }
15452 #endif
15453 #if defined(HAVE_SS7)
15454          if (tmp->ss7) {
15455             struct sig_ss7_chan *chan = tmp->sig_pvt;
15456 
15457             ast_cli(a->fd, "CIC: %d\n", chan->cic);
15458          }
15459 #endif   /* defined(HAVE_SS7) */
15460 #ifdef HAVE_PRI
15461          if (tmp->pri) {
15462             struct sig_pri_chan *chan = tmp->sig_pvt;
15463 
15464             ast_cli(a->fd, "PRI Flags: ");
15465             if (chan->resetting != SIG_PRI_RESET_IDLE) {
15466                ast_cli(a->fd, "Resetting=%d ", chan->resetting);
15467             }
15468             if (chan->call)
15469                ast_cli(a->fd, "Call ");
15470             if (chan->allocated) {
15471                ast_cli(a->fd, "Allocated ");
15472             }
15473             ast_cli(a->fd, "\n");
15474             if (tmp->logicalspan)
15475                ast_cli(a->fd, "PRI Logical Span: %d\n", tmp->logicalspan);
15476             else
15477                ast_cli(a->fd, "PRI Logical Span: Implicit\n");
15478          }
15479 #endif
15480          memset(&ci, 0, sizeof(ci));
15481          ps.channo = tmp->channel;
15482          if (tmp->subs[SUB_REAL].dfd > -1) {
15483             memset(&ci, 0, sizeof(ci));
15484             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
15485                ast_cli(a->fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
15486             }
15487             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONFMUTE, &x)) {
15488                ast_cli(a->fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
15489             }
15490             memset(&ps, 0, sizeof(ps));
15491             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
15492                ast_log(LOG_WARNING, "Failed to get parameters on channel %d: %s\n", tmp->channel, strerror(errno));
15493             } else {
15494                ast_cli(a->fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
15495             }
15496          }
15497          ast_mutex_unlock(&iflock);
15498          return CLI_SUCCESS;
15499       }
15500    }
15501    ast_mutex_unlock(&iflock);
15502 
15503    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15504    return CLI_FAILURE;
15505 }
15506 
15507 static char *handle_dahdi_show_cadences(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15508 {
15509    int i, j;
15510    switch (cmd) {
15511    case CLI_INIT:
15512       e->command = "dahdi show cadences";
15513       e->usage =
15514          "Usage: dahdi show cadences\n"
15515          "       Shows all cadences currently defined\n";
15516       return NULL;
15517    case CLI_GENERATE:
15518       return NULL;
15519    }
15520    for (i = 0; i < num_cadence; i++) {
15521       char output[1024];
15522       char tmp[16], tmp2[64];
15523       snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
15524       term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
15525 
15526       for (j = 0; j < 16; j++) {
15527          if (cadences[i].ringcadence[j] == 0)
15528             break;
15529          snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
15530          if (cidrings[i] * 2 - 1 == j)
15531             term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
15532          else
15533             term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
15534          if (j != 0)
15535             strncat(output, ",", sizeof(output) - strlen(output) - 1);
15536          strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
15537       }
15538       ast_cli(a->fd,"%s\n",output);
15539    }
15540    return CLI_SUCCESS;
15541 }
15542 
15543 /* Based on irqmiss.c */
15544 static char *dahdi_show_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15545 {
15546    #define FORMAT "%-40.40s %-7.7s %-6d %-6d %-6d %-3.3s %-4.4s %-8.8s %s\n"
15547    #define FORMAT2 "%-40.40s %-7.7s %-6.6s %-6.6s %-6.6s %-3.3s %-4.4s %-8.8s %s\n"
15548    int span;
15549    int res;
15550    char alarmstr[50];
15551 
15552    int ctl;
15553    struct dahdi_spaninfo s;
15554 
15555    switch (cmd) {
15556    case CLI_INIT:
15557       e->command = "dahdi show status";
15558       e->usage =
15559          "Usage: dahdi show status\n"
15560          "       Shows a list of DAHDI cards with status\n";
15561       return NULL;
15562    case CLI_GENERATE:
15563       return NULL;
15564    }
15565    ctl = open("/dev/dahdi/ctl", O_RDWR);
15566    if (ctl < 0) {
15567       ast_cli(a->fd, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
15568       return CLI_FAILURE;
15569    }
15570    ast_cli(a->fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC", "Framing", "Coding", "Options", "LBO");
15571 
15572    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
15573       s.spanno = span;
15574       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
15575       if (res) {
15576          continue;
15577       }
15578       alarmstr[0] = '\0';
15579       if (s.alarms > 0) {
15580          if (s.alarms & DAHDI_ALARM_BLUE)
15581             strcat(alarmstr, "BLU/");
15582          if (s.alarms & DAHDI_ALARM_YELLOW)
15583             strcat(alarmstr, "YEL/");
15584          if (s.alarms & DAHDI_ALARM_RED)
15585             strcat(alarmstr, "RED/");
15586          if (s.alarms & DAHDI_ALARM_LOOPBACK)
15587             strcat(alarmstr, "LB/");
15588          if (s.alarms & DAHDI_ALARM_RECOVER)
15589             strcat(alarmstr, "REC/");
15590          if (s.alarms & DAHDI_ALARM_NOTOPEN)
15591             strcat(alarmstr, "NOP/");
15592          if (!strlen(alarmstr))
15593             strcat(alarmstr, "UUU/");
15594          if (strlen(alarmstr)) {
15595             /* Strip trailing / */
15596             alarmstr[strlen(alarmstr) - 1] = '\0';
15597          }
15598       } else {
15599          if (s.numchans)
15600             strcpy(alarmstr, "OK");
15601          else
15602             strcpy(alarmstr, "UNCONFIGURED");
15603       }
15604 
15605       ast_cli(a->fd, FORMAT, s.desc, alarmstr, s.irqmisses, s.bpvcount, s.crc4count,
15606          s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
15607          s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
15608          s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
15609          "CAS",
15610          s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
15611          s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
15612          s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
15613          "Unk",
15614          s.lineconfig & DAHDI_CONFIG_CRC4 ?
15615             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
15616             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "",
15617          lbostr[s.lbo]
15618          );
15619    }
15620    close(ctl);
15621 
15622    return CLI_SUCCESS;
15623 #undef FORMAT
15624 #undef FORMAT2
15625 }
15626 
15627 static char *dahdi_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15628 {
15629    int pseudo_fd = -1;
15630    struct dahdi_versioninfo vi;
15631 
15632    switch (cmd) {
15633    case CLI_INIT:
15634       e->command = "dahdi show version";
15635       e->usage =
15636          "Usage: dahdi show version\n"
15637          "       Shows the DAHDI version in use\n";
15638       return NULL;
15639    case CLI_GENERATE:
15640       return NULL;
15641    }
15642    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
15643       ast_cli(a->fd, "Failed to open control file to get version.\n");
15644       return CLI_SUCCESS;
15645    }
15646 
15647    strcpy(vi.version, "Unknown");
15648    strcpy(vi.echo_canceller, "Unknown");
15649 
15650    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi))
15651       ast_cli(a->fd, "Failed to get DAHDI version: %s\n", strerror(errno));
15652    else
15653       ast_cli(a->fd, "DAHDI Version: %s Echo Canceller: %s\n", vi.version, vi.echo_canceller);
15654 
15655    close(pseudo_fd);
15656 
15657    return CLI_SUCCESS;
15658 }
15659 
15660 static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15661 {
15662    int channel;
15663    int gain;
15664    int tx;
15665    struct dahdi_hwgain hwgain;
15666    struct dahdi_pvt *tmp = NULL;
15667 
15668    switch (cmd) {
15669    case CLI_INIT:
15670       e->command = "dahdi set hwgain";
15671       e->usage =
15672          "Usage: dahdi set hwgain <rx|tx> <chan#> <gain>\n"
15673          "  Sets the hardware gain on a a given channel, overriding the\n"
15674          "   value provided at module loadtime, whether the channel is in\n"
15675          "   use or not.  Changes take effect immediately.\n"
15676          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15677          "   <chan num> is the channel number relative to the device\n"
15678          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15679       return NULL;
15680    case CLI_GENERATE:
15681       return NULL;
15682    }
15683 
15684    if (a->argc != 6)
15685       return CLI_SHOWUSAGE;
15686 
15687    if (!strcasecmp("rx", a->argv[3]))
15688       tx = 0; /* rx */
15689    else if (!strcasecmp("tx", a->argv[3]))
15690       tx = 1; /* tx */
15691    else
15692       return CLI_SHOWUSAGE;
15693 
15694    channel = atoi(a->argv[4]);
15695    gain = atof(a->argv[5])*10.0;
15696 
15697    ast_mutex_lock(&iflock);
15698 
15699    for (tmp = iflist; tmp; tmp = tmp->next) {
15700 
15701       if (tmp->channel != channel)
15702          continue;
15703 
15704       if (tmp->subs[SUB_REAL].dfd == -1)
15705          break;
15706 
15707       hwgain.newgain = gain;
15708       hwgain.tx = tx;
15709       if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_HWGAIN, &hwgain) < 0) {
15710          ast_cli(a->fd, "Unable to set the hardware gain for channel %d: %s\n", channel, strerror(errno));
15711          ast_mutex_unlock(&iflock);
15712          return CLI_FAILURE;
15713       }
15714       ast_cli(a->fd, "hardware %s gain set to %d (%.1f dB) on channel %d\n",
15715          tx ? "tx" : "rx", gain, (float)gain/10.0, channel);
15716       break;
15717    }
15718 
15719    ast_mutex_unlock(&iflock);
15720 
15721    if (tmp)
15722       return CLI_SUCCESS;
15723 
15724    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15725    return CLI_FAILURE;
15726 
15727 }
15728 
15729 static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15730 {
15731    int channel;
15732    float gain;
15733    int tx;
15734    int res;
15735    struct dahdi_pvt *tmp = NULL;
15736 
15737    switch (cmd) {
15738    case CLI_INIT:
15739       e->command = "dahdi set swgain";
15740       e->usage =
15741          "Usage: dahdi set swgain <rx|tx> <chan#> <gain>\n"
15742          "  Sets the software gain on a a given channel, overriding the\n"
15743          "   value provided at module loadtime, whether the channel is in\n"
15744          "   use or not.  Changes take effect immediately.\n"
15745          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15746          "   <chan num> is the channel number relative to the device\n"
15747          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15748       return NULL;
15749    case CLI_GENERATE:
15750       return NULL;
15751    }
15752 
15753    if (a->argc != 6)
15754       return CLI_SHOWUSAGE;
15755 
15756    if (!strcasecmp("rx", a->argv[3]))
15757       tx = 0; /* rx */
15758    else if (!strcasecmp("tx", a->argv[3]))
15759       tx = 1; /* tx */
15760    else
15761       return CLI_SHOWUSAGE;
15762 
15763    channel = atoi(a->argv[4]);
15764    gain = atof(a->argv[5]);
15765 
15766    ast_mutex_lock(&iflock);
15767    for (tmp = iflist; tmp; tmp = tmp->next) {
15768 
15769       if (tmp->channel != channel)
15770          continue;
15771 
15772       if (tmp->subs[SUB_REAL].dfd == -1)
15773          break;
15774 
15775       if (tx)
15776          res = set_actual_txgain(tmp->subs[SUB_REAL].dfd, gain, tmp->txdrc, tmp->law);
15777       else
15778          res = set_actual_rxgain(tmp->subs[SUB_REAL].dfd, gain, tmp->rxdrc, tmp->law);
15779 
15780       if (res) {
15781          ast_cli(a->fd, "Unable to set the software gain for channel %d\n", channel);
15782          ast_mutex_unlock(&iflock);
15783          return CLI_FAILURE;
15784       }
15785 
15786       ast_cli(a->fd, "software %s gain set to %.1f on channel %d\n",
15787          tx ? "tx" : "rx", gain, channel);
15788       break;
15789    }
15790    ast_mutex_unlock(&iflock);
15791 
15792    if (tmp)
15793       return CLI_SUCCESS;
15794 
15795    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15796    return CLI_FAILURE;
15797 
15798 }
15799 
15800 static char *dahdi_set_dnd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15801 {
15802    int channel;
15803    int on;
15804    struct dahdi_pvt *dahdi_chan = NULL;
15805 
15806    switch (cmd) {
15807    case CLI_INIT:
15808       e->command = "dahdi set dnd";
15809       e->usage =
15810          "Usage: dahdi set dnd <chan#> <on|off>\n"
15811          "  Sets/resets DND (Do Not Disturb) mode on a channel.\n"
15812          "  Changes take effect immediately.\n"
15813          "  <chan num> is the channel number\n"
15814          "  <on|off> Enable or disable DND mode?\n"
15815          ;
15816       return NULL;
15817    case CLI_GENERATE:
15818       return NULL;
15819    }
15820 
15821    if (a->argc != 5)
15822       return CLI_SHOWUSAGE;
15823 
15824    if ((channel = atoi(a->argv[3])) <= 0) {
15825       ast_cli(a->fd, "Expected channel number, got '%s'\n", a->argv[3]);
15826       return CLI_SHOWUSAGE;
15827    }
15828 
15829    if (ast_true(a->argv[4]))
15830       on = 1;
15831    else if (ast_false(a->argv[4]))
15832       on = 0;
15833    else {
15834       ast_cli(a->fd, "Expected 'on' or 'off', got '%s'\n", a->argv[4]);
15835       return CLI_SHOWUSAGE;
15836    }
15837 
15838    ast_mutex_lock(&iflock);
15839    for (dahdi_chan = iflist; dahdi_chan; dahdi_chan = dahdi_chan->next) {
15840       if (dahdi_chan->channel != channel)
15841          continue;
15842 
15843       /* Found the channel. Actually set it */
15844       dahdi_dnd(dahdi_chan, on);
15845       break;
15846    }
15847    ast_mutex_unlock(&iflock);
15848 
15849    if (!dahdi_chan) {
15850       ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15851       return CLI_FAILURE;
15852    }
15853 
15854    return CLI_SUCCESS;
15855 }
15856 
15857 static struct ast_cli_entry dahdi_cli[] = {
15858    AST_CLI_DEFINE(handle_dahdi_show_cadences, "List cadences"),
15859    AST_CLI_DEFINE(dahdi_show_channels, "Show active DAHDI channels"),
15860    AST_CLI_DEFINE(dahdi_show_channel, "Show information on a channel"),
15861    AST_CLI_DEFINE(dahdi_destroy_channel, "Destroy a channel"),
15862    AST_CLI_DEFINE(dahdi_restart_cmd, "Fully restart DAHDI channels"),
15863    AST_CLI_DEFINE(dahdi_show_status, "Show all DAHDI cards status"),
15864    AST_CLI_DEFINE(dahdi_show_version, "Show the DAHDI version in use"),
15865    AST_CLI_DEFINE(dahdi_set_hwgain, "Set hardware gain on a channel"),
15866    AST_CLI_DEFINE(dahdi_set_swgain, "Set software gain on a channel"),
15867    AST_CLI_DEFINE(dahdi_set_dnd, "Sets/resets DND (Do Not Disturb) mode on a channel"),
15868 };
15869 
15870 #define TRANSFER  0
15871 #define HANGUP    1
15872 
15873 static int dahdi_fake_event(struct dahdi_pvt *p, int mode)
15874 {
15875    if (p) {
15876       switch (mode) {
15877       case TRANSFER:
15878          p->fake_event = DAHDI_EVENT_WINKFLASH;
15879          break;
15880       case HANGUP:
15881          p->fake_event = DAHDI_EVENT_ONHOOK;
15882          break;
15883       default:
15884          ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
15885       }
15886    }
15887    return 0;
15888 }
15889 static struct dahdi_pvt *find_channel(int channel)
15890 {
15891    struct dahdi_pvt *p;
15892 
15893    ast_mutex_lock(&iflock);
15894    for (p = iflist; p; p = p->next) {
15895       if (p->channel == channel) {
15896          break;
15897       }
15898    }
15899    ast_mutex_unlock(&iflock);
15900    return p;
15901 }
15902 
15903 /*!
15904  * \internal
15905  * \brief Get private struct using given numeric channel string.
15906  *
15907  * \param channel Numeric channel number string get private struct.
15908  *
15909  * \retval pvt on success.
15910  * \retval NULL on error.
15911  */
15912 static struct dahdi_pvt *find_channel_from_str(const char *channel)
15913 {
15914    int chan_num;
15915 
15916    if (sscanf(channel, "%30d", &chan_num) != 1) {
15917       /* Not numeric string. */
15918       return NULL;
15919    }
15920 
15921    return find_channel(chan_num);
15922 }
15923 
15924 static int action_dahdidndon(struct mansession *s, const struct message *m)
15925 {
15926    struct dahdi_pvt *p;
15927    const char *channel = astman_get_header(m, "DAHDIChannel");
15928 
15929    if (ast_strlen_zero(channel)) {
15930       astman_send_error(s, m, "No channel specified");
15931       return 0;
15932    }
15933    p = find_channel_from_str(channel);
15934    if (!p) {
15935       astman_send_error(s, m, "No such channel");
15936       return 0;
15937    }
15938    dahdi_dnd(p, 1);
15939    astman_send_ack(s, m, "DND Enabled");
15940    return 0;
15941 }
15942 
15943 static int action_dahdidndoff(struct mansession *s, const struct message *m)
15944 {
15945    struct dahdi_pvt *p;
15946    const char *channel = astman_get_header(m, "DAHDIChannel");
15947 
15948    if (ast_strlen_zero(channel)) {
15949       astman_send_error(s, m, "No channel specified");
15950       return 0;
15951    }
15952    p = find_channel_from_str(channel);
15953    if (!p) {
15954       astman_send_error(s, m, "No such channel");
15955       return 0;
15956    }
15957    dahdi_dnd(p, 0);
15958    astman_send_ack(s, m, "DND Disabled");
15959    return 0;
15960 }
15961 
15962 static int action_transfer(struct mansession *s, const struct message *m)
15963 {
15964    struct dahdi_pvt *p;
15965    const char *channel = astman_get_header(m, "DAHDIChannel");
15966 
15967    if (ast_strlen_zero(channel)) {
15968       astman_send_error(s, m, "No channel specified");
15969       return 0;
15970    }
15971    p = find_channel_from_str(channel);
15972    if (!p) {
15973       astman_send_error(s, m, "No such channel");
15974       return 0;
15975    }
15976    if (!analog_lib_handles(p->sig, 0, 0)) {
15977       astman_send_error(s, m, "Channel signaling is not analog");
15978       return 0;
15979    }
15980    dahdi_fake_event(p,TRANSFER);
15981    astman_send_ack(s, m, "DAHDITransfer");
15982    return 0;
15983 }
15984 
15985 static int action_transferhangup(struct mansession *s, const struct message *m)
15986 {
15987    struct dahdi_pvt *p;
15988    const char *channel = astman_get_header(m, "DAHDIChannel");
15989 
15990    if (ast_strlen_zero(channel)) {
15991       astman_send_error(s, m, "No channel specified");
15992       return 0;
15993    }
15994    p = find_channel_from_str(channel);
15995    if (!p) {
15996       astman_send_error(s, m, "No such channel");
15997       return 0;
15998    }
15999    if (!analog_lib_handles(p->sig, 0, 0)) {
16000       astman_send_error(s, m, "Channel signaling is not analog");
16001       return 0;
16002    }
16003    dahdi_fake_event(p,HANGUP);
16004    astman_send_ack(s, m, "DAHDIHangup");
16005    return 0;
16006 }
16007 
16008 static int action_dahdidialoffhook(struct mansession *s, const struct message *m)
16009 {
16010    struct dahdi_pvt *p;
16011    const char *channel = astman_get_header(m, "DAHDIChannel");
16012    const char *number = astman_get_header(m, "Number");
16013    int i;
16014 
16015    if (ast_strlen_zero(channel)) {
16016       astman_send_error(s, m, "No channel specified");
16017       return 0;
16018    }
16019    if (ast_strlen_zero(number)) {
16020       astman_send_error(s, m, "No number specified");
16021       return 0;
16022    }
16023    p = find_channel_from_str(channel);
16024    if (!p) {
16025       astman_send_error(s, m, "No such channel");
16026       return 0;
16027    }
16028    if (!p->owner) {
16029       astman_send_error(s, m, "Channel does not have it's owner");
16030       return 0;
16031    }
16032    for (i = 0; i < strlen(number); i++) {
16033       struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = number[i] };
16034       dahdi_queue_frame(p, &f);
16035    }
16036    astman_send_ack(s, m, "DAHDIDialOffhook");
16037    return 0;
16038 }
16039 
16040 static int action_dahdishowchannels(struct mansession *s, const struct message *m)
16041 {
16042    struct dahdi_pvt *tmp = NULL;
16043    const char *id = astman_get_header(m, "ActionID");
16044    const char *dahdichannel = astman_get_header(m, "DAHDIChannel");
16045    char idText[256] = "";
16046    int channels = 0;
16047    int dahdichanquery;
16048 
16049    if (!dahdichannel || sscanf(dahdichannel, "%30d", &dahdichanquery) != 1) {
16050       /* Not numeric string. */
16051       dahdichanquery = -1;
16052    }
16053 
16054    astman_send_ack(s, m, "DAHDI channel status will follow");
16055    if (!ast_strlen_zero(id))
16056       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
16057 
16058    ast_mutex_lock(&iflock);
16059 
16060    for (tmp = iflist; tmp; tmp = tmp->next) {
16061       if (tmp->channel > 0) {
16062          int alm;
16063 
16064          /* If a specific channel is queried for, only deliver status for that channel */
16065          if (dahdichanquery > 0 && tmp->channel != dahdichanquery)
16066             continue;
16067 
16068          alm = get_alarms(tmp);
16069          channels++;
16070          if (tmp->owner) {
16071             /* Add data if we have a current call */
16072             astman_append(s,
16073                "Event: DAHDIShowChannels\r\n"
16074                "DAHDIChannel: %d\r\n"
16075                "Channel: %s\r\n"
16076                "Uniqueid: %s\r\n"
16077                "AccountCode: %s\r\n"
16078                "Signalling: %s\r\n"
16079                "SignallingCode: %d\r\n"
16080                "Context: %s\r\n"
16081                "DND: %s\r\n"
16082                "Alarm: %s\r\n"
16083                "%s"
16084                "\r\n",
16085                tmp->channel,
16086                tmp->owner->name,
16087                tmp->owner->uniqueid,
16088                tmp->owner->accountcode,
16089                sig2str(tmp->sig),
16090                tmp->sig,
16091                tmp->context,
16092                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
16093                alarm2str(alm), idText);
16094          } else {
16095             astman_append(s,
16096                "Event: DAHDIShowChannels\r\n"
16097                "DAHDIChannel: %d\r\n"
16098                "Signalling: %s\r\n"
16099                "SignallingCode: %d\r\n"
16100                "Context: %s\r\n"
16101                "DND: %s\r\n"
16102                "Alarm: %s\r\n"
16103                "%s"
16104                "\r\n",
16105                tmp->channel, sig2str(tmp->sig), tmp->sig,
16106                tmp->context,
16107                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
16108                alarm2str(alm), idText);
16109          }
16110       }
16111    }
16112 
16113    ast_mutex_unlock(&iflock);
16114 
16115    astman_append(s,
16116       "Event: DAHDIShowChannelsComplete\r\n"
16117       "%s"
16118       "Items: %d\r\n"
16119       "\r\n",
16120       idText,
16121       channels);
16122    return 0;
16123 }
16124 
16125 #if defined(HAVE_SS7)
16126 static int linkset_addsigchan(int sigchan)
16127 {
16128    struct dahdi_ss7 *link;
16129    int res;
16130    int curfd;
16131    struct dahdi_params params;
16132    struct dahdi_bufferinfo bi;
16133    struct dahdi_spaninfo si;
16134 
16135    if (sigchan < 0) {
16136       ast_log(LOG_ERROR, "Invalid sigchan!\n");
16137       return -1;
16138    }
16139    if (cur_ss7type < 0) {
16140       ast_log(LOG_ERROR, "Unspecified or invalid ss7type\n");
16141       return -1;
16142    }
16143    if (cur_pointcode < 0) {
16144       ast_log(LOG_ERROR, "Unspecified pointcode!\n");
16145       return -1;
16146    }
16147    if (cur_adjpointcode < 0) {
16148       ast_log(LOG_ERROR, "Unspecified adjpointcode!\n");
16149       return -1;
16150    }
16151    if (cur_defaultdpc < 0) {
16152       ast_log(LOG_ERROR, "Unspecified defaultdpc!\n");
16153       return -1;
16154    }
16155    if (cur_networkindicator < 0) {
16156       ast_log(LOG_ERROR, "Invalid networkindicator!\n");
16157       return -1;
16158    }
16159    link = ss7_resolve_linkset(cur_linkset);
16160    if (!link) {
16161       ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
16162       return -1;
16163    }
16164    if (link->ss7.numsigchans >= SIG_SS7_NUM_DCHANS) {
16165       ast_log(LOG_ERROR, "Too many sigchans on linkset %d\n", cur_linkset);
16166       return -1;
16167    }
16168 
16169    curfd = link->ss7.numsigchans;
16170 
16171    /* Open signaling channel */
16172    link->ss7.fds[curfd] = open("/dev/dahdi/channel", O_RDWR, 0600);
16173    if (link->ss7.fds[curfd] < 0) {
16174       ast_log(LOG_ERROR, "Unable to open SS7 sigchan %d (%s)\n", sigchan,
16175          strerror(errno));
16176       return -1;
16177    }
16178    if (ioctl(link->ss7.fds[curfd], DAHDI_SPECIFY, &sigchan) == -1) {
16179       dahdi_close_ss7_fd(link, curfd);
16180       ast_log(LOG_ERROR, "Unable to specify SS7 sigchan %d (%s)\n", sigchan,
16181          strerror(errno));
16182       return -1;
16183    }
16184 
16185    /* Get signaling channel parameters */
16186    memset(&params, 0, sizeof(params));
16187    res = ioctl(link->ss7.fds[curfd], DAHDI_GET_PARAMS, &params);
16188    if (res) {
16189       dahdi_close_ss7_fd(link, curfd);
16190       ast_log(LOG_ERROR, "Unable to get parameters for sigchan %d (%s)\n", sigchan,
16191          strerror(errno));
16192       return -1;
16193    }
16194    if (params.sigtype != DAHDI_SIG_HDLCFCS
16195       && params.sigtype != DAHDI_SIG_HARDHDLC
16196       && params.sigtype != DAHDI_SIG_MTP2) {
16197       dahdi_close_ss7_fd(link, curfd);
16198       ast_log(LOG_ERROR, "sigchan %d is not in HDLC/FCS mode.\n", sigchan);
16199       return -1;
16200    }
16201 
16202    /* Set signaling channel buffer policy. */
16203    memset(&bi, 0, sizeof(bi));
16204    bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
16205    bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
16206    bi.numbufs = 32;
16207    bi.bufsize = 512;
16208    if (ioctl(link->ss7.fds[curfd], DAHDI_SET_BUFINFO, &bi)) {
16209       ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n",
16210          sigchan, strerror(errno));
16211       dahdi_close_ss7_fd(link, curfd);
16212       return -1;
16213    }
16214 
16215    /* Get current signaling channel alarm status. */
16216    memset(&si, 0, sizeof(si));
16217    res = ioctl(link->ss7.fds[curfd], DAHDI_SPANSTAT, &si);
16218    if (res) {
16219       dahdi_close_ss7_fd(link, curfd);
16220       ast_log(LOG_ERROR, "Unable to get span state for sigchan %d (%s)\n", sigchan,
16221          strerror(errno));
16222    }
16223 
16224    res = sig_ss7_add_sigchan(&link->ss7, curfd, cur_ss7type,
16225       (params.sigtype == DAHDI_SIG_MTP2)
16226          ? SS7_TRANSPORT_DAHDIMTP2
16227          : SS7_TRANSPORT_DAHDIDCHAN,
16228       si.alarms, cur_networkindicator, cur_pointcode, cur_adjpointcode);
16229    if (res) {
16230       dahdi_close_ss7_fd(link, curfd);
16231       return -1;
16232    }
16233 
16234    ++link->ss7.numsigchans;
16235 
16236    return 0;
16237 }
16238 #endif   /* defined(HAVE_SS7) */
16239 
16240 #if defined(HAVE_SS7)
16241 static char *handle_ss7_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16242 {
16243    int span;
16244    switch (cmd) {
16245    case CLI_INIT:
16246       e->command = "ss7 set debug {on|off} linkset";
16247       e->usage =
16248          "Usage: ss7 set debug {on|off} linkset <linkset>\n"
16249          "       Enables debugging on a given SS7 linkset\n";
16250       return NULL;
16251    case CLI_GENERATE:
16252       return NULL;
16253    }
16254    if (a->argc < 6)
16255       return CLI_SHOWUSAGE;
16256    span = atoi(a->argv[5]);
16257    if ((span < 1) || (span > NUM_SPANS)) {
16258       ast_cli(a->fd, "Invalid linkset %s.  Should be a number from %d to %d\n", a->argv[5], 1, NUM_SPANS);
16259       return CLI_SUCCESS;
16260    }
16261    if (!linksets[span-1].ss7.ss7) {
16262       ast_cli(a->fd, "No SS7 running on linkset %d\n", span);
16263    } else {
16264       if (!strcasecmp(a->argv[3], "on")) {
16265          linksets[span - 1].ss7.debug = 1;
16266          ss7_set_debug(linksets[span-1].ss7.ss7, SIG_SS7_DEBUG);
16267          ast_cli(a->fd, "Enabled debugging on linkset %d\n", span);
16268       } else {
16269          linksets[span - 1].ss7.debug = 0;
16270          ss7_set_debug(linksets[span-1].ss7.ss7, 0);
16271          ast_cli(a->fd, "Disabled debugging on linkset %d\n", span);
16272       }
16273    }
16274 
16275    return CLI_SUCCESS;
16276 }
16277 #endif   /* defined(HAVE_SS7) */
16278 
16279 #if defined(HAVE_SS7)
16280 static char *handle_ss7_block_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16281 {
16282    int linkset, cic;
16283    int blocked = -1, i;
16284    switch (cmd) {
16285    case CLI_INIT:
16286       e->command = "ss7 block cic";
16287       e->usage =
16288          "Usage: ss7 block cic <linkset> <CIC>\n"
16289          "       Sends a remote blocking request for the given CIC on the specified linkset\n";
16290       return NULL;
16291    case CLI_GENERATE:
16292       return NULL;
16293    }
16294    if (a->argc == 5)
16295       linkset = atoi(a->argv[3]);
16296    else
16297       return CLI_SHOWUSAGE;
16298 
16299    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16300       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16301       return CLI_SUCCESS;
16302    }
16303 
16304    if (!linksets[linkset-1].ss7.ss7) {
16305       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16306       return CLI_SUCCESS;
16307    }
16308 
16309    cic = atoi(a->argv[4]);
16310 
16311    if (cic < 1) {
16312       ast_cli(a->fd, "Invalid CIC specified!\n");
16313       return CLI_SUCCESS;
16314    }
16315 
16316    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16317       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
16318          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
16319          if (!blocked) {
16320             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16321             isup_blo(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16322             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16323          }
16324       }
16325    }
16326 
16327    if (blocked < 0) {
16328       ast_cli(a->fd, "Invalid CIC specified!\n");
16329       return CLI_SUCCESS;
16330    }
16331 
16332    if (!blocked)
16333       ast_cli(a->fd, "Sent blocking request for linkset %d on CIC %d\n", linkset, cic);
16334    else
16335       ast_cli(a->fd, "CIC %d already locally blocked\n", cic);
16336 
16337    /* Break poll on the linkset so it sends our messages */
16338    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16339 
16340    return CLI_SUCCESS;
16341 }
16342 #endif   /* defined(HAVE_SS7) */
16343 
16344 #if defined(HAVE_SS7)
16345 static char *handle_ss7_block_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16346 {
16347    int linkset;
16348    int i;
16349    switch (cmd) {
16350    case CLI_INIT:
16351       e->command = "ss7 block linkset";
16352       e->usage =
16353          "Usage: ss7 block linkset <linkset number>\n"
16354          "       Sends a remote blocking request for all CICs on the given linkset\n";
16355       return NULL;
16356    case CLI_GENERATE:
16357       return NULL;
16358    }
16359    if (a->argc == 4)
16360       linkset = atoi(a->argv[3]);
16361    else
16362       return CLI_SHOWUSAGE;
16363 
16364    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16365       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16366       return CLI_SUCCESS;
16367    }
16368 
16369    if (!linksets[linkset-1].ss7.ss7) {
16370       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16371       return CLI_SUCCESS;
16372    }
16373 
16374    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16375       ast_cli(a->fd, "Sending remote blocking request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
16376       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16377       isup_blo(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16378       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16379    }
16380 
16381    /* Break poll on the linkset so it sends our messages */
16382    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16383 
16384    return CLI_SUCCESS;
16385 }
16386 #endif   /* defined(HAVE_SS7) */
16387 
16388 #if defined(HAVE_SS7)
16389 static char *handle_ss7_unblock_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16390 {
16391    int linkset, cic;
16392    int i, blocked = -1;
16393    switch (cmd) {
16394    case CLI_INIT:
16395       e->command = "ss7 unblock cic";
16396       e->usage =
16397          "Usage: ss7 unblock cic <linkset> <CIC>\n"
16398          "       Sends a remote unblocking request for the given CIC on the specified linkset\n";
16399       return NULL;
16400    case CLI_GENERATE:
16401       return NULL;
16402    }
16403 
16404    if (a->argc == 5)
16405       linkset = atoi(a->argv[3]);
16406    else
16407       return CLI_SHOWUSAGE;
16408 
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 
16414    if (!linksets[linkset-1].ss7.ss7) {
16415       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16416       return CLI_SUCCESS;
16417    }
16418 
16419    cic = atoi(a->argv[4]);
16420 
16421    if (cic < 1) {
16422       ast_cli(a->fd, "Invalid CIC specified!\n");
16423       return CLI_SUCCESS;
16424    }
16425 
16426    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16427       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
16428          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
16429          if (blocked) {
16430             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16431             isup_ubl(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16432             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16433          }
16434       }
16435    }
16436 
16437    if (blocked > 0)
16438       ast_cli(a->fd, "Sent unblocking request for linkset %d on CIC %d\n", linkset, cic);
16439 
16440    /* Break poll on the linkset so it sends our messages */
16441    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16442 
16443    return CLI_SUCCESS;
16444 }
16445 #endif   /* defined(HAVE_SS7) */
16446 
16447 #if defined(HAVE_SS7)
16448 static char *handle_ss7_unblock_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16449 {
16450    int linkset;
16451    int i;
16452    switch (cmd) {
16453    case CLI_INIT:
16454       e->command = "ss7 unblock linkset";
16455       e->usage =
16456          "Usage: ss7 unblock linkset <linkset number>\n"
16457          "       Sends a remote unblocking request for all CICs on the specified linkset\n";
16458       return NULL;
16459    case CLI_GENERATE:
16460       return NULL;
16461    }
16462 
16463    if (a->argc == 4)
16464       linkset = atoi(a->argv[3]);
16465    else
16466       return CLI_SHOWUSAGE;
16467 
16468    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16469       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16470       return CLI_SUCCESS;
16471    }
16472 
16473    if (!linksets[linkset-1].ss7.ss7) {
16474       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16475       return CLI_SUCCESS;
16476    }
16477 
16478    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
16479       ast_cli(a->fd, "Sending remote unblock request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
16480       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
16481       isup_ubl(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
16482       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
16483    }
16484 
16485    /* Break poll on the linkset so it sends our messages */
16486    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
16487 
16488    return CLI_SUCCESS;
16489 }
16490 #endif   /* defined(HAVE_SS7) */
16491 
16492 #if defined(HAVE_SS7)
16493 static char *handle_ss7_show_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16494 {
16495    int linkset;
16496    struct sig_ss7_linkset *ss7;
16497    switch (cmd) {
16498    case CLI_INIT:
16499       e->command = "ss7 show linkset";
16500       e->usage =
16501          "Usage: ss7 show linkset <span>\n"
16502          "       Shows the status of an SS7 linkset.\n";
16503       return NULL;
16504    case CLI_GENERATE:
16505       return NULL;
16506    }
16507 
16508    if (a->argc < 4)
16509       return CLI_SHOWUSAGE;
16510    linkset = atoi(a->argv[3]);
16511    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16512       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16513       return CLI_SUCCESS;
16514    }
16515    ss7 = &linksets[linkset - 1].ss7;
16516    if (!ss7->ss7) {
16517       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16518       return CLI_SUCCESS;
16519    }
16520 
16521    ast_cli(a->fd, "SS7 linkset %d status: %s\n", linkset, (ss7->state == LINKSET_STATE_UP) ? "Up" : "Down");
16522 
16523    return CLI_SUCCESS;
16524 }
16525 #endif   /* defined(HAVE_SS7) */
16526 
16527 #if defined(HAVE_SS7)
16528 static char *handle_ss7_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16529 {
16530    int linkset;
16531 
16532    switch (cmd) {
16533    case CLI_INIT:
16534       e->command = "ss7 show channels";
16535       e->usage =
16536          "Usage: ss7 show channels\n"
16537          "       Displays SS7 channel information at a glance.\n";
16538       return NULL;
16539    case CLI_GENERATE:
16540       return NULL;
16541    }
16542 
16543    if (a->argc != 3)
16544       return CLI_SHOWUSAGE;
16545 
16546    sig_ss7_cli_show_channels_header(a->fd);
16547    for (linkset = 0; linkset < NUM_SPANS; ++linkset) {
16548       if (linksets[linkset].ss7.ss7) {
16549          sig_ss7_cli_show_channels(a->fd, &linksets[linkset].ss7);
16550       }
16551    }
16552    return CLI_SUCCESS;
16553 }
16554 #endif   /* defined(HAVE_SS7) */
16555 
16556 #if defined(HAVE_SS7)
16557 static char *handle_ss7_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16558 {
16559    switch (cmd) {
16560    case CLI_INIT:
16561       e->command = "ss7 show version";
16562       e->usage =
16563          "Usage: ss7 show version\n"
16564          "  Show the libss7 version\n";
16565       return NULL;
16566    case CLI_GENERATE:
16567       return NULL;
16568    }
16569 
16570    ast_cli(a->fd, "libss7 version: %s\n", ss7_get_version());
16571 
16572    return CLI_SUCCESS;
16573 }
16574 #endif   /* defined(HAVE_SS7) */
16575 
16576 #if defined(HAVE_SS7)
16577 static struct ast_cli_entry dahdi_ss7_cli[] = {
16578    AST_CLI_DEFINE(handle_ss7_debug, "Enables SS7 debugging on a linkset"),
16579    AST_CLI_DEFINE(handle_ss7_block_cic, "Blocks the given CIC"),
16580    AST_CLI_DEFINE(handle_ss7_unblock_cic, "Unblocks the given CIC"),
16581    AST_CLI_DEFINE(handle_ss7_block_linkset, "Blocks all CICs on a linkset"),
16582    AST_CLI_DEFINE(handle_ss7_unblock_linkset, "Unblocks all CICs on a linkset"),
16583    AST_CLI_DEFINE(handle_ss7_show_linkset, "Shows the status of a linkset"),
16584    AST_CLI_DEFINE(handle_ss7_show_channels, "Displays SS7 channel information"),
16585    AST_CLI_DEFINE(handle_ss7_version, "Displays libss7 version"),
16586 };
16587 #endif   /* defined(HAVE_SS7) */
16588 
16589 #if defined(HAVE_PRI)
16590 #if defined(HAVE_PRI_CCSS)
16591 /*!
16592  * \internal
16593  * \brief CC agent initialization.
16594  * \since 1.8
16595  *
16596  * \param agent CC core agent control.
16597  * \param chan Original channel the agent will attempt to recall.
16598  *
16599  * \details
16600  * This callback is called when the CC core is initialized.  Agents should allocate
16601  * any private data necessary for the call and assign it to the private_data
16602  * on the agent.  Additionally, if any ast_cc_agent_flags are pertinent to the
16603  * specific agent type, they should be set in this function as well.
16604  *
16605  * \retval 0 on success.
16606  * \retval -1 on error.
16607  */
16608 static int dahdi_pri_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
16609 {
16610    struct dahdi_pvt *pvt;
16611    struct sig_pri_chan *pvt_chan;
16612    int res;
16613 
16614    ast_assert(!strcmp(chan->tech->type, "DAHDI"));
16615 
16616    pvt = chan->tech_pvt;
16617    if (dahdi_sig_pri_lib_handles(pvt->sig)) {
16618       pvt_chan = pvt->sig_pvt;
16619    } else {
16620       pvt_chan = NULL;
16621    }
16622    if (!pvt_chan) {
16623       return -1;
16624    }
16625 
16626    ast_module_ref(ast_module_info->self);
16627 
16628    res = sig_pri_cc_agent_init(agent, pvt_chan);
16629    if (res) {
16630       ast_module_unref(ast_module_info->self);
16631    }
16632    return res;
16633 }
16634 #endif   /* defined(HAVE_PRI_CCSS) */
16635 #endif   /* defined(HAVE_PRI) */
16636 
16637 #if defined(HAVE_PRI)
16638 #if defined(HAVE_PRI_CCSS)
16639 /*!
16640  * \internal
16641  * \brief Destroy private data on the agent.
16642  * \since 1.8
16643  *
16644  * \param agent CC core agent control.
16645  *
16646  * \details
16647  * The core will call this function upon completion
16648  * or failure of CC.
16649  *
16650  * \return Nothing
16651  */
16652 static void dahdi_pri_cc_agent_destructor(struct ast_cc_agent *agent)
16653 {
16654    sig_pri_cc_agent_destructor(agent);
16655 
16656    ast_module_unref(ast_module_info->self);
16657 }
16658 #endif   /* defined(HAVE_PRI_CCSS) */
16659 #endif   /* defined(HAVE_PRI) */
16660 
16661 #if defined(HAVE_PRI)
16662 #if defined(HAVE_PRI_CCSS)
16663 static struct ast_cc_agent_callbacks dahdi_pri_cc_agent_callbacks = {
16664    .type = dahdi_pri_cc_type,
16665    .init = dahdi_pri_cc_agent_init,
16666    .start_offer_timer = sig_pri_cc_agent_start_offer_timer,
16667    .stop_offer_timer = sig_pri_cc_agent_stop_offer_timer,
16668    .respond = sig_pri_cc_agent_req_rsp,
16669    .status_request = sig_pri_cc_agent_status_req,
16670    .stop_ringing = sig_pri_cc_agent_stop_ringing,
16671    .party_b_free = sig_pri_cc_agent_party_b_free,
16672    .start_monitoring = sig_pri_cc_agent_start_monitoring,
16673    .callee_available = sig_pri_cc_agent_callee_available,
16674    .destructor = dahdi_pri_cc_agent_destructor,
16675 };
16676 #endif   /* defined(HAVE_PRI_CCSS) */
16677 #endif   /* defined(HAVE_PRI) */
16678 
16679 #if defined(HAVE_PRI)
16680 #if defined(HAVE_PRI_CCSS)
16681 static struct ast_cc_monitor_callbacks dahdi_pri_cc_monitor_callbacks = {
16682    .type = dahdi_pri_cc_type,
16683    .request_cc = sig_pri_cc_monitor_req_cc,
16684    .suspend = sig_pri_cc_monitor_suspend,
16685    .unsuspend = sig_pri_cc_monitor_unsuspend,
16686    .status_response = sig_pri_cc_monitor_status_rsp,
16687    .cancel_available_timer = sig_pri_cc_monitor_cancel_available_timer,
16688    .destructor = sig_pri_cc_monitor_destructor,
16689 };
16690 #endif   /* defined(HAVE_PRI_CCSS) */
16691 #endif   /* defined(HAVE_PRI) */
16692 
16693 static int __unload_module(void)
16694 {
16695    struct dahdi_pvt *p;
16696 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16697    int i, j;
16698 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16699 
16700 #ifdef HAVE_PRI
16701    for (i = 0; i < NUM_SPANS; i++) {
16702       if (pris[i].pri.master != AST_PTHREADT_NULL)
16703          pthread_cancel(pris[i].pri.master);
16704    }
16705    ast_cli_unregister_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
16706    ast_unregister_application(dahdi_send_keypad_facility_app);
16707 #ifdef HAVE_PRI_PROG_W_CAUSE
16708    ast_unregister_application(dahdi_send_callrerouting_facility_app);
16709 #endif
16710 #endif
16711 #if defined(HAVE_SS7)
16712    for (i = 0; i < NUM_SPANS; i++) {
16713       if (linksets[i].ss7.master != AST_PTHREADT_NULL)
16714          pthread_cancel(linksets[i].ss7.master);
16715       }
16716    ast_cli_unregister_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
16717 #endif   /* defined(HAVE_SS7) */
16718 #if defined(HAVE_OPENR2)
16719    dahdi_r2_destroy_links();
16720    ast_cli_unregister_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
16721    ast_unregister_application(dahdi_accept_r2_call_app);
16722 #endif
16723 
16724    ast_cli_unregister_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
16725    ast_manager_unregister("DAHDIDialOffhook");
16726    ast_manager_unregister("DAHDIHangup");
16727    ast_manager_unregister("DAHDITransfer");
16728    ast_manager_unregister("DAHDIDNDoff");
16729    ast_manager_unregister("DAHDIDNDon");
16730    ast_manager_unregister("DAHDIShowChannels");
16731    ast_manager_unregister("DAHDIRestart");
16732    ast_data_unregister(NULL);
16733    ast_channel_unregister(&dahdi_tech);
16734 
16735    /* Hangup all interfaces if they have an owner */
16736    ast_mutex_lock(&iflock);
16737    for (p = iflist; p; p = p->next) {
16738       if (p->owner)
16739          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16740    }
16741    ast_mutex_unlock(&iflock);
16742 
16743    ast_mutex_lock(&monlock);
16744    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
16745       pthread_cancel(monitor_thread);
16746       pthread_kill(monitor_thread, SIGURG);
16747       pthread_join(monitor_thread, NULL);
16748    }
16749    monitor_thread = AST_PTHREADT_STOP;
16750    ast_mutex_unlock(&monlock);
16751 
16752    destroy_all_channels();
16753 
16754 #if defined(HAVE_PRI)
16755    for (i = 0; i < NUM_SPANS; i++) {
16756       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL))
16757          pthread_join(pris[i].pri.master, NULL);
16758       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++) {
16759          dahdi_close_pri_fd(&(pris[i]), j);
16760       }
16761       sig_pri_stop_pri(&pris[i].pri);
16762    }
16763 #if defined(HAVE_PRI_CCSS)
16764    ast_cc_agent_unregister(&dahdi_pri_cc_agent_callbacks);
16765    ast_cc_monitor_unregister(&dahdi_pri_cc_monitor_callbacks);
16766 #endif   /* defined(HAVE_PRI_CCSS) */
16767    sig_pri_unload();
16768 #endif
16769 
16770 #if defined(HAVE_SS7)
16771    for (i = 0; i < NUM_SPANS; i++) {
16772       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL))
16773          pthread_join(linksets[i].ss7.master, NULL);
16774       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++) {
16775          dahdi_close_ss7_fd(&(linksets[i]), j);
16776       }
16777    }
16778 #endif   /* defined(HAVE_SS7) */
16779    ast_cond_destroy(&ss_thread_complete);
16780    return 0;
16781 }
16782 
16783 static int unload_module(void)
16784 {
16785 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16786    int y;
16787 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16788 #ifdef HAVE_PRI
16789    for (y = 0; y < NUM_SPANS; y++)
16790       ast_mutex_destroy(&pris[y].pri.lock);
16791 #endif
16792 #if defined(HAVE_SS7)
16793    for (y = 0; y < NUM_SPANS; y++)
16794       ast_mutex_destroy(&linksets[y].ss7.lock);
16795 #endif   /* defined(HAVE_SS7) */
16796    return __unload_module();
16797 }
16798 
16799 static void string_replace(char *str, int char1, int char2)
16800 {
16801    for (; *str; str++) {
16802       if (*str == char1) {
16803          *str = char2;
16804       }
16805    }
16806 }
16807 
16808 static char *parse_spanchan(char *chanstr, char **subdir)
16809 {
16810    char *p;
16811 
16812    if ((p = strrchr(chanstr, '!')) == NULL) {
16813       *subdir = NULL;
16814       return chanstr;
16815    }
16816    *p++ = '\0';
16817    string_replace(chanstr, '!', '/');
16818    *subdir = chanstr;
16819    return p;
16820 }
16821 
16822 static int build_channels(struct dahdi_chan_conf *conf, const char *value, int reload, int lineno, int *found_pseudo)
16823 {
16824    char *c, *chan;
16825    char *subdir;
16826    int x, start, finish;
16827    struct dahdi_pvt *tmp;
16828 
16829    if ((reload == 0) && (conf->chan.sig < 0) && !conf->is_sig_auto) {
16830       ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
16831       return -1;
16832    }
16833 
16834    c = ast_strdupa(value);
16835    c = parse_spanchan(c, &subdir);
16836 
16837    while ((chan = strsep(&c, ","))) {
16838       if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
16839          /* Range */
16840       } else if (sscanf(chan, "%30d", &start)) {
16841          /* Just one */
16842          finish = start;
16843       } else if (!strcasecmp(chan, "pseudo")) {
16844          finish = start = CHAN_PSEUDO;
16845          if (found_pseudo)
16846             *found_pseudo = 1;
16847       } else {
16848          ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
16849          return -1;
16850       }
16851       if (finish < start) {
16852          ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
16853          x = finish;
16854          finish = start;
16855          start = x;
16856       }
16857 
16858       for (x = start; x <= finish; x++) {
16859          char fn[PATH_MAX];
16860          int real_channel = x;
16861 
16862          if (!ast_strlen_zero(subdir)) {
16863             real_channel = device2chan(subdir, x, fn, sizeof(fn));
16864             if (real_channel < 0) {
16865                if (conf->ignore_failed_channels) {
16866                   ast_log(LOG_WARNING, "Failed configuring %s!%d, (got %d). But moving on to others.\n",
16867                         subdir, x, real_channel);
16868                   continue;
16869                } else {
16870                   ast_log(LOG_ERROR, "Failed configuring %s!%d, (got %d).\n",
16871                         subdir, x, real_channel);
16872                   return -1;
16873                }
16874             }
16875          }
16876          tmp = mkintf(real_channel, conf, reload);
16877 
16878          if (tmp) {
16879             ast_verb(3, "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", real_channel, sig2str(tmp->sig));
16880          } else {
16881             ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
16882                   (reload == 1) ? "reconfigure" : "register", value);
16883             return -1;
16884          }
16885       }
16886    }
16887 
16888    return 0;
16889 }
16890 
16891 /** The length of the parameters list of 'dahdichan'.
16892  * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
16893 #define MAX_CHANLIST_LEN 80
16894 
16895 static void process_echocancel(struct dahdi_chan_conf *confp, const char *data, unsigned int line)
16896 {
16897    char *parse = ast_strdupa(data);
16898    char *params[DAHDI_MAX_ECHOCANPARAMS + 1];
16899    unsigned int param_count;
16900    unsigned int x;
16901 
16902    if (!(param_count = ast_app_separate_args(parse, ',', params, ARRAY_LEN(params))))
16903       return;
16904 
16905    memset(&confp->chan.echocancel, 0, sizeof(confp->chan.echocancel));
16906 
16907    /* first parameter is tap length, process it here */
16908 
16909    x = ast_strlen_zero(params[0]) ? 0 : atoi(params[0]);
16910 
16911    if ((x == 32) || (x == 64) || (x == 128) || (x == 256) || (x == 512) || (x == 1024))
16912       confp->chan.echocancel.head.tap_length = x;
16913    else if ((confp->chan.echocancel.head.tap_length = ast_true(params[0])))
16914       confp->chan.echocancel.head.tap_length = 128;
16915 
16916    /* now process any remaining parameters */
16917 
16918    for (x = 1; x < param_count; x++) {
16919       struct {
16920          char *name;
16921          char *value;
16922       } param;
16923 
16924       if (ast_app_separate_args(params[x], '=', (char **) &param, 2) < 1) {
16925          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, params[x]);
16926          continue;
16927       }
16928 
16929       if (ast_strlen_zero(param.name) || (strlen(param.name) > sizeof(confp->chan.echocancel.params[0].name)-1)) {
16930          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, param.name);
16931          continue;
16932       }
16933 
16934       strcpy(confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].name, param.name);
16935 
16936       if (param.value) {
16937          if (sscanf(param.value, "%30d", &confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].value) != 1) {
16938             ast_log(LOG_WARNING, "Invalid echocancel parameter value supplied at line %d: '%s'\n", line, param.value);
16939             continue;
16940          }
16941       }
16942       confp->chan.echocancel.head.param_count++;
16943    }
16944 }
16945 
16946 /*! process_dahdi() - ignore keyword 'channel' and similar */
16947 #define PROC_DAHDI_OPT_NOCHAN  (1 << 0)
16948 /*! process_dahdi() - No warnings on non-existing cofiguration keywords */
16949 #define PROC_DAHDI_OPT_NOWARN  (1 << 1)
16950 
16951 static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct ast_variable *v, int reload, int options)
16952 {
16953    struct dahdi_pvt *tmp;
16954    int y;
16955    int found_pseudo = 0;
16956    struct ast_variable *dahdichan = NULL;
16957 
16958    for (; v; v = v->next) {
16959       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16960          continue;
16961 
16962       /* Create the interface list */
16963       if (!strcasecmp(v->name, "channel") || !strcasecmp(v->name, "channels")) {
16964          if (options & PROC_DAHDI_OPT_NOCHAN) {
16965             ast_log(LOG_WARNING, "Channel '%s' ignored.\n", v->value);
16966             continue;
16967          }
16968          if (build_channels(confp, v->value, reload, v->lineno, &found_pseudo)) {
16969             if (confp->ignore_failed_channels) {
16970                ast_log(LOG_WARNING, "Channel '%s' failure ignored: ignore_failed_channels.\n", v->value);
16971                continue;
16972             } else {
16973                return -1;
16974             }
16975          }
16976          ast_log(LOG_DEBUG, "Channel '%s' configured.\n", v->value);
16977       } else if (!strcasecmp(v->name, "ignore_failed_channels")) {
16978          confp->ignore_failed_channels = ast_true(v->value);
16979       } else if (!strcasecmp(v->name, "buffers")) {
16980          if (parse_buffers_policy(v->value, &confp->chan.buf_no, &confp->chan.buf_policy)) {
16981             ast_log(LOG_WARNING, "Using default buffer policy.\n");
16982             confp->chan.buf_no = numbufs;
16983             confp->chan.buf_policy = DAHDI_POLICY_IMMEDIATE;
16984          }
16985       } else if (!strcasecmp(v->name, "faxbuffers")) {
16986          if (!parse_buffers_policy(v->value, &confp->chan.faxbuf_no, &confp->chan.faxbuf_policy)) {
16987             confp->chan.usefaxbuffers = 1;
16988          }
16989       } else if (!strcasecmp(v->name, "dahdichan")) {
16990          /* Only process the last dahdichan value. */
16991          dahdichan = v;
16992       } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
16993          usedistinctiveringdetection = ast_true(v->value);
16994       } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
16995          distinctiveringaftercid = ast_true(v->value);
16996       } else if (!strcasecmp(v->name, "dring1context")) {
16997          ast_copy_string(confp->chan.drings.ringContext[0].contextData,v->value,sizeof(confp->chan.drings.ringContext[0].contextData));
16998       } else if (!strcasecmp(v->name, "dring2context")) {
16999          ast_copy_string(confp->chan.drings.ringContext[1].contextData,v->value,sizeof(confp->chan.drings.ringContext[1].contextData));
17000       } else if (!strcasecmp(v->name, "dring3context")) {
17001          ast_copy_string(confp->chan.drings.ringContext[2].contextData,v->value,sizeof(confp->chan.drings.ringContext[2].contextData));
17002       } else if (!strcasecmp(v->name, "dring1range")) {
17003          confp->chan.drings.ringnum[0].range = atoi(v->value);
17004       } else if (!strcasecmp(v->name, "dring2range")) {
17005          confp->chan.drings.ringnum[1].range = atoi(v->value);
17006       } else if (!strcasecmp(v->name, "dring3range")) {
17007          confp->chan.drings.ringnum[2].range = atoi(v->value);
17008       } else if (!strcasecmp(v->name, "dring1")) {
17009          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]);
17010       } else if (!strcasecmp(v->name, "dring2")) {
17011          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]);
17012       } else if (!strcasecmp(v->name, "dring3")) {
17013          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]);
17014       } else if (!strcasecmp(v->name, "usecallerid")) {
17015          confp->chan.use_callerid = ast_true(v->value);
17016       } else if (!strcasecmp(v->name, "cidsignalling")) {
17017          if (!strcasecmp(v->value, "bell"))
17018             confp->chan.cid_signalling = CID_SIG_BELL;
17019          else if (!strcasecmp(v->value, "v23"))
17020             confp->chan.cid_signalling = CID_SIG_V23;
17021          else if (!strcasecmp(v->value, "dtmf"))
17022             confp->chan.cid_signalling = CID_SIG_DTMF;
17023          else if (!strcasecmp(v->value, "smdi"))
17024             confp->chan.cid_signalling = CID_SIG_SMDI;
17025          else if (!strcasecmp(v->value, "v23_jp"))
17026             confp->chan.cid_signalling = CID_SIG_V23_JP;
17027          else if (ast_true(v->value))
17028             confp->chan.cid_signalling = CID_SIG_BELL;
17029       } else if (!strcasecmp(v->name, "cidstart")) {
17030          if (!strcasecmp(v->value, "ring"))
17031             confp->chan.cid_start = CID_START_RING;
17032          else if (!strcasecmp(v->value, "polarity_in"))
17033             confp->chan.cid_start = CID_START_POLARITY_IN;
17034          else if (!strcasecmp(v->value, "polarity"))
17035             confp->chan.cid_start = CID_START_POLARITY;
17036          else if (!strcasecmp(v->value, "dtmf"))
17037             confp->chan.cid_start = CID_START_DTMF_NOALERT;
17038          else if (ast_true(v->value))
17039             confp->chan.cid_start = CID_START_RING;
17040       } else if (!strcasecmp(v->name, "threewaycalling")) {
17041          confp->chan.threewaycalling = ast_true(v->value);
17042       } else if (!strcasecmp(v->name, "cancallforward")) {
17043          confp->chan.cancallforward = ast_true(v->value);
17044       } else if (!strcasecmp(v->name, "relaxdtmf")) {
17045          if (ast_true(v->value))
17046             confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
17047          else
17048             confp->chan.dtmfrelax = 0;
17049       } else if (!strcasecmp(v->name, "mailbox")) {
17050          ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
17051       } else if (!strcasecmp(v->name, "hasvoicemail")) {
17052          if (ast_true(v->value) && ast_strlen_zero(confp->chan.mailbox)) {
17053             ast_copy_string(confp->chan.mailbox, cat, sizeof(confp->chan.mailbox));
17054          }
17055       } else if (!strcasecmp(v->name, "adsi")) {
17056          confp->chan.adsi = ast_true(v->value);
17057       } else if (!strcasecmp(v->name, "usesmdi")) {
17058          confp->chan.use_smdi = ast_true(v->value);
17059       } else if (!strcasecmp(v->name, "smdiport")) {
17060          ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
17061       } else if (!strcasecmp(v->name, "transfer")) {
17062          confp->chan.transfer = ast_true(v->value);
17063       } else if (!strcasecmp(v->name, "canpark")) {
17064          confp->chan.canpark = ast_true(v->value);
17065       } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
17066          confp->chan.echocanbridged = ast_true(v->value);
17067       } else if (!strcasecmp(v->name, "busydetect")) {
17068          confp->chan.busydetect = ast_true(v->value);
17069       } else if (!strcasecmp(v->name, "busycount")) {
17070          confp->chan.busycount = atoi(v->value);
17071       } else if (!strcasecmp(v->name, "busypattern")) {
17072          if (sscanf(v->value, "%30d,%30d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
17073             ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength at line %d.\n", v->lineno);
17074          }
17075       } else if (!strcasecmp(v->name, "callprogress")) {
17076          confp->chan.callprogress &= ~CALLPROGRESS_PROGRESS;
17077          if (ast_true(v->value))
17078             confp->chan.callprogress |= CALLPROGRESS_PROGRESS;
17079       } else if (!strcasecmp(v->name, "waitfordialtone")) {
17080          confp->chan.waitfordialtone = atoi(v->value);
17081       } else if (!strcasecmp(v->name, "faxdetect")) {
17082          confp->chan.callprogress &= ~CALLPROGRESS_FAX;
17083          if (!strcasecmp(v->value, "incoming")) {
17084             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING;
17085          } else if (!strcasecmp(v->value, "outgoing")) {
17086             confp->chan.callprogress |= CALLPROGRESS_FAX_OUTGOING;
17087          } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
17088             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING;
17089       } else if (!strcasecmp(v->name, "echocancel")) {
17090          process_echocancel(confp, v->value, v->lineno);
17091       } else if (!strcasecmp(v->name, "echotraining")) {
17092          if (sscanf(v->value, "%30d", &y) == 1) {
17093             if ((y < 10) || (y > 4000)) {
17094                ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d.\n", v->lineno);
17095             } else {
17096                confp->chan.echotraining = y;
17097             }
17098          } else if (ast_true(v->value)) {
17099             confp->chan.echotraining = 400;
17100          } else
17101             confp->chan.echotraining = 0;
17102       } else if (!strcasecmp(v->name, "hidecallerid")) {
17103          confp->chan.hidecallerid = ast_true(v->value);
17104       } else if (!strcasecmp(v->name, "hidecalleridname")) {
17105          confp->chan.hidecalleridname = ast_true(v->value);
17106       } else if (!strcasecmp(v->name, "pulsedial")) {
17107          confp->chan.pulse = ast_true(v->value);
17108       } else if (!strcasecmp(v->name, "callreturn")) {
17109          confp->chan.callreturn = ast_true(v->value);
17110       } else if (!strcasecmp(v->name, "callwaiting")) {
17111          confp->chan.callwaiting = ast_true(v->value);
17112       } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
17113          confp->chan.callwaitingcallerid = ast_true(v->value);
17114       } else if (!strcasecmp(v->name, "context")) {
17115          ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
17116       } else if (!strcasecmp(v->name, "language")) {
17117          ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
17118       } else if (!strcasecmp(v->name, "progzone")) {
17119          ast_copy_string(progzone, v->value, sizeof(progzone));
17120       } else if (!strcasecmp(v->name, "mohinterpret")
17121          ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
17122          ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
17123       } else if (!strcasecmp(v->name, "mohsuggest")) {
17124          ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
17125       } else if (!strcasecmp(v->name, "parkinglot")) {
17126          ast_copy_string(confp->chan.parkinglot, v->value, sizeof(confp->chan.parkinglot));
17127       } else if (!strcasecmp(v->name, "stripmsd")) {
17128          ast_log(LOG_NOTICE, "Configuration option \"%s\" has been deprecated. Please use dialplan instead\n", v->name);
17129          confp->chan.stripmsd = atoi(v->value);
17130       } else if (!strcasecmp(v->name, "jitterbuffers")) {
17131          numbufs = atoi(v->value);
17132       } else if (!strcasecmp(v->name, "group")) {
17133          confp->chan.group = ast_get_group(v->value);
17134       } else if (!strcasecmp(v->name, "callgroup")) {
17135          if (!strcasecmp(v->value, "none"))
17136             confp->chan.callgroup = 0;
17137          else
17138             confp->chan.callgroup = ast_get_group(v->value);
17139       } else if (!strcasecmp(v->name, "pickupgroup")) {
17140          if (!strcasecmp(v->value, "none"))
17141             confp->chan.pickupgroup = 0;
17142          else
17143             confp->chan.pickupgroup = ast_get_group(v->value);
17144       } else if (!strcasecmp(v->name, "setvar")) {
17145          char *varname = ast_strdupa(v->value), *varval = NULL;
17146          struct ast_variable *tmpvar;
17147          if (varname && (varval = strchr(varname, '='))) {
17148             *varval++ = '\0';
17149             if ((tmpvar = ast_variable_new(varname, varval, ""))) {
17150                tmpvar->next = confp->chan.vars;
17151                confp->chan.vars = tmpvar;
17152             }
17153          }
17154       } else if (!strcasecmp(v->name, "immediate")) {
17155          confp->chan.immediate = ast_true(v->value);
17156       } else if (!strcasecmp(v->name, "transfertobusy")) {
17157          confp->chan.transfertobusy = ast_true(v->value);
17158       } else if (!strcasecmp(v->name, "mwimonitor")) {
17159          confp->chan.mwimonitor_neon = 0;
17160          confp->chan.mwimonitor_fsk = 0;
17161          confp->chan.mwimonitor_rpas = 0;
17162          if (strcasestr(v->value, "fsk")) {
17163             confp->chan.mwimonitor_fsk = 1;
17164          }
17165          if (strcasestr(v->value, "rpas")) {
17166             confp->chan.mwimonitor_rpas = 1;
17167          }
17168          if (strcasestr(v->value, "neon")) {
17169             confp->chan.mwimonitor_neon = 1;
17170          }
17171          /* If set to true or yes, assume that simple fsk is desired */
17172          if (ast_true(v->value)) {
17173             confp->chan.mwimonitor_fsk = 1;
17174          }
17175       } else if (!strcasecmp(v->name, "cid_rxgain")) {
17176          if (sscanf(v->value, "%30f", &confp->chan.cid_rxgain) != 1) {
17177             ast_log(LOG_WARNING, "Invalid cid_rxgain: %s at line %d.\n", v->value, v->lineno);
17178          }
17179       } else if (!strcasecmp(v->name, "rxgain")) {
17180          if (sscanf(v->value, "%30f", &confp->chan.rxgain) != 1) {
17181             ast_log(LOG_WARNING, "Invalid rxgain: %s at line %d.\n", v->value, v->lineno);
17182          }
17183       } else if (!strcasecmp(v->name, "txgain")) {
17184          if (sscanf(v->value, "%30f", &confp->chan.txgain) != 1) {
17185             ast_log(LOG_WARNING, "Invalid txgain: %s at line %d.\n", v->value, v->lineno);
17186          }
17187       } else if (!strcasecmp(v->name, "txdrc")) {
17188          if (sscanf(v->value, "%f", &confp->chan.txdrc) != 1) {
17189             ast_log(LOG_WARNING, "Invalid txdrc: %s\n", v->value);
17190          }
17191       } else if (!strcasecmp(v->name, "rxdrc")) {
17192          if (sscanf(v->value, "%f", &confp->chan.rxdrc) != 1) {
17193             ast_log(LOG_WARNING, "Invalid rxdrc: %s\n", v->value);
17194          }
17195       } else if (!strcasecmp(v->name, "tonezone")) {
17196          if (sscanf(v->value, "%30d", &confp->chan.tonezone) != 1) {
17197             ast_log(LOG_WARNING, "Invalid tonezone: %s at line %d.\n", v->value, v->lineno);
17198          }
17199       } else if (!strcasecmp(v->name, "callerid")) {
17200          if (!strcasecmp(v->value, "asreceived")) {
17201             confp->chan.cid_num[0] = '\0';
17202             confp->chan.cid_name[0] = '\0';
17203          } else {
17204             ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
17205          }
17206       } else if (!strcasecmp(v->name, "fullname")) {
17207          ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
17208       } else if (!strcasecmp(v->name, "cid_number")) {
17209          ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
17210       } else if (!strcasecmp(v->name, "cid_tag")) {
17211          ast_copy_string(confp->chan.cid_tag, v->value, sizeof(confp->chan.cid_tag));
17212       } else if (!strcasecmp(v->name, "useincomingcalleridondahditransfer")) {
17213          confp->chan.dahditrcallerid = ast_true(v->value);
17214       } else if (!strcasecmp(v->name, "restrictcid")) {
17215          confp->chan.restrictcid = ast_true(v->value);
17216       } else if (!strcasecmp(v->name, "usecallingpres")) {
17217          confp->chan.use_callingpres = ast_true(v->value);
17218       } else if (!strcasecmp(v->name, "accountcode")) {
17219          ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
17220       } else if (!strcasecmp(v->name, "amaflags")) {
17221          y = ast_cdr_amaflags2int(v->value);
17222          if (y < 0)
17223             ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d.\n", v->value, v->lineno);
17224          else
17225             confp->chan.amaflags = y;
17226       } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
17227          confp->chan.polarityonanswerdelay = atoi(v->value);
17228       } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
17229          confp->chan.answeronpolarityswitch = ast_true(v->value);
17230       } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
17231          confp->chan.hanguponpolarityswitch = ast_true(v->value);
17232       } else if (!strcasecmp(v->name, "sendcalleridafter")) {
17233          confp->chan.sendcalleridafter = atoi(v->value);
17234       } else if (!strcasecmp(v->name, "mwimonitornotify")) {
17235          ast_copy_string(mwimonitornotify, v->value, sizeof(mwimonitornotify));
17236       } else if (ast_cc_is_config_param(v->name)) {
17237          ast_cc_set_param(confp->chan.cc_params, v->name, v->value);
17238       } else if (!strcasecmp(v->name, "mwisendtype")) {
17239 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI  /* backward compatibility for older dahdi VMWI implementation */
17240          if (!strcasecmp(v->value, "rpas")) { /* Ring Pulse Alert Signal */
17241             mwisend_rpas = 1;
17242          } else {
17243             mwisend_rpas = 0;
17244          }
17245 #else
17246          /* Default is fsk, to turn it off you must specify nofsk */
17247          memset(&confp->chan.mwisend_setting, 0, sizeof(confp->chan.mwisend_setting));
17248          if (strcasestr(v->value, "nofsk")) {      /* NoFSK */
17249             confp->chan.mwisend_fsk = 0;
17250          } else {             /* Default FSK */
17251             confp->chan.mwisend_fsk = 1;
17252          }
17253          if (strcasestr(v->value, "rpas")) {       /* Ring Pulse Alert Signal, normally followed by FSK */
17254             confp->chan.mwisend_rpas = 1;
17255          } else {
17256             confp->chan.mwisend_rpas = 0;
17257          }
17258          if (strcasestr(v->value, "lrev")) {       /* Line Reversal */
17259             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_LREV;
17260          }
17261          if (strcasestr(v->value, "hvdc")) {       /* HV 90VDC */
17262             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVDC;
17263          }
17264          if ( (strcasestr(v->value, "neon")) || (strcasestr(v->value, "hvac")) ){   /* 90V DC pulses */
17265             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVAC;
17266          }
17267 #endif
17268       } else if (reload != 1) {
17269           if (!strcasecmp(v->name, "signalling") || !strcasecmp(v->name, "signaling")) {
17270             int orig_radio = confp->chan.radio;
17271             int orig_outsigmod = confp->chan.outsigmod;
17272             int orig_auto = confp->is_sig_auto;
17273 
17274             confp->chan.radio = 0;
17275             confp->chan.outsigmod = -1;
17276             confp->is_sig_auto = 0;
17277             if (!strcasecmp(v->value, "em")) {
17278                confp->chan.sig = SIG_EM;
17279             } else if (!strcasecmp(v->value, "em_e1")) {
17280                confp->chan.sig = SIG_EM_E1;
17281             } else if (!strcasecmp(v->value, "em_w")) {
17282                confp->chan.sig = SIG_EMWINK;
17283             } else if (!strcasecmp(v->value, "fxs_ls")) {
17284                confp->chan.sig = SIG_FXSLS;
17285             } else if (!strcasecmp(v->value, "fxs_gs")) {
17286                confp->chan.sig = SIG_FXSGS;
17287             } else if (!strcasecmp(v->value, "fxs_ks")) {
17288                confp->chan.sig = SIG_FXSKS;
17289             } else if (!strcasecmp(v->value, "fxo_ls")) {
17290                confp->chan.sig = SIG_FXOLS;
17291             } else if (!strcasecmp(v->value, "fxo_gs")) {
17292                confp->chan.sig = SIG_FXOGS;
17293             } else if (!strcasecmp(v->value, "fxo_ks")) {
17294                confp->chan.sig = SIG_FXOKS;
17295             } else if (!strcasecmp(v->value, "fxs_rx")) {
17296                confp->chan.sig = SIG_FXSKS;
17297                confp->chan.radio = 1;
17298             } else if (!strcasecmp(v->value, "fxo_rx")) {
17299                confp->chan.sig = SIG_FXOLS;
17300                confp->chan.radio = 1;
17301             } else if (!strcasecmp(v->value, "fxs_tx")) {
17302                confp->chan.sig = SIG_FXSLS;
17303                confp->chan.radio = 1;
17304             } else if (!strcasecmp(v->value, "fxo_tx")) {
17305                confp->chan.sig = SIG_FXOGS;
17306                confp->chan.radio = 1;
17307             } else if (!strcasecmp(v->value, "em_rx")) {
17308                confp->chan.sig = SIG_EM;
17309                confp->chan.radio = 1;
17310             } else if (!strcasecmp(v->value, "em_tx")) {
17311                confp->chan.sig = SIG_EM;
17312                confp->chan.radio = 1;
17313             } else if (!strcasecmp(v->value, "em_rxtx")) {
17314                confp->chan.sig = SIG_EM;
17315                confp->chan.radio = 2;
17316             } else if (!strcasecmp(v->value, "em_txrx")) {
17317                confp->chan.sig = SIG_EM;
17318                confp->chan.radio = 2;
17319             } else if (!strcasecmp(v->value, "sf")) {
17320                confp->chan.sig = SIG_SF;
17321             } else if (!strcasecmp(v->value, "sf_w")) {
17322                confp->chan.sig = SIG_SFWINK;
17323             } else if (!strcasecmp(v->value, "sf_featd")) {
17324                confp->chan.sig = SIG_FEATD;
17325             } else if (!strcasecmp(v->value, "sf_featdmf")) {
17326                confp->chan.sig = SIG_FEATDMF;
17327             } else if (!strcasecmp(v->value, "sf_featb")) {
17328                confp->chan.sig = SIG_SF_FEATB;
17329             } else if (!strcasecmp(v->value, "sf")) {
17330                confp->chan.sig = SIG_SF;
17331             } else if (!strcasecmp(v->value, "sf_rx")) {
17332                confp->chan.sig = SIG_SF;
17333                confp->chan.radio = 1;
17334             } else if (!strcasecmp(v->value, "sf_tx")) {
17335                confp->chan.sig = SIG_SF;
17336                confp->chan.radio = 1;
17337             } else if (!strcasecmp(v->value, "sf_rxtx")) {
17338                confp->chan.sig = SIG_SF;
17339                confp->chan.radio = 2;
17340             } else if (!strcasecmp(v->value, "sf_txrx")) {
17341                confp->chan.sig = SIG_SF;
17342                confp->chan.radio = 2;
17343             } else if (!strcasecmp(v->value, "featd")) {
17344                confp->chan.sig = SIG_FEATD;
17345             } else if (!strcasecmp(v->value, "featdmf")) {
17346                confp->chan.sig = SIG_FEATDMF;
17347             } else if (!strcasecmp(v->value, "featdmf_ta")) {
17348                confp->chan.sig = SIG_FEATDMF_TA;
17349             } else if (!strcasecmp(v->value, "e911")) {
17350                confp->chan.sig = SIG_E911;
17351             } else if (!strcasecmp(v->value, "fgccama")) {
17352                confp->chan.sig = SIG_FGC_CAMA;
17353             } else if (!strcasecmp(v->value, "fgccamamf")) {
17354                confp->chan.sig = SIG_FGC_CAMAMF;
17355             } else if (!strcasecmp(v->value, "featb")) {
17356                confp->chan.sig = SIG_FEATB;
17357 #ifdef HAVE_PRI
17358             } else if (!strcasecmp(v->value, "pri_net")) {
17359                confp->chan.sig = SIG_PRI;
17360                confp->pri.pri.nodetype = PRI_NETWORK;
17361             } else if (!strcasecmp(v->value, "pri_cpe")) {
17362                confp->chan.sig = SIG_PRI;
17363                confp->pri.pri.nodetype = PRI_CPE;
17364             } else if (!strcasecmp(v->value, "bri_cpe")) {
17365                confp->chan.sig = SIG_BRI;
17366                confp->pri.pri.nodetype = PRI_CPE;
17367             } else if (!strcasecmp(v->value, "bri_net")) {
17368                confp->chan.sig = SIG_BRI;
17369                confp->pri.pri.nodetype = PRI_NETWORK;
17370             } else if (!strcasecmp(v->value, "bri_cpe_ptmp")) {
17371                confp->chan.sig = SIG_BRI_PTMP;
17372                confp->pri.pri.nodetype = PRI_CPE;
17373             } else if (!strcasecmp(v->value, "bri_net_ptmp")) {
17374 #if defined(HAVE_PRI_CALL_HOLD)
17375                confp->chan.sig = SIG_BRI_PTMP;
17376                confp->pri.pri.nodetype = PRI_NETWORK;
17377 #else
17378                ast_log(LOG_WARNING, "How cool would it be if someone implemented this mode!  For now, sucks for you. (line %d)\n", v->lineno);
17379 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
17380 #endif
17381 #if defined(HAVE_SS7)
17382             } else if (!strcasecmp(v->value, "ss7")) {
17383                confp->chan.sig = SIG_SS7;
17384 #endif   /* defined(HAVE_SS7) */
17385 #ifdef HAVE_OPENR2
17386             } else if (!strcasecmp(v->value, "mfcr2")) {
17387                confp->chan.sig = SIG_MFCR2;
17388 #endif
17389             } else if (!strcasecmp(v->value, "auto")) {
17390                confp->is_sig_auto = 1;
17391             } else {
17392                confp->chan.outsigmod = orig_outsigmod;
17393                confp->chan.radio = orig_radio;
17394                confp->is_sig_auto = orig_auto;
17395                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
17396             }
17397           } else if (!strcasecmp(v->name, "outsignalling") || !strcasecmp(v->name, "outsignaling")) {
17398             if (!strcasecmp(v->value, "em")) {
17399                confp->chan.outsigmod = SIG_EM;
17400             } else if (!strcasecmp(v->value, "em_e1")) {
17401                confp->chan.outsigmod = SIG_EM_E1;
17402             } else if (!strcasecmp(v->value, "em_w")) {
17403                confp->chan.outsigmod = SIG_EMWINK;
17404             } else if (!strcasecmp(v->value, "sf")) {
17405                confp->chan.outsigmod = SIG_SF;
17406             } else if (!strcasecmp(v->value, "sf_w")) {
17407                confp->chan.outsigmod = SIG_SFWINK;
17408             } else if (!strcasecmp(v->value, "sf_featd")) {
17409                confp->chan.outsigmod = SIG_FEATD;
17410             } else if (!strcasecmp(v->value, "sf_featdmf")) {
17411                confp->chan.outsigmod = SIG_FEATDMF;
17412             } else if (!strcasecmp(v->value, "sf_featb")) {
17413                confp->chan.outsigmod = SIG_SF_FEATB;
17414             } else if (!strcasecmp(v->value, "sf")) {
17415                confp->chan.outsigmod = SIG_SF;
17416             } else if (!strcasecmp(v->value, "featd")) {
17417                confp->chan.outsigmod = SIG_FEATD;
17418             } else if (!strcasecmp(v->value, "featdmf")) {
17419                confp->chan.outsigmod = SIG_FEATDMF;
17420             } else if (!strcasecmp(v->value, "featdmf_ta")) {
17421                confp->chan.outsigmod = SIG_FEATDMF_TA;
17422             } else if (!strcasecmp(v->value, "e911")) {
17423                confp->chan.outsigmod = SIG_E911;
17424             } else if (!strcasecmp(v->value, "fgccama")) {
17425                confp->chan.outsigmod = SIG_FGC_CAMA;
17426             } else if (!strcasecmp(v->value, "fgccamamf")) {
17427                confp->chan.outsigmod = SIG_FGC_CAMAMF;
17428             } else if (!strcasecmp(v->value, "featb")) {
17429                confp->chan.outsigmod = SIG_FEATB;
17430             } else {
17431                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
17432             }
17433 #ifdef HAVE_PRI
17434          } else if (!strcasecmp(v->name, "pridialplan")) {
17435             if (!strcasecmp(v->value, "national")) {
17436                confp->pri.pri.dialplan = PRI_NATIONAL_ISDN + 1;
17437             } else if (!strcasecmp(v->value, "unknown")) {
17438                confp->pri.pri.dialplan = PRI_UNKNOWN + 1;
17439             } else if (!strcasecmp(v->value, "private")) {
17440                confp->pri.pri.dialplan = PRI_PRIVATE + 1;
17441             } else if (!strcasecmp(v->value, "international")) {
17442                confp->pri.pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
17443             } else if (!strcasecmp(v->value, "local")) {
17444                confp->pri.pri.dialplan = PRI_LOCAL_ISDN + 1;
17445             } else if (!strcasecmp(v->value, "dynamic")) {
17446                confp->pri.pri.dialplan = -1;
17447             } else if (!strcasecmp(v->value, "redundant")) {
17448                confp->pri.pri.dialplan = -2;
17449             } else {
17450                ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
17451             }
17452          } else if (!strcasecmp(v->name, "prilocaldialplan")) {
17453             if (!strcasecmp(v->value, "national")) {
17454                confp->pri.pri.localdialplan = PRI_NATIONAL_ISDN + 1;
17455             } else if (!strcasecmp(v->value, "unknown")) {
17456                confp->pri.pri.localdialplan = PRI_UNKNOWN + 1;
17457             } else if (!strcasecmp(v->value, "private")) {
17458                confp->pri.pri.localdialplan = PRI_PRIVATE + 1;
17459             } else if (!strcasecmp(v->value, "international")) {
17460                confp->pri.pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
17461             } else if (!strcasecmp(v->value, "local")) {
17462                confp->pri.pri.localdialplan = PRI_LOCAL_ISDN + 1;
17463             } else if (!strcasecmp(v->value, "dynamic")) {
17464                confp->pri.pri.localdialplan = -1;
17465             } else if (!strcasecmp(v->value, "redundant")) {
17466                confp->pri.pri.localdialplan = -2;
17467             } else {
17468                ast_log(LOG_WARNING, "Unknown PRI localdialplan '%s' at line %d.\n", v->value, v->lineno);
17469             }
17470          } else if (!strcasecmp(v->name, "switchtype")) {
17471             if (!strcasecmp(v->value, "national"))
17472                confp->pri.pri.switchtype = PRI_SWITCH_NI2;
17473             else if (!strcasecmp(v->value, "ni1"))
17474                confp->pri.pri.switchtype = PRI_SWITCH_NI1;
17475             else if (!strcasecmp(v->value, "dms100"))
17476                confp->pri.pri.switchtype = PRI_SWITCH_DMS100;
17477             else if (!strcasecmp(v->value, "4ess"))
17478                confp->pri.pri.switchtype = PRI_SWITCH_ATT4ESS;
17479             else if (!strcasecmp(v->value, "5ess"))
17480                confp->pri.pri.switchtype = PRI_SWITCH_LUCENT5E;
17481             else if (!strcasecmp(v->value, "euroisdn"))
17482                confp->pri.pri.switchtype = PRI_SWITCH_EUROISDN_E1;
17483             else if (!strcasecmp(v->value, "qsig"))
17484                confp->pri.pri.switchtype = PRI_SWITCH_QSIG;
17485             else {
17486                ast_log(LOG_ERROR, "Unknown switchtype '%s' at line %d.\n", v->value, v->lineno);
17487                return -1;
17488             }
17489          } else if (!strcasecmp(v->name, "msn")) {
17490             ast_copy_string(confp->pri.pri.msn_list, v->value,
17491                sizeof(confp->pri.pri.msn_list));
17492          } else if (!strcasecmp(v->name, "nsf")) {
17493             if (!strcasecmp(v->value, "sdn"))
17494                confp->pri.pri.nsf = PRI_NSF_SDN;
17495             else if (!strcasecmp(v->value, "megacom"))
17496                confp->pri.pri.nsf = PRI_NSF_MEGACOM;
17497             else if (!strcasecmp(v->value, "tollfreemegacom"))
17498                confp->pri.pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
17499             else if (!strcasecmp(v->value, "accunet"))
17500                confp->pri.pri.nsf = PRI_NSF_ACCUNET;
17501             else if (!strcasecmp(v->value, "none"))
17502                confp->pri.pri.nsf = PRI_NSF_NONE;
17503             else {
17504                ast_log(LOG_WARNING, "Unknown network-specific facility '%s' at line %d.\n", v->value, v->lineno);
17505                confp->pri.pri.nsf = PRI_NSF_NONE;
17506             }
17507          } else if (!strcasecmp(v->name, "priindication")) {
17508             if (!strcasecmp(v->value, "outofband"))
17509                confp->chan.priindication_oob = 1;
17510             else if (!strcasecmp(v->value, "inband"))
17511                confp->chan.priindication_oob = 0;
17512             else
17513                ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d.\n",
17514                   v->value, v->lineno);
17515          } else if (!strcasecmp(v->name, "priexclusive")) {
17516             confp->chan.priexclusive = ast_true(v->value);
17517          } else if (!strcasecmp(v->name, "internationalprefix")) {
17518             ast_copy_string(confp->pri.pri.internationalprefix, v->value, sizeof(confp->pri.pri.internationalprefix));
17519          } else if (!strcasecmp(v->name, "nationalprefix")) {
17520             ast_copy_string(confp->pri.pri.nationalprefix, v->value, sizeof(confp->pri.pri.nationalprefix));
17521          } else if (!strcasecmp(v->name, "localprefix")) {
17522             ast_copy_string(confp->pri.pri.localprefix, v->value, sizeof(confp->pri.pri.localprefix));
17523          } else if (!strcasecmp(v->name, "privateprefix")) {
17524             ast_copy_string(confp->pri.pri.privateprefix, v->value, sizeof(confp->pri.pri.privateprefix));
17525          } else if (!strcasecmp(v->name, "unknownprefix")) {
17526             ast_copy_string(confp->pri.pri.unknownprefix, v->value, sizeof(confp->pri.pri.unknownprefix));
17527          } else if (!strcasecmp(v->name, "resetinterval")) {
17528             if (!strcasecmp(v->value, "never"))
17529                confp->pri.pri.resetinterval = -1;
17530             else if (atoi(v->value) >= 60)
17531                confp->pri.pri.resetinterval = atoi(v->value);
17532             else
17533                ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d.\n",
17534                   v->value, v->lineno);
17535          } else if (!strcasecmp(v->name, "minunused")) {
17536             confp->pri.pri.minunused = atoi(v->value);
17537          } else if (!strcasecmp(v->name, "minidle")) {
17538             confp->pri.pri.minidle = atoi(v->value);
17539          } else if (!strcasecmp(v->name, "idleext")) {
17540             ast_copy_string(confp->pri.pri.idleext, v->value, sizeof(confp->pri.pri.idleext));
17541          } else if (!strcasecmp(v->name, "idledial")) {
17542             ast_copy_string(confp->pri.pri.idledial, v->value, sizeof(confp->pri.pri.idledial));
17543          } else if (!strcasecmp(v->name, "overlapdial")) {
17544             if (ast_true(v->value)) {
17545                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
17546             } else if (!strcasecmp(v->value, "incoming")) {
17547                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_INCOMING;
17548             } else if (!strcasecmp(v->value, "outgoing")) {
17549                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_OUTGOING;
17550             } else if (!strcasecmp(v->value, "both") || ast_true(v->value)) {
17551                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
17552             } else {
17553                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_NONE;
17554             }
17555 #ifdef HAVE_PRI_PROG_W_CAUSE
17556          } else if (!strcasecmp(v->name, "qsigchannelmapping")) {
17557             if (!strcasecmp(v->value, "logical")) {
17558                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_LOGICAL;
17559             } else if (!strcasecmp(v->value, "physical")) {
17560                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
17561             } else {
17562                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
17563             }
17564 #endif
17565          } else if (!strcasecmp(v->name, "discardremoteholdretrieval")) {
17566             confp->pri.pri.discardremoteholdretrieval = ast_true(v->value);
17567 #if defined(HAVE_PRI_SERVICE_MESSAGES)
17568          } else if (!strcasecmp(v->name, "service_message_support")) {
17569             /* assuming switchtype for this channel group has been configured already */
17570             if ((confp->pri.pri.switchtype == PRI_SWITCH_ATT4ESS 
17571                || confp->pri.pri.switchtype == PRI_SWITCH_LUCENT5E
17572                || confp->pri.pri.switchtype == PRI_SWITCH_NI2) && ast_true(v->value)) {
17573                confp->pri.pri.enable_service_message_support = 1;
17574             } else {
17575                confp->pri.pri.enable_service_message_support = 0;
17576             }
17577 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
17578 #ifdef HAVE_PRI_INBANDDISCONNECT
17579          } else if (!strcasecmp(v->name, "inbanddisconnect")) {
17580             confp->pri.pri.inbanddisconnect = ast_true(v->value);
17581 #endif
17582          } else if (!strcasecmp(v->name, "pritimer")) {
17583 #ifdef PRI_GETSET_TIMERS
17584             char tmp[20];
17585             char *timerc;
17586             char *c;
17587             int timer;
17588             int timeridx;
17589 
17590             ast_copy_string(tmp, v->value, sizeof(tmp));
17591             c = tmp;
17592             timerc = strsep(&c, ",");
17593             if (!ast_strlen_zero(timerc) && !ast_strlen_zero(c)) {
17594                timeridx = pri_timer2idx(timerc);
17595                timer = atoi(c);
17596                if (timeridx < 0 || PRI_MAX_TIMERS <= timeridx) {
17597                   ast_log(LOG_WARNING,
17598                      "'%s' is not a valid ISDN timer at line %d.\n", timerc,
17599                      v->lineno);
17600                } else if (!timer) {
17601                   ast_log(LOG_WARNING,
17602                      "'%s' is not a valid value for ISDN timer '%s' at line %d.\n",
17603                      c, timerc, v->lineno);
17604                } else {
17605                   confp->pri.pri.pritimers[timeridx] = timer;
17606                }
17607             } else {
17608                ast_log(LOG_WARNING,
17609                   "'%s' is not a valid ISDN timer configuration string at line %d.\n",
17610                   v->value, v->lineno);
17611             }
17612 #endif /* PRI_GETSET_TIMERS */
17613          } else if (!strcasecmp(v->name, "facilityenable")) {
17614             confp->pri.pri.facilityenable = ast_true(v->value);
17615 #if defined(HAVE_PRI_AOC_EVENTS)
17616          } else if (!strcasecmp(v->name, "aoc_enable")) {
17617             confp->pri.pri.aoc_passthrough_flag = 0;
17618             if (strchr(v->value, 's') || strchr(v->value, 'S')) {
17619                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_S;
17620             }
17621             if (strchr(v->value, 'd') || strchr(v->value, 'D')) {
17622                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_D;
17623             }
17624             if (strchr(v->value, 'e') || strchr(v->value, 'E')) {
17625                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_E;
17626             }
17627          } else if (!strcasecmp(v->name, "aoce_delayhangup")) {
17628             confp->pri.pri.aoce_delayhangup = ast_true(v->value);
17629 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
17630 #if defined(HAVE_PRI_CALL_HOLD)
17631          } else if (!strcasecmp(v->name, "hold_disconnect_transfer")) {
17632             confp->pri.pri.hold_disconnect_transfer = ast_true(v->value);
17633 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
17634 #if defined(HAVE_PRI_CCSS)
17635          } else if (!strcasecmp(v->name, "cc_ptmp_recall_mode")) {
17636             if (!strcasecmp(v->value, "global")) {
17637                confp->pri.pri.cc_ptmp_recall_mode = 0;/* globalRecall */
17638             } else if (!strcasecmp(v->value, "specific")) {
17639                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
17640             } else {
17641                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
17642             }
17643          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_req")) {
17644             if (!strcasecmp(v->value, "release")) {
17645                confp->pri.pri.cc_qsig_signaling_link_req = 0;/* release */
17646             } else if (!strcasecmp(v->value, "retain")) {
17647                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
17648             } else if (!strcasecmp(v->value, "do_not_care")) {
17649                confp->pri.pri.cc_qsig_signaling_link_req = 2;/* do-not-care */
17650             } else {
17651                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
17652             }
17653          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_rsp")) {
17654             if (!strcasecmp(v->value, "release")) {
17655                confp->pri.pri.cc_qsig_signaling_link_rsp = 0;/* release */
17656             } else if (!strcasecmp(v->value, "retain")) {
17657                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
17658             } else {
17659                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
17660             }
17661 #endif   /* defined(HAVE_PRI_CCSS) */
17662 #if defined(HAVE_PRI_CALL_WAITING)
17663          } else if (!strcasecmp(v->name, "max_call_waiting_calls")) {
17664             confp->pri.pri.max_call_waiting_calls = atoi(v->value);
17665             if (confp->pri.pri.max_call_waiting_calls < 0) {
17666                /* Negative values are not allowed. */
17667                confp->pri.pri.max_call_waiting_calls = 0;
17668             }
17669          } else if (!strcasecmp(v->name, "allow_call_waiting_calls")) {
17670             confp->pri.pri.allow_call_waiting_calls = ast_true(v->value);
17671 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
17672 #if defined(HAVE_PRI_MWI)
17673          } else if (!strcasecmp(v->name, "mwi_mailboxes")) {
17674             ast_copy_string(confp->pri.pri.mwi_mailboxes, v->value,
17675                sizeof(confp->pri.pri.mwi_mailboxes));
17676 #endif   /* defined(HAVE_PRI_MWI) */
17677          } else if (!strcasecmp(v->name, "append_msn_to_cid_tag")) {
17678             confp->pri.pri.append_msn_to_user_tag = ast_true(v->value);
17679          } else if (!strcasecmp(v->name, "layer1_presence")) {
17680             if (!strcasecmp(v->value, "required")) {
17681                confp->pri.pri.layer1_ignored = 0;
17682             } else if (!strcasecmp(v->value, "ignore")) {
17683                confp->pri.pri.layer1_ignored = 1;
17684             } else {
17685                /* Default */
17686                confp->pri.pri.layer1_ignored = 0;
17687             }
17688 #if defined(HAVE_PRI_L2_PERSISTENCE)
17689          } else if (!strcasecmp(v->name, "layer2_persistence")) {
17690             if (!strcasecmp(v->value, "keep_up")) {
17691                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_KEEP_UP;
17692             } else if (!strcasecmp(v->value, "leave_down")) {
17693                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_LEAVE_DOWN;
17694             } else {
17695                confp->pri.pri.l2_persistence = PRI_L2_PERSISTENCE_DEFAULT;
17696             }
17697 #endif   /* defined(HAVE_PRI_L2_PERSISTENCE) */
17698 #endif /* HAVE_PRI */
17699 #if defined(HAVE_SS7)
17700          } else if (!strcasecmp(v->name, "ss7type")) {
17701             if (!strcasecmp(v->value, "itu")) {
17702                cur_ss7type = SS7_ITU;
17703             } else if (!strcasecmp(v->value, "ansi")) {
17704                cur_ss7type = SS7_ANSI;
17705             } else
17706                ast_log(LOG_WARNING, "'%s' is an unknown ss7 switch type at line %d.!\n", v->value, v->lineno);
17707          } else if (!strcasecmp(v->name, "linkset")) {
17708             cur_linkset = atoi(v->value);
17709          } else if (!strcasecmp(v->name, "pointcode")) {
17710             cur_pointcode = parse_pointcode(v->value);
17711          } else if (!strcasecmp(v->name, "adjpointcode")) {
17712             cur_adjpointcode = parse_pointcode(v->value);
17713          } else if (!strcasecmp(v->name, "defaultdpc")) {
17714             cur_defaultdpc = parse_pointcode(v->value);
17715          } else if (!strcasecmp(v->name, "cicbeginswith")) {
17716             cur_cicbeginswith = atoi(v->value);
17717          } else if (!strcasecmp(v->name, "networkindicator")) {
17718             if (!strcasecmp(v->value, "national"))
17719                cur_networkindicator = SS7_NI_NAT;
17720             else if (!strcasecmp(v->value, "national_spare"))
17721                cur_networkindicator = SS7_NI_NAT_SPARE;
17722             else if (!strcasecmp(v->value, "international"))
17723                cur_networkindicator = SS7_NI_INT;
17724             else if (!strcasecmp(v->value, "international_spare"))
17725                cur_networkindicator = SS7_NI_INT_SPARE;
17726             else
17727                cur_networkindicator = -1;
17728          } else if (!strcasecmp(v->name, "ss7_internationalprefix")) {
17729             ast_copy_string(confp->ss7.ss7.internationalprefix, v->value, sizeof(confp->ss7.ss7.internationalprefix));
17730          } else if (!strcasecmp(v->name, "ss7_nationalprefix")) {
17731             ast_copy_string(confp->ss7.ss7.nationalprefix, v->value, sizeof(confp->ss7.ss7.nationalprefix));
17732          } else if (!strcasecmp(v->name, "ss7_subscriberprefix")) {
17733             ast_copy_string(confp->ss7.ss7.subscriberprefix, v->value, sizeof(confp->ss7.ss7.subscriberprefix));
17734          } else if (!strcasecmp(v->name, "ss7_unknownprefix")) {
17735             ast_copy_string(confp->ss7.ss7.unknownprefix, v->value, sizeof(confp->ss7.ss7.unknownprefix));
17736          } else if (!strcasecmp(v->name, "ss7_called_nai")) {
17737             if (!strcasecmp(v->value, "national")) {
17738                confp->ss7.ss7.called_nai = SS7_NAI_NATIONAL;
17739             } else if (!strcasecmp(v->value, "international")) {
17740                confp->ss7.ss7.called_nai = SS7_NAI_INTERNATIONAL;
17741             } else if (!strcasecmp(v->value, "subscriber")) {
17742                confp->ss7.ss7.called_nai = SS7_NAI_SUBSCRIBER;
17743             } else if (!strcasecmp(v->value, "unknown")) {
17744                confp->ss7.ss7.called_nai = SS7_NAI_UNKNOWN;
17745             } else if (!strcasecmp(v->value, "dynamic")) {
17746                confp->ss7.ss7.called_nai = SS7_NAI_DYNAMIC;
17747             } else {
17748                ast_log(LOG_WARNING, "Unknown SS7 called_nai '%s' at line %d.\n", v->value, v->lineno);
17749             }
17750          } else if (!strcasecmp(v->name, "ss7_calling_nai")) {
17751             if (!strcasecmp(v->value, "national")) {
17752                confp->ss7.ss7.calling_nai = SS7_NAI_NATIONAL;
17753             } else if (!strcasecmp(v->value, "international")) {
17754                confp->ss7.ss7.calling_nai = SS7_NAI_INTERNATIONAL;
17755             } else if (!strcasecmp(v->value, "subscriber")) {
17756                confp->ss7.ss7.calling_nai = SS7_NAI_SUBSCRIBER;
17757             } else if (!strcasecmp(v->value, "unknown")) {
17758                confp->ss7.ss7.calling_nai = SS7_NAI_UNKNOWN;
17759             } else if (!strcasecmp(v->value, "dynamic")) {
17760                confp->ss7.ss7.calling_nai = SS7_NAI_DYNAMIC;
17761             } else {
17762                ast_log(LOG_WARNING, "Unknown SS7 calling_nai '%s' at line %d.\n", v->value, v->lineno);
17763             }
17764          } else if (!strcasecmp(v->name, "sigchan")) {
17765             int sigchan, res;
17766             sigchan = atoi(v->value);
17767             res = linkset_addsigchan(sigchan);
17768             if (res < 0)
17769                return -1;
17770 
17771          } else if (!strcasecmp(v->name, "ss7_explicitacm")) {
17772             struct dahdi_ss7 *link;
17773             link = ss7_resolve_linkset(cur_linkset);
17774             if (!link) {
17775                ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
17776                return -1;
17777             }
17778             if (ast_true(v->value))
17779                link->ss7.flags |= LINKSET_FLAG_EXPLICITACM;
17780 #endif   /* defined(HAVE_SS7) */
17781 #ifdef HAVE_OPENR2
17782          } else if (!strcasecmp(v->name, "mfcr2_advanced_protocol_file")) {
17783             ast_copy_string(confp->mfcr2.r2proto_file, v->value, sizeof(confp->mfcr2.r2proto_file));
17784             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);
17785          } else if (!strcasecmp(v->name, "mfcr2_logdir")) {
17786             ast_copy_string(confp->mfcr2.logdir, v->value, sizeof(confp->mfcr2.logdir));
17787          } else if (!strcasecmp(v->name, "mfcr2_variant")) {
17788             confp->mfcr2.variant = openr2_proto_get_variant(v->value);
17789             if (OR2_VAR_UNKNOWN == confp->mfcr2.variant) {
17790                ast_log(LOG_WARNING, "Unknown MFC/R2 variant '%s' at line %d, defaulting to ITU.\n", v->value, v->lineno);
17791                confp->mfcr2.variant = OR2_VAR_ITU;
17792             }
17793          } else if (!strcasecmp(v->name, "mfcr2_mfback_timeout")) {
17794             confp->mfcr2.mfback_timeout = atoi(v->value);
17795             if (!confp->mfcr2.mfback_timeout) {
17796                ast_log(LOG_WARNING, "MF timeout of 0? hum, I will protect you from your ignorance. Setting default.\n");
17797                confp->mfcr2.mfback_timeout = -1;
17798             } else if (confp->mfcr2.mfback_timeout > 0 && confp->mfcr2.mfback_timeout < 500) {
17799                ast_log(LOG_WARNING, "MF timeout less than 500ms is not recommended, you have been warned!\n");
17800             }
17801          } else if (!strcasecmp(v->name, "mfcr2_metering_pulse_timeout")) {
17802             confp->mfcr2.metering_pulse_timeout = atoi(v->value);
17803             if (confp->mfcr2.metering_pulse_timeout > 500) {
17804                ast_log(LOG_WARNING, "Metering pulse timeout greater than 500ms is not recommended, you have been warned!\n");
17805             }
17806          } else if (!strcasecmp(v->name, "mfcr2_get_ani_first")) {
17807             confp->mfcr2.get_ani_first = ast_true(v->value) ? 1 : 0;
17808          } else if (!strcasecmp(v->name, "mfcr2_double_answer")) {
17809             confp->mfcr2.double_answer = ast_true(v->value) ? 1 : 0;
17810          } else if (!strcasecmp(v->name, "mfcr2_charge_calls")) {
17811             confp->mfcr2.charge_calls = ast_true(v->value) ? 1 : 0;
17812          } else if (!strcasecmp(v->name, "mfcr2_accept_on_offer")) {
17813             confp->mfcr2.accept_on_offer = ast_true(v->value) ? 1 : 0;
17814          } else if (!strcasecmp(v->name, "mfcr2_allow_collect_calls")) {
17815             confp->mfcr2.allow_collect_calls = ast_true(v->value) ? 1 : 0;
17816          } else if (!strcasecmp(v->name, "mfcr2_forced_release")) {
17817             confp->mfcr2.forced_release = ast_true(v->value) ? 1 : 0;
17818          } else if (!strcasecmp(v->name, "mfcr2_immediate_accept")) {
17819             confp->mfcr2.immediate_accept = ast_true(v->value) ? 1 : 0;
17820 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
17821          } else if (!strcasecmp(v->name, "mfcr2_skip_category")) {
17822             confp->mfcr2.skip_category_request = ast_true(v->value) ? 1 : 0;
17823 #endif
17824          } else if (!strcasecmp(v->name, "mfcr2_call_files")) {
17825             confp->mfcr2.call_files = ast_true(v->value) ? 1 : 0;
17826          } else if (!strcasecmp(v->name, "mfcr2_max_ani")) {
17827             confp->mfcr2.max_ani = atoi(v->value);
17828             if (confp->mfcr2.max_ani >= AST_MAX_EXTENSION){
17829                confp->mfcr2.max_ani = AST_MAX_EXTENSION - 1;
17830             }
17831          } else if (!strcasecmp(v->name, "mfcr2_max_dnis")) {
17832             confp->mfcr2.max_dnis = atoi(v->value);
17833             if (confp->mfcr2.max_dnis >= AST_MAX_EXTENSION){
17834                confp->mfcr2.max_dnis = AST_MAX_EXTENSION - 1;
17835             }
17836          } else if (!strcasecmp(v->name, "mfcr2_category")) {
17837             confp->mfcr2.category = openr2_proto_get_category(v->value);
17838             if (OR2_CALLING_PARTY_CATEGORY_UNKNOWN == confp->mfcr2.category) {
17839                confp->mfcr2.category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER;
17840                ast_log(LOG_WARNING, "Invalid MFC/R2 caller category '%s' at line %d. Using national subscriber as default.\n",
17841                      v->value, v->lineno);
17842             }
17843          } else if (!strcasecmp(v->name, "mfcr2_logging")) {
17844             openr2_log_level_t tmplevel;
17845             char *clevel;
17846             char *logval = ast_strdupa(v->value);
17847             while (logval) {
17848                clevel = strsep(&logval,",");
17849                if (-1 == (tmplevel = openr2_log_get_level(clevel))) {
17850                   ast_log(LOG_WARNING, "Ignoring invalid logging level: '%s' at line %d.\n", clevel, v->lineno);
17851                   continue;
17852                }
17853                confp->mfcr2.loglevel |= tmplevel;
17854             }
17855 #endif /* HAVE_OPENR2 */
17856          } else if (!strcasecmp(v->name, "cadence")) {
17857             /* setup to scan our argument */
17858             int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
17859             int i;
17860             struct dahdi_ring_cadence new_cadence;
17861             int cid_location = -1;
17862             int firstcadencepos = 0;
17863             char original_args[80];
17864             int cadence_is_ok = 1;
17865 
17866             ast_copy_string(original_args, v->value, sizeof(original_args));
17867             /* 16 cadences allowed (8 pairs) */
17868             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]);
17869 
17870             /* Cadence must be even (on/off) */
17871             if (element_count % 2 == 1) {
17872                ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s at line %d.\n", original_args, v->lineno);
17873                cadence_is_ok = 0;
17874             }
17875 
17876             /* Ring cadences cannot be negative */
17877             for (i = 0; i < element_count; i++) {
17878                if (c[i] == 0) {
17879                   ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s at line %d.\n", original_args, v->lineno);
17880                   cadence_is_ok = 0;
17881                   break;
17882                } else if (c[i] < 0) {
17883                   if (i % 2 == 1) {
17884                      /* Silence duration, negative possibly okay */
17885                      if (cid_location == -1) {
17886                         cid_location = i;
17887                         c[i] *= -1;
17888                      } else {
17889                         ast_log(LOG_ERROR, "CID location specified twice: %s at line %d.\n", original_args, v->lineno);
17890                         cadence_is_ok = 0;
17891                         break;
17892                      }
17893                   } else {
17894                      if (firstcadencepos == 0) {
17895                         firstcadencepos = i; /* only recorded to avoid duplicate specification */
17896                                  /* duration will be passed negative to the DAHDI driver */
17897                      } else {
17898                          ast_log(LOG_ERROR, "First cadence position specified twice: %s at line %d.\n", original_args, v->lineno);
17899                         cadence_is_ok = 0;
17900                         break;
17901                      }
17902                   }
17903                }
17904             }
17905 
17906             /* Substitute our scanned cadence */
17907             for (i = 0; i < 16; i++) {
17908                new_cadence.ringcadence[i] = c[i];
17909             }
17910 
17911             if (cadence_is_ok) {
17912                /* ---we scanned it without getting annoyed; now some sanity checks--- */
17913                if (element_count < 2) {
17914                   ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s at line %d.\n", original_args, v->lineno);
17915                } else {
17916                   if (cid_location == -1) {
17917                      /* user didn't say; default to first pause */
17918                      cid_location = 1;
17919                   } else {
17920                      /* convert element_index to cidrings value */
17921                      cid_location = (cid_location + 1) / 2;
17922                   }
17923                   /* ---we like their cadence; try to install it--- */
17924                   if (!user_has_defined_cadences++)
17925                      /* this is the first user-defined cadence; clear the default user cadences */
17926                      num_cadence = 0;
17927                   if ((num_cadence+1) >= NUM_CADENCE_MAX)
17928                      ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s at line %d.\n", NUM_CADENCE_MAX, original_args, v->lineno);
17929                   else {
17930                      cadences[num_cadence] = new_cadence;
17931                      cidrings[num_cadence++] = cid_location;
17932                      ast_verb(3, "cadence 'r%d' added: %s\n",num_cadence,original_args);
17933                   }
17934                }
17935             }
17936          } else if (!strcasecmp(v->name, "ringtimeout")) {
17937             ringt_base = (atoi(v->value) * 8) / READ_SIZE;
17938          } else if (!strcasecmp(v->name, "prewink")) {
17939             confp->timing.prewinktime = atoi(v->value);
17940          } else if (!strcasecmp(v->name, "preflash")) {
17941             confp->timing.preflashtime = atoi(v->value);
17942          } else if (!strcasecmp(v->name, "wink")) {
17943             confp->timing.winktime = atoi(v->value);
17944          } else if (!strcasecmp(v->name, "flash")) {
17945             confp->timing.flashtime = atoi(v->value);
17946          } else if (!strcasecmp(v->name, "start")) {
17947             confp->timing.starttime = atoi(v->value);
17948          } else if (!strcasecmp(v->name, "rxwink")) {
17949             confp->timing.rxwinktime = atoi(v->value);
17950          } else if (!strcasecmp(v->name, "rxflash")) {
17951             confp->timing.rxflashtime = atoi(v->value);
17952          } else if (!strcasecmp(v->name, "debounce")) {
17953             confp->timing.debouncetime = atoi(v->value);
17954          } else if (!strcasecmp(v->name, "toneduration")) {
17955             int toneduration;
17956             int ctlfd;
17957             int res;
17958             struct dahdi_dialparams dps;
17959 
17960             ctlfd = open("/dev/dahdi/ctl", O_RDWR);
17961             if (ctlfd == -1) {
17962                ast_log(LOG_ERROR, "Unable to open /dev/dahdi/ctl to set toneduration at line %d.\n", v->lineno);
17963                return -1;
17964             }
17965 
17966             toneduration = atoi(v->value);
17967             if (toneduration > -1) {
17968                memset(&dps, 0, sizeof(dps));
17969 
17970                dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
17971                res = ioctl(ctlfd, DAHDI_SET_DIALPARAMS, &dps);
17972                if (res < 0) {
17973                   ast_log(LOG_ERROR, "Invalid tone duration: %d ms at line %d: %s\n", toneduration, v->lineno, strerror(errno));
17974                   close(ctlfd);
17975                   return -1;
17976                }
17977             }
17978             close(ctlfd);
17979          } else if (!strcasecmp(v->name, "defaultcic")) {
17980             ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
17981          } else if (!strcasecmp(v->name, "defaultozz")) {
17982             ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
17983          } else if (!strcasecmp(v->name, "mwilevel")) {
17984             mwilevel = atoi(v->value);
17985          } else if (!strcasecmp(v->name, "dtmfcidlevel")) {
17986             dtmfcid_level = atoi(v->value);
17987          } else if (!strcasecmp(v->name, "reportalarms")) {
17988             if (!strcasecmp(v->value, "all"))
17989                report_alarms = REPORT_CHANNEL_ALARMS | REPORT_SPAN_ALARMS;
17990             if (!strcasecmp(v->value, "none"))
17991                report_alarms = 0;
17992             else if (!strcasecmp(v->value, "channels"))
17993                report_alarms = REPORT_CHANNEL_ALARMS;
17994             else if (!strcasecmp(v->value, "spans"))
17995                report_alarms = REPORT_SPAN_ALARMS;
17996           }
17997       } else if (!(options & PROC_DAHDI_OPT_NOWARN) )
17998          ast_log(LOG_WARNING, "Ignoring any changes to '%s' (on reload) at line %d.\n", v->name, v->lineno);
17999    }
18000 
18001    /* Since confp has already filled invidual dahdi_pvt objects with channels at this point, clear the variables in confp's pvt. */
18002    if (confp->chan.vars) {
18003       ast_variables_destroy(confp->chan.vars);
18004       confp->chan.vars = NULL;
18005    }
18006 
18007    if (dahdichan) {
18008       /* Process the deferred dahdichan value. */
18009       if (build_channels(confp, dahdichan->value, reload, dahdichan->lineno,
18010          &found_pseudo)) {
18011          if (confp->ignore_failed_channels) {
18012             ast_log(LOG_WARNING,
18013                "Dahdichan '%s' failure ignored: ignore_failed_channels.\n",
18014                dahdichan->value);
18015          } else {
18016             return -1;
18017          }
18018       }
18019    }
18020 
18021    /* mark the first channels of each DAHDI span to watch for their span alarms */
18022    for (tmp = iflist, y=-1; tmp; tmp = tmp->next) {
18023       if (!tmp->destroy && tmp->span != y) {
18024          tmp->manages_span_alarms = 1;
18025          y = tmp->span; 
18026       } else {
18027          tmp->manages_span_alarms = 0;
18028       }
18029    }
18030 
18031    /*< \todo why check for the pseudo in the per-channel section.
18032     * Any actual use for manual setup of the pseudo channel? */
18033    if (!found_pseudo && reload != 1 && !(options & PROC_DAHDI_OPT_NOCHAN)) {
18034       /* use the default configuration for a channel, so
18035          that any settings from real configured channels
18036          don't "leak" into the pseudo channel config
18037       */
18038       struct dahdi_chan_conf conf = dahdi_chan_conf_default();
18039 
18040       if (conf.chan.cc_params) {
18041          tmp = mkintf(CHAN_PSEUDO, &conf, reload);
18042       } else {
18043          tmp = NULL;
18044       }
18045       if (tmp) {
18046          ast_verb(3, "Automatically generated pseudo channel\n");
18047       } else {
18048          ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
18049       }
18050       ast_cc_config_params_destroy(conf.chan.cc_params);
18051    }
18052    return 0;
18053 }
18054 
18055 /*!
18056  * \internal
18057  * \brief Deep copy struct dahdi_chan_conf.
18058  * \since 1.8
18059  *
18060  * \param dest Destination.
18061  * \param src Source.
18062  *
18063  * \return Nothing
18064  */
18065 static void deep_copy_dahdi_chan_conf(struct dahdi_chan_conf *dest, const struct dahdi_chan_conf *src)
18066 {
18067    struct ast_cc_config_params *cc_params;
18068 
18069    cc_params = dest->chan.cc_params;
18070    *dest = *src;
18071    dest->chan.cc_params = cc_params;
18072    ast_cc_copy_config_params(dest->chan.cc_params, src->chan.cc_params);
18073 }
18074 
18075 /*!
18076  * \internal
18077  * \brief Setup DAHDI channel driver.
18078  *
18079  * \param reload enum: load_module(0), reload(1), restart(2).
18080  * \param default_conf Default config parameters.  So cc_params can be properly destroyed.
18081  * \param base_conf Default config parameters per section.  So cc_params can be properly destroyed.
18082  * \param conf Local config parameters.  So cc_params can be properly destroyed.
18083  *
18084  * \retval 0 on success.
18085  * \retval -1 on error.
18086  */
18087 static int setup_dahdi_int(int reload, struct dahdi_chan_conf *default_conf, struct dahdi_chan_conf *base_conf, struct dahdi_chan_conf *conf)
18088 {
18089    struct ast_config *cfg;
18090    struct ast_config *ucfg;
18091    struct ast_variable *v;
18092    struct ast_flags config_flags = { reload == 1 ? CONFIG_FLAG_FILEUNCHANGED : 0 };
18093    const char *chans;
18094    const char *cat;
18095    int res;
18096 
18097 #ifdef HAVE_PRI
18098    char *c;
18099    int spanno;
18100    int i;
18101    int logicalspan;
18102    int trunkgroup;
18103    int dchannels[SIG_PRI_NUM_DCHANS];
18104 #endif
18105    int have_cfg_now;
18106    static int had_cfg_before = 1;/* So initial load will complain if we don't have cfg. */
18107 
18108    cfg = ast_config_load(config, config_flags);
18109    have_cfg_now = !!cfg;
18110    if (!cfg) {
18111       /* Error if we have no config file */
18112       if (had_cfg_before) {
18113          ast_log(LOG_ERROR, "Unable to load config %s\n", config);
18114          ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18115       }
18116       cfg = ast_config_new();/* Dummy config */
18117       if (!cfg) {
18118          return 0;
18119       }
18120       ucfg = ast_config_load("users.conf", config_flags);
18121       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
18122          ast_config_destroy(cfg);
18123          return 0;
18124       }
18125       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18126          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18127          ast_config_destroy(cfg);
18128          return 0;
18129       }
18130    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
18131       ucfg = ast_config_load("users.conf", config_flags);
18132       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
18133          return 0;
18134       }
18135       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18136          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18137          return 0;
18138       }
18139       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18140       cfg = ast_config_load(config, config_flags);
18141       have_cfg_now = !!cfg;
18142       if (!cfg) {
18143          if (had_cfg_before) {
18144             /* We should have been able to load the config. */
18145             ast_log(LOG_ERROR, "Bad. Unable to load config %s\n", config);
18146             ast_config_destroy(ucfg);
18147             return 0;
18148          }
18149          cfg = ast_config_new();/* Dummy config */
18150          if (!cfg) {
18151             ast_config_destroy(ucfg);
18152             return 0;
18153          }
18154       } else if (cfg == CONFIG_STATUS_FILEINVALID) {
18155          ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
18156          ast_config_destroy(ucfg);
18157          return 0;
18158       }
18159    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
18160       ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
18161       return 0;
18162    } else {
18163       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
18164       ucfg = ast_config_load("users.conf", config_flags);
18165       if (ucfg == CONFIG_STATUS_FILEINVALID) {
18166          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
18167          ast_config_destroy(cfg);
18168          return 0;
18169       }
18170    }
18171    had_cfg_before = have_cfg_now;
18172 
18173    /* It's a little silly to lock it, but we might as well just to be sure */
18174    ast_mutex_lock(&iflock);
18175 #ifdef HAVE_PRI
18176    if (reload != 1) {
18177       /* Process trunkgroups first */
18178       v = ast_variable_browse(cfg, "trunkgroups");
18179       while (v) {
18180          if (!strcasecmp(v->name, "trunkgroup")) {
18181             trunkgroup = atoi(v->value);
18182             if (trunkgroup > 0) {
18183                if ((c = strchr(v->value, ','))) {
18184                   i = 0;
18185                   memset(dchannels, 0, sizeof(dchannels));
18186                   while (c && (i < SIG_PRI_NUM_DCHANS)) {
18187                      dchannels[i] = atoi(c + 1);
18188                      if (dchannels[i] < 0) {
18189                         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);
18190                      } else
18191                         i++;
18192                      c = strchr(c + 1, ',');
18193                   }
18194                   if (i) {
18195                      if (pri_create_trunkgroup(trunkgroup, dchannels)) {
18196                         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);
18197                   } else
18198                         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");
18199                   } else
18200                      ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18201                } else
18202                   ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
18203             } else
18204                ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of chan_dahdi.conf\n", v->lineno);
18205          } else if (!strcasecmp(v->name, "spanmap")) {
18206             spanno = atoi(v->value);
18207             if (spanno > 0) {
18208                if ((c = strchr(v->value, ','))) {
18209                   trunkgroup = atoi(c + 1);
18210                   if (trunkgroup > 0) {
18211                      if ((c = strchr(c + 1, ',')))
18212                         logicalspan = atoi(c + 1);
18213                      else
18214                         logicalspan = 0;
18215                      if (logicalspan >= 0) {
18216                         if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
18217                            ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
18218                      } else
18219                            ast_verb(2, "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
18220                      } else
18221                         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);
18222                   } else
18223                      ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of chan_dahdi.conf\n", v->lineno);
18224                } else
18225                   ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of chan_dahdi.conf\n", v->lineno);
18226             } else
18227                ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of chan_dahdi.conf\n", v->lineno);
18228          } else {
18229             ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
18230          }
18231          v = v->next;
18232       }
18233    }
18234 #endif
18235 
18236    /* Copy the default jb config over global_jbconf */
18237    memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
18238 
18239    mwimonitornotify[0] = '\0';
18240 
18241    v = ast_variable_browse(cfg, "channels");
18242    if ((res = process_dahdi(base_conf,
18243       "" /* Must be empty for the channels category.  Silly voicemail mailbox. */,
18244       v, reload, 0))) {
18245       ast_mutex_unlock(&iflock);
18246       ast_config_destroy(cfg);
18247       if (ucfg) {
18248          ast_config_destroy(ucfg);
18249       }
18250       return res;
18251    }
18252 
18253    /* Now get configuration from all normal sections in chan_dahdi.conf: */
18254    for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
18255       /* [channels] and [trunkgroups] are used. Let's also reserve
18256        * [globals] and [general] for future use
18257        */
18258       if (!strcasecmp(cat, "general") ||
18259          !strcasecmp(cat, "trunkgroups") ||
18260          !strcasecmp(cat, "globals") ||
18261          !strcasecmp(cat, "channels")) {
18262          continue;
18263       }
18264 
18265       chans = ast_variable_retrieve(cfg, cat, "dahdichan");
18266       if (ast_strlen_zero(chans)) {
18267          /* Section is useless without a dahdichan value present. */
18268          continue;
18269       }
18270 
18271       /* Copy base_conf to conf. */
18272       deep_copy_dahdi_chan_conf(conf, base_conf);
18273 
18274       if ((res = process_dahdi(conf, cat, ast_variable_browse(cfg, cat), reload, PROC_DAHDI_OPT_NOCHAN))) {
18275          ast_mutex_unlock(&iflock);
18276          ast_config_destroy(cfg);
18277          if (ucfg) {
18278             ast_config_destroy(ucfg);
18279          }
18280          return res;
18281       }
18282    }
18283 
18284    ast_config_destroy(cfg);
18285 
18286    if (ucfg) {
18287       /* Reset base_conf, so things don't leak from chan_dahdi.conf */
18288       deep_copy_dahdi_chan_conf(base_conf, default_conf);
18289       process_dahdi(base_conf,
18290          "" /* Must be empty for the general category.  Silly voicemail mailbox. */,
18291          ast_variable_browse(ucfg, "general"), 1, 0);
18292 
18293       for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
18294          if (!strcasecmp(cat, "general")) {
18295             continue;
18296          }
18297 
18298          chans = ast_variable_retrieve(ucfg, cat, "dahdichan");
18299          if (ast_strlen_zero(chans)) {
18300             /* Section is useless without a dahdichan value present. */
18301             continue;
18302          }
18303 
18304          /* Copy base_conf to conf. */
18305          deep_copy_dahdi_chan_conf(conf, base_conf);
18306 
18307          if ((res = process_dahdi(conf, cat, ast_variable_browse(ucfg, cat), reload, PROC_DAHDI_OPT_NOCHAN | PROC_DAHDI_OPT_NOWARN))) {
18308             ast_config_destroy(ucfg);
18309             ast_mutex_unlock(&iflock);
18310             return res;
18311          }
18312       }
18313       ast_config_destroy(ucfg);
18314    }
18315    ast_mutex_unlock(&iflock);
18316 
18317 #ifdef HAVE_PRI
18318    if (reload != 1) {
18319       int x;
18320       for (x = 0; x < NUM_SPANS; x++) {
18321          if (pris[x].pri.pvts[0]) {
18322             prepare_pri(pris + x);
18323             if (sig_pri_start_pri(&pris[x].pri)) {
18324                ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
18325                return -1;
18326             } else
18327                ast_verb(2, "Starting D-Channel on span %d\n", x + 1);
18328          }
18329       }
18330    }
18331 #endif
18332 #if defined(HAVE_SS7)
18333    if (reload != 1) {
18334       int x;
18335       for (x = 0; x < NUM_SPANS; x++) {
18336          if (linksets[x].ss7.ss7) {
18337             linksets[x].ss7.calls = &dahdi_ss7_callbacks;
18338             if (ast_pthread_create(&linksets[x].ss7.master, NULL, ss7_linkset, &linksets[x].ss7)) {
18339                ast_log(LOG_ERROR, "Unable to start SS7 linkset on span %d\n", x + 1);
18340                return -1;
18341             } else
18342                ast_verb(2, "Starting SS7 linkset on span %d\n", x + 1);
18343          }
18344       }
18345    }
18346 #endif   /* defined(HAVE_SS7) */
18347 #ifdef HAVE_OPENR2
18348    if (reload != 1) {
18349       int x;
18350       for (x = 0; x < r2links_count; x++) {
18351          if (ast_pthread_create(&r2links[x]->r2master, NULL, mfcr2_monitor, r2links[x])) {
18352             ast_log(LOG_ERROR, "Unable to start R2 monitor on channel group %d\n", x + 1);
18353             return -1;
18354          } else {
18355             ast_verb(2, "Starting R2 monitor on channel group %d\n", x + 1);
18356          }
18357       }
18358    }
18359 #endif
18360    /* And start the monitor for the first time */
18361    restart_monitor();
18362    return 0;
18363 }
18364 
18365 /*!
18366  * \internal
18367  * \brief Setup DAHDI channel driver.
18368  *
18369  * \param reload enum: load_module(0), reload(1), restart(2).
18370  *
18371  * \retval 0 on success.
18372  * \retval -1 on error.
18373  */
18374 static int setup_dahdi(int reload)
18375 {
18376    int res;
18377    struct dahdi_chan_conf default_conf = dahdi_chan_conf_default();
18378    struct dahdi_chan_conf base_conf = dahdi_chan_conf_default();
18379    struct dahdi_chan_conf conf = dahdi_chan_conf_default();
18380 
18381    if (default_conf.chan.cc_params && base_conf.chan.cc_params && conf.chan.cc_params) {
18382       res = setup_dahdi_int(reload, &default_conf, &base_conf, &conf);
18383    } else {
18384       res = -1;
18385    }
18386    ast_cc_config_params_destroy(default_conf.chan.cc_params);
18387    ast_cc_config_params_destroy(base_conf.chan.cc_params);
18388    ast_cc_config_params_destroy(conf.chan.cc_params);
18389 
18390    return res;
18391 }
18392 
18393 /*!
18394  * \internal
18395  * \brief Callback used to generate the dahdi status tree.
18396  * \param[in] search The search pattern tree.
18397  * \retval NULL on error.
18398  * \retval non-NULL The generated tree.
18399  */
18400 static int dahdi_status_data_provider_get(const struct ast_data_search *search,
18401       struct ast_data *data_root)
18402 {
18403    int ctl, res, span;
18404    struct ast_data *data_span, *data_alarms;
18405    struct dahdi_spaninfo s;
18406 
18407    ctl = open("/dev/dahdi/ctl", O_RDWR);
18408    if (ctl < 0) {
18409       ast_log(LOG_ERROR, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
18410       return -1;
18411    }
18412    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
18413       s.spanno = span;
18414       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
18415       if (res) {
18416          continue;
18417       }
18418 
18419       data_span = ast_data_add_node(data_root, "span");
18420       if (!data_span) {
18421          continue;
18422       }
18423       ast_data_add_str(data_span, "description", s.desc);
18424 
18425       /* insert the alarms status */
18426       data_alarms = ast_data_add_node(data_span, "alarms");
18427       if (!data_alarms) {
18428          continue;
18429       }
18430 
18431       ast_data_add_bool(data_alarms, "BLUE", s.alarms & DAHDI_ALARM_BLUE);
18432       ast_data_add_bool(data_alarms, "YELLOW", s.alarms & DAHDI_ALARM_YELLOW);
18433       ast_data_add_bool(data_alarms, "RED", s.alarms & DAHDI_ALARM_RED);
18434       ast_data_add_bool(data_alarms, "LOOPBACK", s.alarms & DAHDI_ALARM_LOOPBACK);
18435       ast_data_add_bool(data_alarms, "RECOVER", s.alarms & DAHDI_ALARM_RECOVER);
18436       ast_data_add_bool(data_alarms, "NOTOPEN", s.alarms & DAHDI_ALARM_NOTOPEN);
18437 
18438       ast_data_add_int(data_span, "irqmisses", s.irqmisses);
18439       ast_data_add_int(data_span, "bpviol", s.bpvcount);
18440       ast_data_add_int(data_span, "crc4", s.crc4count);
18441       ast_data_add_str(data_span, "framing", s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
18442                      s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
18443                      s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
18444                      "CAS");
18445       ast_data_add_str(data_span, "coding",  s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
18446                      s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
18447                      s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
18448                      "Unknown");
18449       ast_data_add_str(data_span, "options", s.lineconfig & DAHDI_CONFIG_CRC4 ?
18450                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
18451                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "");
18452       ast_data_add_str(data_span, "lbo", lbostr[s.lbo]);
18453 
18454       /* if this span doesn't match remove it. */
18455       if (!ast_data_search_match(search, data_span)) {
18456          ast_data_remove_node(data_root, data_span);
18457       }
18458    }
18459    close(ctl);
18460 
18461    return 0;
18462 }
18463 
18464 /*!
18465  * \internal
18466  * \brief Callback used to generate the dahdi channels tree.
18467  * \param[in] search The search pattern tree.
18468  * \retval NULL on error.
18469  * \retval non-NULL The generated tree.
18470  */
18471 static int dahdi_channels_data_provider_get(const struct ast_data_search *search,
18472       struct ast_data *data_root)
18473 {
18474    struct dahdi_pvt *tmp;
18475    struct ast_data *data_channel;
18476 
18477    ast_mutex_lock(&iflock);
18478    for (tmp = iflist; tmp; tmp = tmp->next) {
18479       data_channel = ast_data_add_node(data_root, "channel");
18480       if (!data_channel) {
18481          continue;
18482       }
18483 
18484       ast_data_add_structure(dahdi_pvt, data_channel, tmp);
18485 
18486       /* if this channel doesn't match remove it. */
18487       if (!ast_data_search_match(search, data_channel)) {
18488          ast_data_remove_node(data_root, data_channel);
18489       }
18490    }
18491    ast_mutex_unlock(&iflock);
18492 
18493    return 0;
18494 }
18495 
18496 /*!
18497  * \internal
18498  * \brief Callback used to generate the dahdi channels tree.
18499  * \param[in] search The search pattern tree.
18500  * \retval NULL on error.
18501  * \retval non-NULL The generated tree.
18502  */
18503 static int dahdi_version_data_provider_get(const struct ast_data_search *search,
18504       struct ast_data *data_root)
18505 {
18506    int pseudo_fd = -1;
18507    struct dahdi_versioninfo vi = {
18508       .version = "Unknown",
18509       .echo_canceller = "Unknown"
18510    };
18511 
18512    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
18513       ast_log(LOG_ERROR, "Failed to open control file to get version.\n");
18514       return -1;
18515    }
18516 
18517    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi)) {
18518       ast_log(LOG_ERROR, "Failed to get DAHDI version: %s\n", strerror(errno));
18519    }
18520 
18521    close(pseudo_fd);
18522 
18523    ast_data_add_str(data_root, "value", vi.version);
18524    ast_data_add_str(data_root, "echocanceller", vi.echo_canceller);
18525 
18526    return 0;
18527 }
18528 
18529 static const struct ast_data_handler dahdi_status_data_provider = {
18530    .version = AST_DATA_HANDLER_VERSION,
18531    .get = dahdi_status_data_provider_get
18532 };
18533 
18534 static const struct ast_data_handler dahdi_channels_data_provider = {
18535    .version = AST_DATA_HANDLER_VERSION,
18536    .get = dahdi_channels_data_provider_get
18537 };
18538 
18539 static const struct ast_data_handler dahdi_version_data_provider = {
18540    .version = AST_DATA_HANDLER_VERSION,
18541    .get = dahdi_version_data_provider_get
18542 };
18543 
18544 static const struct ast_data_entry dahdi_data_providers[] = {
18545    AST_DATA_ENTRY("asterisk/channel/dahdi/status", &dahdi_status_data_provider),
18546    AST_DATA_ENTRY("asterisk/channel/dahdi/channels", &dahdi_channels_data_provider),
18547    AST_DATA_ENTRY("asterisk/channel/dahdi/version", &dahdi_version_data_provider)
18548 };
18549 
18550 static int load_module(void)
18551 {
18552    int res;
18553 #if defined(HAVE_PRI) || defined(HAVE_SS7)
18554    int y;
18555 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
18556 
18557 #ifdef HAVE_PRI
18558    memset(pris, 0, sizeof(pris));
18559    for (y = 0; y < NUM_SPANS; y++) {
18560       sig_pri_init_pri(&pris[y].pri);
18561    }
18562    pri_set_error(dahdi_pri_error);
18563    pri_set_message(dahdi_pri_message);
18564    ast_register_application_xml(dahdi_send_keypad_facility_app, dahdi_send_keypad_facility_exec);
18565 #ifdef HAVE_PRI_PROG_W_CAUSE
18566    ast_register_application_xml(dahdi_send_callrerouting_facility_app, dahdi_send_callrerouting_facility_exec);
18567 #endif
18568 #if defined(HAVE_PRI_CCSS)
18569    if (ast_cc_agent_register(&dahdi_pri_cc_agent_callbacks)
18570       || ast_cc_monitor_register(&dahdi_pri_cc_monitor_callbacks)) {
18571       __unload_module();
18572       return AST_MODULE_LOAD_FAILURE;
18573    }
18574 #endif   /* defined(HAVE_PRI_CCSS) */
18575    if (sig_pri_load(
18576 #if defined(HAVE_PRI_CCSS)
18577       dahdi_pri_cc_type
18578 #else
18579       NULL
18580 #endif   /* defined(HAVE_PRI_CCSS) */
18581       )) {
18582       __unload_module();
18583       return AST_MODULE_LOAD_FAILURE;
18584    }
18585 #endif
18586 #if defined(HAVE_SS7)
18587    memset(linksets, 0, sizeof(linksets));
18588    for (y = 0; y < NUM_SPANS; y++) {
18589       sig_ss7_init_linkset(&linksets[y].ss7);
18590    }
18591    ss7_set_error(dahdi_ss7_error);
18592    ss7_set_message(dahdi_ss7_message);
18593 #endif   /* defined(HAVE_SS7) */
18594    res = setup_dahdi(0);
18595    /* Make sure we can register our DAHDI channel type */
18596    if (res)
18597       return AST_MODULE_LOAD_DECLINE;
18598    if (ast_channel_register(&dahdi_tech)) {
18599       ast_log(LOG_ERROR, "Unable to register channel class 'DAHDI'\n");
18600       __unload_module();
18601       return AST_MODULE_LOAD_FAILURE;
18602    }
18603 #ifdef HAVE_PRI
18604    ast_cli_register_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
18605 #endif
18606 #if defined(HAVE_SS7)
18607    ast_cli_register_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
18608 #endif   /* defined(HAVE_SS7) */
18609 #ifdef HAVE_OPENR2
18610    ast_cli_register_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
18611    ast_register_application_xml(dahdi_accept_r2_call_app, dahdi_accept_r2_call_exec);
18612 #endif
18613 
18614    ast_cli_register_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
18615    /* register all the data providers */
18616    ast_data_register_multiple(dahdi_data_providers, ARRAY_LEN(dahdi_data_providers));
18617    memset(round_robin, 0, sizeof(round_robin));
18618    ast_manager_register_xml("DAHDITransfer", 0, action_transfer);
18619    ast_manager_register_xml("DAHDIHangup", 0, action_transferhangup);
18620    ast_manager_register_xml("DAHDIDialOffhook", 0, action_dahdidialoffhook);
18621    ast_manager_register_xml("DAHDIDNDon", 0, action_dahdidndon);
18622    ast_manager_register_xml("DAHDIDNDoff", 0, action_dahdidndoff);
18623    ast_manager_register_xml("DAHDIShowChannels", 0, action_dahdishowchannels);
18624    ast_manager_register_xml("DAHDIRestart", 0, action_dahdirestart);
18625 
18626    ast_cond_init(&ss_thread_complete, NULL);
18627 
18628    return res;
18629 }
18630 
18631 static int dahdi_sendtext(struct ast_channel *c, const char *text)
18632 {
18633 #define  END_SILENCE_LEN 400
18634 #define  HEADER_MS 50
18635 #define  TRAILER_MS 5
18636 #define  HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
18637 #define  ASCII_BYTES_PER_CHAR 80
18638 
18639    unsigned char *buf,*mybuf;
18640    struct dahdi_pvt *p = c->tech_pvt;
18641    struct pollfd fds[1];
18642    int size,res,fd,len,x;
18643    int bytes=0;
18644    /* Initial carrier (imaginary) */
18645    float cr = 1.0;
18646    float ci = 0.0;
18647    float scont = 0.0;
18648    int idx;
18649 
18650    idx = dahdi_get_index(c, p, 0);
18651    if (idx < 0) {
18652       ast_log(LOG_WARNING, "Huh?  I don't exist?\n");
18653       return -1;
18654    }
18655    if (!text[0]) return(0); /* if nothing to send, don't */
18656    if ((!p->tdd) && (!p->mate)) return(0);  /* if not in TDD mode, just return */
18657    if (p->mate)
18658       buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
18659    else
18660       buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
18661    if (!buf)
18662       return -1;
18663    mybuf = buf;
18664    if (p->mate) {
18665       int codec = AST_LAW(p);
18666       for (x = 0; x < HEADER_MS; x++) {   /* 50 ms of Mark */
18667          PUT_CLID_MARKMS;
18668       }
18669       /* Put actual message */
18670       for (x = 0; text[x]; x++) {
18671          PUT_CLID(text[x]);
18672       }
18673       for (x = 0; x < TRAILER_MS; x++) {  /* 5 ms of Mark */
18674          PUT_CLID_MARKMS;
18675       }
18676       len = bytes;
18677       buf = mybuf;
18678    } else {
18679       len = tdd_generate(p->tdd, buf, text);
18680       if (len < 1) {
18681          ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
18682          ast_free(mybuf);
18683          return -1;
18684       }
18685    }
18686    memset(buf + len, 0x7f, END_SILENCE_LEN);
18687    len += END_SILENCE_LEN;
18688    fd = p->subs[idx].dfd;
18689    while (len) {
18690       if (ast_check_hangup(c)) {
18691          ast_free(mybuf);
18692          return -1;
18693       }
18694       size = len;
18695       if (size > READ_SIZE)
18696          size = READ_SIZE;
18697       fds[0].fd = fd;
18698       fds[0].events = POLLOUT | POLLPRI;
18699       fds[0].revents = 0;
18700       res = poll(fds, 1, -1);
18701       if (!res) {
18702          ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
18703          continue;
18704       }
18705       /* if got exception */
18706       if (fds[0].revents & POLLPRI) {
18707          ast_free(mybuf);
18708          return -1;
18709       }
18710       if (!(fds[0].revents & POLLOUT)) {
18711          ast_debug(1, "write fd not ready on channel %d\n", p->channel);
18712          continue;
18713       }
18714       res = write(fd, buf, size);
18715       if (res != size) {
18716          if (res == -1) {
18717             ast_free(mybuf);
18718             return -1;
18719          }
18720          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
18721          break;
18722       }
18723       len -= size;
18724       buf += size;
18725    }
18726    ast_free(mybuf);
18727    return(0);
18728 }
18729 
18730 
18731 static int reload(void)
18732 {
18733    int res = 0;
18734 
18735    res = setup_dahdi(1);
18736    if (res) {
18737       ast_log(LOG_WARNING, "Reload of chan_dahdi.so is unsuccessful!\n");
18738       return -1;
18739    }
18740    return 0;
18741 }
18742 
18743 /* This is a workaround so that menuselect displays a proper description
18744  * AST_MODULE_INFO(, , "DAHDI Telephony"
18745  */
18746 
18747 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, tdesc,
18748    .load = load_module,
18749    .unload = unload_module,
18750    .reload = reload,
18751    .load_pri = AST_MODPRI_CHANNEL_DRIVER,
18752       .nonoptreq = "res_smdi",
18753    );

Generated on 18 Jan 2013 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1