Sat Mar 26 11:06:52 2011

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  ***/
00048 
00049 #include "asterisk.h"
00050 
00051 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 291656 $")
00052 
00053 #if defined(__NetBSD__) || defined(__FreeBSD__)
00054 #include <pthread.h>
00055 #include <signal.h>
00056 #else
00057 #include <sys/signal.h>
00058 #endif
00059 #include <sys/ioctl.h>
00060 #include <sys/stat.h>
00061 #include <math.h>
00062 #include <ctype.h>
00063 
00064 #include <dahdi/user.h>
00065 #include <dahdi/tonezone.h>
00066 #include "sig_analog.h"
00067 /* Analog signaling is currently still present in chan_dahdi for use with
00068  * radio. Sig_analog does not currently handle any radio operations. If
00069  * radio only uses analog signaling, then the radio handling logic could
00070  * be placed in sig_analog and the duplicated code could be removed.
00071  */
00072 
00073 #ifdef HAVE_PRI
00074 #include "sig_pri.h"
00075 #endif
00076 
00077 #if defined(HAVE_SS7)
00078 #include "sig_ss7.h"
00079 #endif   /* defined(HAVE_SS7) */
00080 
00081 #ifdef HAVE_OPENR2
00082 /* put this here until sig_mfcr2 comes along */
00083 #define SIG_MFCR2_MAX_CHANNELS   672      /*!< No more than a DS3 per trunk group */
00084 #include <openr2.h>
00085 #endif
00086 
00087 #include "asterisk/lock.h"
00088 #include "asterisk/channel.h"
00089 #include "asterisk/config.h"
00090 #include "asterisk/module.h"
00091 #include "asterisk/pbx.h"
00092 #include "asterisk/file.h"
00093 #include "asterisk/ulaw.h"
00094 #include "asterisk/alaw.h"
00095 #include "asterisk/callerid.h"
00096 #include "asterisk/adsi.h"
00097 #include "asterisk/cli.h"
00098 #include "asterisk/cdr.h"
00099 #include "asterisk/cel.h"
00100 #include "asterisk/features.h"
00101 #include "asterisk/musiconhold.h"
00102 #include "asterisk/say.h"
00103 #include "asterisk/tdd.h"
00104 #include "asterisk/app.h"
00105 #include "asterisk/dsp.h"
00106 #include "asterisk/astdb.h"
00107 #include "asterisk/manager.h"
00108 #include "asterisk/causes.h"
00109 #include "asterisk/term.h"
00110 #include "asterisk/utils.h"
00111 #include "asterisk/transcap.h"
00112 #include "asterisk/stringfields.h"
00113 #include "asterisk/abstract_jb.h"
00114 #include "asterisk/smdi.h"
00115 #include "asterisk/astobj.h"
00116 #include "asterisk/event.h"
00117 #include "asterisk/devicestate.h"
00118 #include "asterisk/paths.h"
00119 #include "asterisk/ccss.h"
00120 #include "asterisk/data.h"
00121 
00122 /*** DOCUMENTATION
00123    <application name="DAHDISendKeypadFacility" language="en_US">
00124       <synopsis>
00125          Send digits out of band over a PRI.
00126       </synopsis>
00127       <syntax>
00128          <parameter name="digits" required="true" />
00129       </syntax>
00130       <description>
00131          <para>This application will send the given string of digits in a Keypad
00132          Facility IE over the current channel.</para>
00133       </description>
00134    </application>
00135    <application name="DAHDISendCallreroutingFacility" language="en_US">
00136       <synopsis>
00137          Send QSIG call rerouting facility over a PRI.
00138       </synopsis>
00139       <syntax argsep=",">
00140          <parameter name="destination" required="true">
00141             <para>Destination number.</para>
00142          </parameter>
00143          <parameter name="original">
00144             <para>Original called number.</para>
00145          </parameter>
00146          <parameter name="reason">
00147             <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
00148          </parameter>
00149       </syntax>
00150       <description>
00151          <para>This application will send a Callrerouting Facility IE over the
00152          current channel.</para>
00153       </description>
00154    </application>
00155    <application name="DAHDIAcceptR2Call" language="en_US">
00156       <synopsis>
00157          Accept an R2 call if its not already accepted (you still need to answer it)
00158       </synopsis>
00159       <syntax>
00160          <parameter name="charge" required="true">
00161             <para>Yes or No.</para>
00162             <para>Whether you want to accept the call with charge or without charge.</para>
00163          </parameter>
00164       </syntax>
00165       <description>
00166          <para>This application will Accept the R2 call either with charge or no charge.</para>
00167       </description>
00168    </application>
00169    <manager name="DAHDITransfer" language="en_US">
00170       <synopsis>
00171          Transfer DAHDI Channel.
00172       </synopsis>
00173       <syntax>
00174          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00175          <parameter name="DAHDIChannel" required="true">
00176             <para>DAHDI channel name to transfer.</para>
00177          </parameter>
00178       </syntax>
00179       <description>
00180          <para>Transfer a DAHDI channel.</para>
00181       </description>
00182    </manager>
00183    <manager name="DAHDIHangup" language="en_US">
00184       <synopsis>
00185          Hangup DAHDI Channel.
00186       </synopsis>
00187       <syntax>
00188          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00189          <parameter name="DAHDIChannel" required="true">
00190             <para>DAHDI channel name to hangup.</para>
00191          </parameter>
00192       </syntax>
00193       <description>
00194          <para>Hangup a DAHDI channel.</para>
00195       </description>
00196    </manager>
00197    <manager name="DAHDIDialOffhook" language="en_US">
00198       <synopsis>
00199          Dial over DAHDI channel while offhook.
00200       </synopsis>
00201       <syntax>
00202          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00203          <parameter name="DAHDIChannel" required="true" />
00204          <parameter name="Number" required="true" />
00205       </syntax>
00206       <description>
00207       </description>
00208    </manager>
00209    <manager name="DAHDIDNDon" language="en_US">
00210       <synopsis>
00211          Toggle DAHDI channel Do Not Disturb status ON.
00212       </synopsis>
00213       <syntax>
00214          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00215          <parameter name="DAHDIChannel" required="true" />
00216       </syntax>
00217       <description>
00218       </description>
00219    </manager>
00220    <manager name="DAHDIDNDoff" language="en_US">
00221       <synopsis>
00222          Toggle DAHDI channel Do Not Disturb status OFF.
00223       </synopsis>
00224       <syntax>
00225          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00226          <parameter name="DAHDIChannel" required="true" />
00227       </syntax>
00228       <description>
00229       </description>
00230    </manager>
00231    <manager name="DAHDIShowChannels" language="en_US">
00232       <synopsis>
00233          Show status DAHDI channels.
00234       </synopsis>
00235       <syntax>
00236          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00237          <parameter name="DAHDIChannel" required="true" />
00238       </syntax>
00239       <description>
00240       </description>
00241    </manager>
00242    <manager name="DAHDIRestart" language="en_US">
00243       <synopsis>
00244          Fully Restart DAHDI channels (terminates calls).
00245       </synopsis>
00246       <syntax>
00247          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00248       </syntax>
00249       <description>
00250       </description>
00251    </manager>
00252  ***/
00253 
00254 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
00255 
00256 static const char * const lbostr[] = {
00257 "0 db (CSU)/0-133 feet (DSX-1)",
00258 "133-266 feet (DSX-1)",
00259 "266-399 feet (DSX-1)",
00260 "399-533 feet (DSX-1)",
00261 "533-655 feet (DSX-1)",
00262 "-7.5db (CSU)",
00263 "-15db (CSU)",
00264 "-22.5db (CSU)"
00265 };
00266 
00267 /*! Global jitterbuffer configuration - by default, jb is disabled */
00268 static struct ast_jb_conf default_jbconf =
00269 {
00270    .flags = 0,
00271    .max_size = -1,
00272    .resync_threshold = -1,
00273    .impl = "",
00274    .target_extra = -1,
00275 };
00276 static struct ast_jb_conf global_jbconf;
00277 
00278 /*!
00279  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
00280  * the user hangs up to reset the state machine so ring works properly.
00281  * This is used to be able to support kewlstart by putting the zhone in
00282  * groundstart mode since their forward disconnect supervision is entirely
00283  * broken even though their documentation says it isn't and their support
00284  * is entirely unwilling to provide any assistance with their channel banks
00285  * even though their web site says they support their products for life.
00286  */
00287 /* #define ZHONE_HACK */
00288 
00289 /*! \brief Typically, how many rings before we should send Caller*ID */
00290 #define DEFAULT_CIDRINGS 1
00291 
00292 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
00293 
00294 
00295 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
00296 #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))
00297 
00298 static const char tdesc[] = "DAHDI Telephony Driver"
00299 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
00300    " w/"
00301    #if defined(HAVE_PRI)
00302       "PRI"
00303    #endif   /* defined(HAVE_PRI) */
00304    #if defined(HAVE_SS7)
00305       #if defined(HAVE_PRI)
00306       " & "
00307       #endif   /* defined(HAVE_PRI) */
00308       "SS7"
00309    #endif   /* defined(HAVE_SS7) */
00310    #if defined(HAVE_OPENR2)
00311       #if defined(HAVE_PRI) || defined(HAVE_SS7)
00312       " & "
00313       #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
00314       "MFC/R2"
00315    #endif   /* defined(HAVE_OPENR2) */
00316 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2) */
00317 ;
00318 
00319 static const char config[] = "chan_dahdi.conf";
00320 
00321 #define SIG_EM    DAHDI_SIG_EM
00322 #define SIG_EMWINK   (0x0100000 | DAHDI_SIG_EM)
00323 #define SIG_FEATD (0x0200000 | DAHDI_SIG_EM)
00324 #define  SIG_FEATDMF (0x0400000 | DAHDI_SIG_EM)
00325 #define  SIG_FEATB   (0x0800000 | DAHDI_SIG_EM)
00326 #define  SIG_E911 (0x1000000 | DAHDI_SIG_EM)
00327 #define  SIG_FEATDMF_TA (0x2000000 | DAHDI_SIG_EM)
00328 #define  SIG_FGC_CAMA   (0x4000000 | DAHDI_SIG_EM)
00329 #define  SIG_FGC_CAMAMF (0x8000000 | DAHDI_SIG_EM)
00330 #define SIG_FXSLS DAHDI_SIG_FXSLS
00331 #define SIG_FXSGS DAHDI_SIG_FXSGS
00332 #define SIG_FXSKS DAHDI_SIG_FXSKS
00333 #define SIG_FXOLS DAHDI_SIG_FXOLS
00334 #define SIG_FXOGS DAHDI_SIG_FXOGS
00335 #define SIG_FXOKS DAHDI_SIG_FXOKS
00336 #define SIG_PRI      DAHDI_SIG_CLEAR
00337 #define SIG_BRI      (0x2000000 | DAHDI_SIG_CLEAR)
00338 #define SIG_BRI_PTMP (0X4000000 | DAHDI_SIG_CLEAR)
00339 #define SIG_SS7      (0x1000000 | DAHDI_SIG_CLEAR)
00340 #define SIG_MFCR2    DAHDI_SIG_CAS
00341 #define  SIG_SF      DAHDI_SIG_SF
00342 #define SIG_SFWINK   (0x0100000 | DAHDI_SIG_SF)
00343 #define SIG_SF_FEATD (0x0200000 | DAHDI_SIG_SF)
00344 #define  SIG_SF_FEATDMF (0x0400000 | DAHDI_SIG_SF)
00345 #define  SIG_SF_FEATB   (0x0800000 | DAHDI_SIG_SF)
00346 #define SIG_EM_E1 DAHDI_SIG_EM_E1
00347 
00348 #ifdef LOTS_OF_SPANS
00349 #define NUM_SPANS DAHDI_MAX_SPANS
00350 #else
00351 #define NUM_SPANS       32
00352 #endif
00353 
00354 #define CHAN_PSEUDO  -2
00355 
00356 #define CALLPROGRESS_PROGRESS    1
00357 #define CALLPROGRESS_FAX_OUTGOING   2
00358 #define CALLPROGRESS_FAX_INCOMING   4
00359 #define CALLPROGRESS_FAX      (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
00360 
00361 #define NUM_CADENCE_MAX 25
00362 static int num_cadence = 4;
00363 static int user_has_defined_cadences = 0;
00364 
00365 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
00366    { { 125, 125, 2000, 4000 } },       /*!< Quick chirp followed by normal ring */
00367    { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
00368    { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
00369    { { 1000, 500, 2500, 5000 } },   /*!< Long ring */
00370 };
00371 
00372 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
00373  * is 1, the second pause is 2 and so on.
00374  */
00375 
00376 static int cidrings[NUM_CADENCE_MAX] = {
00377    2,                            /*!< Right after first long ring */
00378    4,                            /*!< Right after long part */
00379    3,                            /*!< After third chirp */
00380    2,                            /*!< Second spell */
00381 };
00382 
00383 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
00384 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
00385 
00386 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
00387          (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
00388 
00389 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
00390 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
00391 
00392 static char defaultcic[64] = "";
00393 static char defaultozz[64] = "";
00394 
00395 static char parkinglot[AST_MAX_EXTENSION] = "";    /*!< Default parking lot for this channel */
00396 
00397 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
00398 static char mwimonitornotify[PATH_MAX] = "";
00399 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
00400 static int  mwisend_rpas = 0;
00401 #endif
00402 
00403 static char progzone[10] = "";
00404 
00405 static int usedistinctiveringdetection = 0;
00406 static int distinctiveringaftercid = 0;
00407 
00408 static int numbufs = 4;
00409 
00410 static int mwilevel = 512;
00411 static int dtmfcid_level = 256;
00412 
00413 #define REPORT_CHANNEL_ALARMS 1
00414 #define REPORT_SPAN_ALARMS    2 
00415 static int report_alarms = REPORT_CHANNEL_ALARMS;
00416 
00417 #ifdef HAVE_PRI
00418 static int pridebugfd = -1;
00419 static char pridebugfilename[1024] = "";
00420 #endif
00421 
00422 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
00423 static int firstdigittimeout = 16000;
00424 
00425 /*! \brief How long to wait for following digits (FXO logic) */
00426 static int gendigittimeout = 8000;
00427 
00428 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
00429 static int matchdigittimeout = 3000;
00430 
00431 /*! \brief Protect the interface list (of dahdi_pvt's) */
00432 AST_MUTEX_DEFINE_STATIC(iflock);
00433 
00434 
00435 static int ifcount = 0;
00436 
00437 #ifdef HAVE_PRI
00438 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
00439 #endif
00440 
00441 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00442    when it's doing something critical. */
00443 AST_MUTEX_DEFINE_STATIC(monlock);
00444 
00445 /*! \brief This is the thread for the monitor which checks for input on the channels
00446    which are not currently in use. */
00447 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00448 static ast_cond_t ss_thread_complete;
00449 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
00450 AST_MUTEX_DEFINE_STATIC(restart_lock);
00451 static int ss_thread_count = 0;
00452 static int num_restart_pending = 0;
00453 
00454 static int restart_monitor(void);
00455 
00456 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);
00457 
00458 static int dahdi_sendtext(struct ast_channel *c, const char *text);
00459 
00460 static void mwi_event_cb(const struct ast_event *event, void *userdata)
00461 {
00462    /* This module does not handle MWI in an event-based manner.  However, it
00463     * subscribes to MWI for each mailbox that is configured so that the core
00464     * knows that we care about it.  Then, chan_dahdi will get the MWI from the
00465     * event cache instead of checking the mailbox directly. */
00466 }
00467 
00468 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
00469 static inline int dahdi_get_event(int fd)
00470 {
00471    int j;
00472    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00473       return -1;
00474    return j;
00475 }
00476 
00477 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
00478 static inline int dahdi_wait_event(int fd)
00479 {
00480    int i, j = 0;
00481    i = DAHDI_IOMUX_SIGEVENT;
00482    if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
00483       return -1;
00484    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00485       return -1;
00486    return j;
00487 }
00488 
00489 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
00490 #define READ_SIZE 160
00491 
00492 #define MASK_AVAIL      (1 << 0) /*!< Channel available for PRI use */
00493 #define MASK_INUSE      (1 << 1) /*!< Channel currently in use */
00494 
00495 #define CALLWAITING_SILENT_SAMPLES  ( (300 * 8) / READ_SIZE) /*!< 300 ms */
00496 #define CALLWAITING_REPEAT_SAMPLES  ( (10000 * 8) / READ_SIZE) /*!< 10,000 ms */
00497 #define CIDCW_EXPIRE_SAMPLES     ( (500 * 8) / READ_SIZE) /*!< 500 ms */
00498 #define MIN_MS_SINCE_FLASH       ( (2000) )  /*!< 2000 ms */
00499 #define DEFAULT_RINGT            ( (8000 * 8) / READ_SIZE) /*!< 8,000 ms */
00500 
00501 struct dahdi_pvt;
00502 
00503 /*!
00504  * \brief Configured ring timeout base.
00505  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
00506  */
00507 static int ringt_base = DEFAULT_RINGT;
00508 
00509 #if defined(HAVE_SS7)
00510 
00511 struct dahdi_ss7 {
00512    struct sig_ss7_linkset ss7;
00513 };
00514 
00515 static struct dahdi_ss7 linksets[NUM_SPANS];
00516 
00517 static int cur_ss7type = -1;
00518 static int cur_linkset = -1;
00519 static int cur_pointcode = -1;
00520 static int cur_cicbeginswith = -1;
00521 static int cur_adjpointcode = -1;
00522 static int cur_networkindicator = -1;
00523 static int cur_defaultdpc = -1;
00524 #endif   /* defined(HAVE_SS7) */
00525 
00526 #ifdef HAVE_OPENR2
00527 struct dahdi_mfcr2 {
00528    pthread_t r2master;            /*!< Thread of master */
00529    openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
00530    struct dahdi_pvt *pvts[SIG_MFCR2_MAX_CHANNELS];     /*!< Member channel pvt structs */
00531    int numchans;                          /*!< Number of channels in this R2 block */
00532    int monitored_count;                   /*!< Number of channels being monitored */
00533 };
00534 
00535 struct dahdi_mfcr2_conf {
00536    openr2_variant_t variant;
00537    int mfback_timeout;
00538    int metering_pulse_timeout;
00539    int max_ani;
00540    int max_dnis;
00541    signed int get_ani_first:2;
00542 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
00543    signed int skip_category_request:2;
00544 #endif
00545    unsigned int call_files:1;
00546    unsigned int allow_collect_calls:1;
00547    unsigned int charge_calls:1;
00548    unsigned int accept_on_offer:1;
00549    unsigned int forced_release:1;
00550    unsigned int double_answer:1;
00551    signed int immediate_accept:2;
00552    char logdir[OR2_MAX_PATH];
00553    char r2proto_file[OR2_MAX_PATH];
00554    openr2_log_level_t loglevel;
00555    openr2_calling_party_category_t category;
00556 };
00557 
00558 /* malloc'd array of malloc'd r2links */
00559 static struct dahdi_mfcr2 **r2links;
00560 /* how many r2links have been malloc'd */
00561 static int r2links_count = 0;
00562 
00563 #endif /* HAVE_OPENR2 */
00564 
00565 #ifdef HAVE_PRI
00566 
00567 struct dahdi_pri {
00568    int dchannels[SIG_PRI_NUM_DCHANS];     /*!< What channel are the dchannels on */
00569    int mastertrunkgroup;               /*!< What trunk group is our master */
00570    int prilogicalspan;                 /*!< Logical span number within trunk group */
00571    struct sig_pri_span pri;
00572 };
00573 
00574 static struct dahdi_pri pris[NUM_SPANS];
00575 
00576 #if defined(HAVE_PRI_CCSS)
00577 /*! DAHDI PRI CCSS agent and monitor type name. */
00578 static const char dahdi_pri_cc_type[] = "DAHDI/PRI";
00579 #endif   /* defined(HAVE_PRI_CCSS) */
00580 
00581 #else
00582 /*! Shut up the compiler */
00583 struct dahdi_pri;
00584 #endif
00585 
00586 #define SUB_REAL  0        /*!< Active call */
00587 #define SUB_CALLWAIT 1        /*!< Call-Waiting call on hold */
00588 #define SUB_THREEWAY 2        /*!< Three-way call */
00589 
00590 /* Polarity states */
00591 #define POLARITY_IDLE   0
00592 #define POLARITY_REV    1
00593 
00594 
00595 struct distRingData {
00596    int ring[3];
00597    int range;
00598 };
00599 struct ringContextData {
00600    char contextData[AST_MAX_CONTEXT];
00601 };
00602 struct dahdi_distRings {
00603    struct distRingData ringnum[3];
00604    struct ringContextData ringContext[3];
00605 };
00606 
00607 static const char * const subnames[] = {
00608    "Real",
00609    "Callwait",
00610    "Threeway"
00611 };
00612 
00613 struct dahdi_subchannel {
00614    int dfd;
00615    struct ast_channel *owner;
00616    int chan;
00617    short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
00618    struct ast_frame f;     /*!< One frame for each channel.  How did this ever work before? */
00619    unsigned int needringing:1;
00620    unsigned int needbusy:1;
00621    unsigned int needcongestion:1;
00622    unsigned int needanswer:1;
00623    unsigned int needflash:1;
00624    unsigned int needhold:1;
00625    unsigned int needunhold:1;
00626    unsigned int linear:1;
00627    unsigned int inthreeway:1;
00628    struct dahdi_confinfo curconf;
00629 };
00630 
00631 #define CONF_USER_REAL     (1 << 0)
00632 #define CONF_USER_THIRDCALL   (1 << 1)
00633 
00634 #define MAX_SLAVES   4
00635 
00636 /* States for sending MWI message
00637  * First three states are required for send Ring Pulse Alert Signal
00638  */
00639 typedef enum {
00640    MWI_SEND_NULL = 0,
00641    MWI_SEND_SA,
00642    MWI_SEND_SA_WAIT,
00643    MWI_SEND_PAUSE,
00644    MWI_SEND_SPILL,
00645    MWI_SEND_CLEANUP,
00646    MWI_SEND_DONE,
00647 } mwisend_states;
00648 
00649 struct mwisend_info {
00650    struct   timeval  pause;
00651    mwisend_states    mwisend_current;
00652 };
00653 
00654 /*! Specify the lists dahdi_pvt can be put in. */
00655 enum DAHDI_IFLIST {
00656    DAHDI_IFLIST_NONE,   /*!< The dahdi_pvt is not in any list. */
00657    DAHDI_IFLIST_MAIN,   /*!< The dahdi_pvt is in the main interface list */
00658 #if defined(HAVE_PRI)
00659    DAHDI_IFLIST_NO_B_CHAN, /*!< The dahdi_pvt is in a no B channel interface list */
00660 #endif   /* defined(HAVE_PRI) */
00661 };
00662 
00663 struct dahdi_pvt {
00664    ast_mutex_t lock;             /*!< Channel private lock. */
00665    struct callerid_state *cs;
00666    struct ast_channel *owner;       /*!< Our current active owner (if applicable) */
00667                      /*!< Up to three channels can be associated with this call */
00668 
00669    struct dahdi_subchannel sub_unused;    /*!< Just a safety precaution */
00670    struct dahdi_subchannel subs[3];       /*!< Sub-channels */
00671    struct dahdi_confinfo saveconf;        /*!< Saved conference info */
00672 
00673    struct dahdi_pvt *slaves[MAX_SLAVES];     /*!< Slave to us (follows our conferencing) */
00674    struct dahdi_pvt *master;           /*!< Master to us (we follow their conferencing) */
00675    int inconference;          /*!< If our real should be in the conference */
00676 
00677    int bufsize;                /*!< Size of the buffers */
00678    int buf_no;             /*!< Number of buffers */
00679    int buf_policy;            /*!< Buffer policy */
00680    int faxbuf_no;              /*!< Number of Fax buffers */
00681    int faxbuf_policy;          /*!< Fax buffer policy */
00682    int sig;             /*!< Signalling style */
00683    /*!
00684     * \brief Nonzero if the signaling type is sent over a radio.
00685     * \note Set to a couple of nonzero values but it is only tested like a boolean.
00686     */
00687    int radio;
00688    int outsigmod;             /*!< Outbound Signalling style (modifier) */
00689    int oprmode;               /*!< "Operator Services" mode */
00690    struct dahdi_pvt *oprpeer;          /*!< "Operator Services" peer tech_pvt ptr */
00691    /*! \brief Amount of gain to increase during caller id */
00692    float cid_rxgain;
00693    /*! \brief Rx gain set by chan_dahdi.conf */
00694    float rxgain;
00695    /*! \brief Tx gain set by chan_dahdi.conf */
00696    float txgain;
00697 
00698    float txdrc; /*!< Dynamic Range Compression factor. a number between 1 and 6ish */
00699    float rxdrc;
00700    
00701    int tonezone;              /*!< tone zone for this chan, or -1 for default */
00702    enum DAHDI_IFLIST which_iflist;  /*!< Which interface list is this structure listed? */
00703    struct dahdi_pvt *next;          /*!< Next channel in list */
00704    struct dahdi_pvt *prev;          /*!< Prev channel in list */
00705 
00706    /* flags */
00707 
00708    /*!
00709     * \brief TRUE if ADSI (Analog Display Services Interface) available
00710     * \note Set from the "adsi" value read in from chan_dahdi.conf
00711     */
00712    unsigned int adsi:1;
00713    /*!
00714     * \brief TRUE if we can use a polarity reversal to mark when an outgoing
00715     * call is answered by the remote party.
00716     * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
00717     */
00718    unsigned int answeronpolarityswitch:1;
00719    /*!
00720     * \brief TRUE if busy detection is enabled.
00721     * (Listens for the beep-beep busy pattern.)
00722     * \note Set from the "busydetect" value read in from chan_dahdi.conf
00723     */
00724    unsigned int busydetect:1;
00725    /*!
00726     * \brief TRUE if call return is enabled.
00727     * (*69, if your dialplan doesn't catch this first)
00728     * \note Set from the "callreturn" value read in from chan_dahdi.conf
00729     */
00730    unsigned int callreturn:1;
00731    /*!
00732     * \brief TRUE if busy extensions will hear the call-waiting tone
00733     * and can use hook-flash to switch between callers.
00734     * \note Can be disabled by dialing *70.
00735     * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
00736     */
00737    unsigned int callwaiting:1;
00738    /*!
00739     * \brief TRUE if send caller ID for Call Waiting
00740     * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
00741     */
00742    unsigned int callwaitingcallerid:1;
00743    /*!
00744     * \brief TRUE if support for call forwarding enabled.
00745     * Dial *72 to enable call forwarding.
00746     * Dial *73 to disable call forwarding.
00747     * \note Set from the "cancallforward" value read in from chan_dahdi.conf
00748     */
00749    unsigned int cancallforward:1;
00750    /*!
00751     * \brief TRUE if support for call parking is enabled.
00752     * \note Set from the "canpark" value read in from chan_dahdi.conf
00753     */
00754    unsigned int canpark:1;
00755    /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
00756    unsigned int confirmanswer:1;
00757    /*!
00758     * \brief TRUE if the channel is to be destroyed on hangup.
00759     * (Used by pseudo channels.)
00760     */
00761    unsigned int destroy:1;
00762    unsigned int didtdd:1;           /*!< flag to say its done it once */
00763    /*! \brief TRUE if analog type line dialed no digits in Dial() */
00764    unsigned int dialednone:1;
00765    /*!
00766     * \brief TRUE if in the process of dialing digits or sending something.
00767     * \note This is used as a receive squelch for ISDN until connected.
00768     */
00769    unsigned int dialing:1;
00770    /*! \brief TRUE if the transfer capability of the call is digital. */
00771    unsigned int digital:1;
00772    /*! \brief TRUE if Do-Not-Disturb is enabled, present only for non sig_analog */
00773    unsigned int dnd:1;
00774    /*! \brief XXX BOOLEAN Purpose??? */
00775    unsigned int echobreak:1;
00776    /*!
00777     * \brief TRUE if echo cancellation enabled when bridged.
00778     * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
00779     * \note Disabled if the echo canceller is not setup.
00780     */
00781    unsigned int echocanbridged:1;
00782    /*! \brief TRUE if echo cancellation is turned on. */
00783    unsigned int echocanon:1;
00784    /*! \brief TRUE if a fax tone has already been handled. */
00785    unsigned int faxhandled:1;
00786    /*! TRUE if dynamic faxbuffers are configured for use, default is OFF */
00787    unsigned int usefaxbuffers:1;
00788    /*! TRUE while buffer configuration override is in use */
00789    unsigned int bufferoverrideinuse:1;
00790    /*! \brief TRUE if over a radio and dahdi_read() has been called. */
00791    unsigned int firstradio:1;
00792    /*!
00793     * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
00794     * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
00795     */
00796    unsigned int hanguponpolarityswitch:1;
00797    /*! \brief TRUE if DTMF detection needs to be done by hardware. */
00798    unsigned int hardwaredtmf:1;
00799    /*!
00800     * \brief TRUE if the outgoing caller ID is blocked/hidden.
00801     * \note Caller ID can be disabled by dialing *67.
00802     * \note Caller ID can be enabled by dialing *82.
00803     * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
00804     */
00805    unsigned int hidecallerid:1;
00806    /*!
00807     * \brief TRUE if hide just the name not the number for legacy PBX use.
00808     * \note Only applies to PRI channels.
00809     * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
00810     */
00811    unsigned int hidecalleridname:1;
00812    /*! \brief TRUE if DTMF detection is disabled. */
00813    unsigned int ignoredtmf:1;
00814    /*!
00815     * \brief TRUE if the channel should be answered immediately
00816     * without attempting to gather any digits.
00817     * \note Set from the "immediate" value read in from chan_dahdi.conf
00818     */
00819    unsigned int immediate:1;
00820    /*! \brief TRUE if in an alarm condition. */
00821    unsigned int inalarm:1;
00822    /*! \brief TRUE if TDD in MATE mode */
00823    unsigned int mate:1;
00824    /*! \brief TRUE if we originated the call leg. */
00825    unsigned int outgoing:1;
00826    /* unsigned int overlapdial:1;         unused and potentially confusing */
00827    /*!
00828     * \brief TRUE if busy extensions will hear the call-waiting tone
00829     * and can use hook-flash to switch between callers.
00830     * \note Set from the "callwaiting" value read in from chan_dahdi.conf
00831     */
00832    unsigned int permcallwaiting:1;
00833    /*!
00834     * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
00835     * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
00836     */
00837    unsigned int permhidecallerid:1;
00838    /*!
00839     * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
00840     * \note Set from the "priindication" value read in from chan_dahdi.conf
00841     */
00842    unsigned int priindication_oob:1;
00843    /*!
00844     * \brief TRUE if PRI B channels are always exclusively selected.
00845     * \note Set from the "priexclusive" value read in from chan_dahdi.conf
00846     */
00847    unsigned int priexclusive:1;
00848    /*!
00849     * \brief TRUE if we will pulse dial.
00850     * \note Set from the "pulsedial" value read in from chan_dahdi.conf
00851     */
00852    unsigned int pulse:1;
00853    /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
00854    unsigned int pulsedial:1;
00855    unsigned int restartpending:1;      /*!< flag to ensure counted only once for restart */
00856    /*!
00857     * \brief TRUE if caller ID is restricted.
00858     * \note Set but not used.  Should be deleted.  Redundant with permhidecallerid.
00859     * \note Set from the "restrictcid" value read in from chan_dahdi.conf
00860     */
00861    unsigned int restrictcid:1;
00862    /*!
00863     * \brief TRUE if three way calling is enabled
00864     * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
00865     */
00866    unsigned int threewaycalling:1;
00867    /*!
00868     * \brief TRUE if call transfer is enabled
00869     * \note For FXS ports (either direct analog or over T1/E1):
00870     *   Support flash-hook call transfer
00871     * \note For digital ports using ISDN PRI protocols:
00872     *   Support switch-side transfer (called 2BCT, RLT or other names)
00873     * \note Set from the "transfer" value read in from chan_dahdi.conf
00874     */
00875    unsigned int transfer:1;
00876    /*!
00877     * \brief TRUE if caller ID is used on this channel.
00878     * \note PRI and SS7 spans will save caller ID from the networking peer.
00879     * \note FXS ports will generate the caller ID spill.
00880     * \note FXO ports will listen for the caller ID spill.
00881     * \note Set from the "usecallerid" value read in from chan_dahdi.conf
00882     */
00883    unsigned int use_callerid:1;
00884    /*!
00885     * \brief TRUE if we will use the calling presentation setting
00886     * from the Asterisk channel for outgoing calls.
00887     * \note Only applies to PRI and SS7 channels.
00888     * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
00889     */
00890    unsigned int use_callingpres:1;
00891    /*!
00892     * \brief TRUE if distinctive rings are to be detected.
00893     * \note For FXO lines
00894     * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
00895     */
00896    unsigned int usedistinctiveringdetection:1;
00897    /*!
00898     * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
00899     * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
00900     */
00901    unsigned int dahditrcallerid:1;
00902    /*!
00903     * \brief TRUE if allowed to flash-transfer to busy channels.
00904     * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
00905     */
00906    unsigned int transfertobusy:1;
00907    /*!
00908     * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
00909     * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
00910     */
00911    unsigned int mwimonitor_neon:1;
00912    /*!
00913     * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
00914     * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
00915     */
00916    unsigned int mwimonitor_fsk:1;
00917    /*!
00918     * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
00919     * \note RPAS - Ring Pulse Alert Signal
00920     * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
00921     */
00922    unsigned int mwimonitor_rpas:1;
00923    /*! \brief TRUE if an MWI monitor thread is currently active */
00924    unsigned int mwimonitoractive:1;
00925    /*! \brief TRUE if a MWI message sending thread is active */
00926    unsigned int mwisendactive:1;
00927    /*!
00928     * \brief TRUE if channel is out of reset and ready
00929     * \note Set but not used.
00930     */
00931    unsigned int inservice:1;
00932    /*!
00933     * \brief TRUE if the channel is locally blocked.
00934     * \note Applies to SS7 and MFCR2 channels.
00935     */
00936    unsigned int locallyblocked:1;
00937    /*!
00938     * \brief TRUE if the channel is remotely blocked.
00939     * \note Applies to SS7 and MFCR2 channels.
00940     */
00941    unsigned int remotelyblocked:1;
00942    /*!
00943     * \brief TRUE if the channel alarms will be managed also as Span ones
00944     * \note Applies to all channels
00945     */
00946    unsigned int manages_span_alarms:1;
00947 
00948 #if defined(HAVE_PRI)
00949    struct sig_pri_span *pri;
00950    int logicalspan;
00951 #endif
00952    /*!
00953     * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
00954     * \note Set from the "usesmdi" value read in from chan_dahdi.conf
00955     */
00956    unsigned int use_smdi:1;
00957    struct mwisend_info mwisend_data;
00958    /*! \brief The serial port to listen for SMDI data on */
00959    struct ast_smdi_interface *smdi_iface;
00960 
00961    /*! \brief Distinctive Ring data */
00962    struct dahdi_distRings drings;
00963 
00964    /*!
00965     * \brief The configured context for incoming calls.
00966     * \note The "context" string read in from chan_dahdi.conf
00967     */
00968    char context[AST_MAX_CONTEXT];
00969    /*!
00970     * \brief Saved context string.
00971     */
00972    char defcontext[AST_MAX_CONTEXT];
00973    /*! \brief Extension to use in the dialplan. */
00974    char exten[AST_MAX_EXTENSION];
00975    /*!
00976     * \brief Language configured for calls.
00977     * \note The "language" string read in from chan_dahdi.conf
00978     */
00979    char language[MAX_LANGUAGE];
00980    /*!
00981     * \brief The configured music-on-hold class to use for calls.
00982     * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
00983     */
00984    char mohinterpret[MAX_MUSICCLASS];
00985    /*!
00986     * \brief Suggested music-on-hold class for peer channel to use for calls.
00987     * \note The "mohsuggest" string read in from chan_dahdi.conf
00988     */
00989    char mohsuggest[MAX_MUSICCLASS];
00990    char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
00991 #if defined(HAVE_PRI) || defined(HAVE_SS7)
00992    /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
00993    char cid_ani[AST_MAX_EXTENSION];
00994 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
00995    /*! \brief Automatic Number Identification code from PRI */
00996    int cid_ani2;
00997    /*! \brief Caller ID number from an incoming call. */
00998    char cid_num[AST_MAX_EXTENSION];
00999    /*!
01000     * \brief Caller ID tag from incoming call
01001     * \note the "cid_tag" string read in from chan_dahdi.conf
01002     */
01003    char cid_tag[AST_MAX_EXTENSION];
01004    /*! \brief Caller ID Q.931 TON/NPI field values.  Set by PRI. Zero otherwise. */
01005    int cid_ton;
01006    /*! \brief Caller ID name from an incoming call. */
01007    char cid_name[AST_MAX_EXTENSION];
01008    /*! \brief Caller ID subaddress from an incoming call. */
01009    char cid_subaddr[AST_MAX_EXTENSION];
01010    char *origcid_num;            /*!< malloced original callerid */
01011    char *origcid_name;           /*!< malloced original callerid */
01012    /*! \brief Call waiting number. */
01013    char callwait_num[AST_MAX_EXTENSION];
01014    /*! \brief Call waiting name. */
01015    char callwait_name[AST_MAX_EXTENSION];
01016    /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
01017    char rdnis[AST_MAX_EXTENSION];
01018    /*! \brief Dialed Number Identifier */
01019    char dnid[AST_MAX_EXTENSION];
01020    /*!
01021     * \brief Bitmapped groups this belongs to.
01022     * \note The "group" bitmapped group string read in from chan_dahdi.conf
01023     */
01024    ast_group_t group;
01025    /*! \brief Default call PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW. */
01026    int law_default;
01027    /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
01028    int law;
01029    int confno;             /*!< Our conference */
01030    int confusers;             /*!< Who is using our conference */
01031    int propconfno;               /*!< Propagated conference number */
01032    /*!
01033     * \brief Bitmapped call groups this belongs to.
01034     * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
01035     */
01036    ast_group_t callgroup;
01037    /*!
01038     * \brief Bitmapped pickup groups this belongs to.
01039     * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
01040     */
01041    ast_group_t pickupgroup;
01042    /*!
01043     * \brief Channel variable list with associated values to set when a channel is created.
01044     * \note The "setvar" strings read in from chan_dahdi.conf
01045     */
01046    struct ast_variable *vars;
01047    int channel;               /*!< Channel Number */
01048    int span;               /*!< Span number */
01049    time_t guardtime;          /*!< Must wait this much time before using for new call */
01050    int cid_signalling;           /*!< CID signalling type bell202 or v23 */
01051    int cid_start;             /*!< CID start indicator, polarity or ring or DTMF without warning event */
01052    int dtmfcid_holdoff_state;    /*!< State indicator that allows for line to settle before checking for dtmf energy */
01053    struct timeval dtmfcid_delay;  /*!< Time value used for allow line to settle */
01054    int callingpres;           /*!< The value of calling presentation that we're going to use when placing a PRI call */
01055    int callwaitingrepeat;           /*!< How many samples to wait before repeating call waiting */
01056    int cidcwexpire;           /*!< When to expire our muting for CID/CW */
01057    /*! \brief Analog caller ID waveform sample buffer */
01058    unsigned char *cidspill;
01059    /*! \brief Position in the cidspill buffer to send out next. */
01060    int cidpos;
01061    /*! \brief Length of the cidspill buffer containing samples. */
01062    int cidlen;
01063    /*! \brief Ring timeout timer?? */
01064    int ringt;
01065    /*!
01066     * \brief Ring timeout base.
01067     * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
01068     */
01069    int ringt_base;
01070    /*!
01071     * \brief Number of most significant digits/characters to strip from the dialed number.
01072     * \note Feature is deprecated.  Use dialplan logic.
01073     * \note The characters are stripped before the PRI TON/NPI prefix
01074     * characters are processed.
01075     */
01076    int stripmsd;
01077    /*! \brief BOOLEAN. XXX Meaning what?? */
01078    int callwaitcas;
01079    /*! \brief Number of call waiting rings. */
01080    int callwaitrings;
01081    /*! \brief Echo cancel parameters. */
01082    struct {
01083       struct dahdi_echocanparams head;
01084       struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
01085    } echocancel;
01086    /*!
01087     * \brief Echo training time. 0 = disabled
01088     * \note Set from the "echotraining" value read in from chan_dahdi.conf
01089     */
01090    int echotraining;
01091    /*! \brief Filled with 'w'.  XXX Purpose?? */
01092    char echorest[20];
01093    /*!
01094     * \brief Number of times to see "busy" tone before hanging up.
01095     * \note Set from the "busycount" value read in from chan_dahdi.conf
01096     */
01097    int busycount;
01098    /*!
01099     * \brief Length of "busy" tone on time.
01100     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01101     */
01102    int busy_tonelength;
01103    /*!
01104     * \brief Length of "busy" tone off time.
01105     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01106     */
01107    int busy_quietlength;
01108    /*!
01109     * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
01110     * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
01111     */
01112    int callprogress;
01113    /*!
01114     * \brief Number of milliseconds to wait for dialtone.
01115     * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
01116     */
01117    int waitfordialtone;
01118    struct timeval waitingfordt;        /*!< Time we started waiting for dialtone */
01119    struct timeval flashtime;        /*!< Last flash-hook time */
01120    /*! \brief Opaque DSP configuration structure. */
01121    struct ast_dsp *dsp;
01122    /*! \brief DAHDI dial operation command struct for ioctl() call. */
01123    struct dahdi_dialoperation dop;
01124    int whichwink;             /*!< SIG_FEATDMF_TA Which wink are we on? */
01125    /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
01126    char finaldial[64];
01127    char accountcode[AST_MAX_ACCOUNT_CODE];      /*!< Account code */
01128    int amaflags;              /*!< AMA Flags */
01129    struct tdd_state *tdd;           /*!< TDD flag */
01130    /*! \brief Accumulated call forwarding number. */
01131    char call_forward[AST_MAX_EXTENSION];
01132    /*!
01133     * \brief Voice mailbox location.
01134     * \note Set from the "mailbox" string read in from chan_dahdi.conf
01135     */
01136    char mailbox[AST_MAX_EXTENSION];
01137    /*! \brief Opaque event subscription parameters for message waiting indication support. */
01138    struct ast_event_sub *mwi_event_sub;
01139    /*! \brief Delayed dialing for E911.  Overlap digits for ISDN. */
01140    char dialdest[256];
01141 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01142    struct dahdi_vmwi_info mwisend_setting;            /*!< Which VMWI methods to use */
01143    unsigned int mwisend_fsk: 1;     /*! Variable for enabling FSK MWI handling in chan_dahdi */
01144    unsigned int mwisend_rpas:1;     /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
01145 #endif
01146    int distinctivering;          /*!< Which distinctivering to use */
01147    int dtmfrelax;             /*!< whether to run in relaxed DTMF mode */
01148    /*! \brief Holding place for event injected from outside normal operation. */
01149    int fake_event;
01150    /*!
01151     * \brief Minimal time period (ms) between the answer polarity
01152     * switch and hangup polarity switch.
01153     */
01154    int polarityonanswerdelay;
01155    /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
01156    struct timeval polaritydelaytv;
01157    /*!
01158     * \brief Send caller ID on FXS after this many rings. Set to 1 for US.
01159     * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
01160     */
01161    int sendcalleridafter;
01162    /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
01163    int polarity;
01164    /*! \brief DSP feature flags: DSP_FEATURE_xxx */
01165    int dsp_features;
01166 #if defined(HAVE_SS7)
01167    /*! \brief SS7 control parameters */
01168    struct sig_ss7_linkset *ss7;
01169 #endif   /* defined(HAVE_SS7) */
01170 #ifdef HAVE_OPENR2
01171    struct dahdi_mfcr2 *mfcr2;
01172    openr2_chan_t *r2chan;
01173    openr2_calling_party_category_t mfcr2_recvd_category;
01174    openr2_calling_party_category_t mfcr2_category;
01175    int mfcr2_dnis_index;
01176    int mfcr2_ani_index;
01177    int mfcr2call:1;
01178    int mfcr2_answer_pending:1;
01179    int mfcr2_charge_calls:1;
01180    int mfcr2_allow_collect_calls:1;
01181    int mfcr2_forced_release:1;
01182    int mfcr2_dnis_matched:1;
01183    int mfcr2_call_accepted:1;
01184    int mfcr2_accept_on_offer:1;
01185 #endif
01186    /*! \brief DTMF digit in progress.  0 when no digit in progress. */
01187    char begindigit;
01188    /*! \brief TRUE if confrence is muted. */
01189    int muting;
01190    void *sig_pvt;
01191    struct ast_cc_config_params *cc_params;
01192    /* DAHDI channel names may differ greatly from the
01193     * string that was provided to an app such as Dial. We
01194     * need to save the original string passed to dahdi_request
01195     * for call completion purposes. This way, we can replicate
01196     * the original dialed string later.
01197     */
01198    char dialstring[AST_CHANNEL_NAME];
01199 };
01200 
01201 #define DATA_EXPORT_DAHDI_PVT(MEMBER)              \
01202    MEMBER(dahdi_pvt, cid_rxgain, AST_DATA_DOUBLE)        \
01203    MEMBER(dahdi_pvt, rxgain, AST_DATA_DOUBLE)         \
01204    MEMBER(dahdi_pvt, txgain, AST_DATA_DOUBLE)         \
01205    MEMBER(dahdi_pvt, txdrc, AST_DATA_DOUBLE)       \
01206    MEMBER(dahdi_pvt, rxdrc, AST_DATA_DOUBLE)       \
01207    MEMBER(dahdi_pvt, adsi, AST_DATA_BOOLEAN)       \
01208    MEMBER(dahdi_pvt, answeronpolarityswitch, AST_DATA_BOOLEAN) \
01209    MEMBER(dahdi_pvt, busydetect, AST_DATA_BOOLEAN)       \
01210    MEMBER(dahdi_pvt, callreturn, AST_DATA_BOOLEAN)       \
01211    MEMBER(dahdi_pvt, callwaiting, AST_DATA_BOOLEAN)      \
01212    MEMBER(dahdi_pvt, callwaitingcallerid, AST_DATA_BOOLEAN) \
01213    MEMBER(dahdi_pvt, cancallforward, AST_DATA_BOOLEAN)      \
01214    MEMBER(dahdi_pvt, canpark, AST_DATA_BOOLEAN)       \
01215    MEMBER(dahdi_pvt, confirmanswer, AST_DATA_BOOLEAN)    \
01216    MEMBER(dahdi_pvt, destroy, AST_DATA_BOOLEAN)       \
01217    MEMBER(dahdi_pvt, didtdd, AST_DATA_BOOLEAN)        \
01218    MEMBER(dahdi_pvt, dialednone, AST_DATA_BOOLEAN)       \
01219    MEMBER(dahdi_pvt, dialing, AST_DATA_BOOLEAN)       \
01220    MEMBER(dahdi_pvt, digital, AST_DATA_BOOLEAN)       \
01221    MEMBER(dahdi_pvt, dnd, AST_DATA_BOOLEAN)        \
01222    MEMBER(dahdi_pvt, echobreak, AST_DATA_BOOLEAN)        \
01223    MEMBER(dahdi_pvt, echocanbridged, AST_DATA_BOOLEAN)      \
01224    MEMBER(dahdi_pvt, echocanon, AST_DATA_BOOLEAN)        \
01225    MEMBER(dahdi_pvt, faxhandled, AST_DATA_BOOLEAN)       \
01226    MEMBER(dahdi_pvt, usefaxbuffers, AST_DATA_BOOLEAN)    \
01227    MEMBER(dahdi_pvt, bufferoverrideinuse, AST_DATA_BOOLEAN) \
01228    MEMBER(dahdi_pvt, firstradio, AST_DATA_BOOLEAN)       \
01229    MEMBER(dahdi_pvt, hanguponpolarityswitch, AST_DATA_BOOLEAN) \
01230    MEMBER(dahdi_pvt, hardwaredtmf, AST_DATA_BOOLEAN)     \
01231    MEMBER(dahdi_pvt, hidecallerid, AST_DATA_BOOLEAN)     \
01232    MEMBER(dahdi_pvt, hidecalleridname, AST_DATA_BOOLEAN)    \
01233    MEMBER(dahdi_pvt, ignoredtmf, AST_DATA_BOOLEAN)       \
01234    MEMBER(dahdi_pvt, immediate, AST_DATA_BOOLEAN)        \
01235    MEMBER(dahdi_pvt, inalarm, AST_DATA_BOOLEAN)       \
01236    MEMBER(dahdi_pvt, mate, AST_DATA_BOOLEAN)       \
01237    MEMBER(dahdi_pvt, outgoing, AST_DATA_BOOLEAN)         \
01238    MEMBER(dahdi_pvt, permcallwaiting, AST_DATA_BOOLEAN)     \
01239    MEMBER(dahdi_pvt, priindication_oob, AST_DATA_BOOLEAN)      \
01240    MEMBER(dahdi_pvt, priexclusive, AST_DATA_BOOLEAN)     \
01241    MEMBER(dahdi_pvt, pulse, AST_DATA_BOOLEAN)         \
01242    MEMBER(dahdi_pvt, pulsedial, AST_DATA_BOOLEAN)        \
01243    MEMBER(dahdi_pvt, restartpending, AST_DATA_BOOLEAN)      \
01244    MEMBER(dahdi_pvt, restrictcid, AST_DATA_BOOLEAN)      \
01245    MEMBER(dahdi_pvt, threewaycalling, AST_DATA_BOOLEAN)     \
01246    MEMBER(dahdi_pvt, transfer, AST_DATA_BOOLEAN)         \
01247    MEMBER(dahdi_pvt, use_callerid, AST_DATA_BOOLEAN)     \
01248    MEMBER(dahdi_pvt, use_callingpres, AST_DATA_BOOLEAN)     \
01249    MEMBER(dahdi_pvt, usedistinctiveringdetection, AST_DATA_BOOLEAN)  \
01250    MEMBER(dahdi_pvt, dahditrcallerid, AST_DATA_BOOLEAN)        \
01251    MEMBER(dahdi_pvt, transfertobusy, AST_DATA_BOOLEAN)         \
01252    MEMBER(dahdi_pvt, mwimonitor_neon, AST_DATA_BOOLEAN)        \
01253    MEMBER(dahdi_pvt, mwimonitor_fsk, AST_DATA_BOOLEAN)         \
01254    MEMBER(dahdi_pvt, mwimonitor_rpas, AST_DATA_BOOLEAN)        \
01255    MEMBER(dahdi_pvt, mwimonitoractive, AST_DATA_BOOLEAN)       \
01256    MEMBER(dahdi_pvt, mwisendactive, AST_DATA_BOOLEAN)       \
01257    MEMBER(dahdi_pvt, inservice, AST_DATA_BOOLEAN)           \
01258    MEMBER(dahdi_pvt, locallyblocked, AST_DATA_BOOLEAN)         \
01259    MEMBER(dahdi_pvt, remotelyblocked, AST_DATA_BOOLEAN)        \
01260    MEMBER(dahdi_pvt, manages_span_alarms, AST_DATA_BOOLEAN)    \
01261    MEMBER(dahdi_pvt, use_smdi, AST_DATA_BOOLEAN)            \
01262    MEMBER(dahdi_pvt, context, AST_DATA_STRING)           \
01263    MEMBER(dahdi_pvt, defcontext, AST_DATA_STRING)           \
01264    MEMBER(dahdi_pvt, exten, AST_DATA_STRING)          \
01265    MEMBER(dahdi_pvt, language, AST_DATA_STRING)          \
01266    MEMBER(dahdi_pvt, mohinterpret, AST_DATA_STRING)         \
01267    MEMBER(dahdi_pvt, mohsuggest, AST_DATA_STRING)           \
01268    MEMBER(dahdi_pvt, parkinglot, AST_DATA_STRING)
01269 
01270 AST_DATA_STRUCTURE(dahdi_pvt, DATA_EXPORT_DAHDI_PVT);
01271 
01272 static struct dahdi_pvt *iflist = NULL;   /*!< Main interface list start */
01273 static struct dahdi_pvt *ifend = NULL; /*!< Main interface list end */
01274 
01275 #if defined(HAVE_PRI)
01276 static struct dahdi_parms_pseudo {
01277    int buf_no;             /*!< Number of buffers */
01278    int buf_policy;            /*!< Buffer policy */
01279    int faxbuf_no;              /*!< Number of Fax buffers */
01280    int faxbuf_policy;          /*!< Fax buffer policy */
01281 } dahdi_pseudo_parms;
01282 #endif   /* defined(HAVE_PRI) */
01283 
01284 /*! \brief Channel configuration from chan_dahdi.conf .
01285  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
01286  * Generally there is a field here for every possible configuration item.
01287  *
01288  * The state of fields is saved along the parsing and whenever a 'channel'
01289  * statement is reached, the current dahdi_chan_conf is used to configure the
01290  * channel (struct dahdi_pvt)
01291  *
01292  * \see dahdi_chan_init for the default values.
01293  */
01294 struct dahdi_chan_conf {
01295    struct dahdi_pvt chan;
01296 #ifdef HAVE_PRI
01297    struct dahdi_pri pri;
01298 #endif
01299 
01300 #if defined(HAVE_SS7)
01301    struct dahdi_ss7 ss7;
01302 #endif   /* defined(HAVE_SS7) */
01303 
01304 #ifdef HAVE_OPENR2
01305    struct dahdi_mfcr2_conf mfcr2;
01306 #endif
01307    struct dahdi_params timing;
01308    int is_sig_auto; /*!< Use channel signalling from DAHDI? */
01309    /*! Continue configuration even if a channel is not there. */
01310    int ignore_failed_channels;
01311 
01312    /*!
01313     * \brief The serial port to listen for SMDI data on
01314     * \note Set from the "smdiport" string read in from chan_dahdi.conf
01315     */
01316    char smdi_port[SMDI_MAX_FILENAME_LEN];
01317 };
01318 
01319 /*! returns a new dahdi_chan_conf with default values (by-value) */
01320 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
01321 {
01322    /* recall that if a field is not included here it is initialized
01323     * to 0 or equivalent
01324     */
01325    struct dahdi_chan_conf conf = {
01326 #ifdef HAVE_PRI
01327       .pri.pri = {
01328          .nsf = PRI_NSF_NONE,
01329          .switchtype = PRI_SWITCH_NI2,
01330          .dialplan = PRI_UNKNOWN + 1,
01331          .localdialplan = PRI_NATIONAL_ISDN + 1,
01332          .nodetype = PRI_CPE,
01333          .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
01334 
01335 #if defined(HAVE_PRI_CCSS)
01336          .cc_ptmp_recall_mode = 1,/* specificRecall */
01337          .cc_qsig_signaling_link_req = 1,/* retain */
01338          .cc_qsig_signaling_link_rsp = 1,/* retain */
01339 #endif   /* defined(HAVE_PRI_CCSS) */
01340 
01341          .minunused = 2,
01342          .idleext = "",
01343          .idledial = "",
01344          .internationalprefix = "",
01345          .nationalprefix = "",
01346          .localprefix = "",
01347          .privateprefix = "",
01348          .unknownprefix = "",
01349          .resetinterval = -1,
01350       },
01351 #endif
01352 #if defined(HAVE_SS7)
01353       .ss7.ss7 = {
01354          .called_nai = SS7_NAI_NATIONAL,
01355          .calling_nai = SS7_NAI_NATIONAL,
01356          .internationalprefix = "",
01357          .nationalprefix = "",
01358          .subscriberprefix = "",
01359          .unknownprefix = ""
01360       },
01361 #endif   /* defined(HAVE_SS7) */
01362 #ifdef HAVE_OPENR2
01363       .mfcr2 = {
01364          .variant = OR2_VAR_ITU,
01365          .mfback_timeout = -1,
01366          .metering_pulse_timeout = -1,
01367          .max_ani = 10,
01368          .max_dnis = 4,
01369          .get_ani_first = -1,
01370 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
01371          .skip_category_request = -1,
01372 #endif
01373          .call_files = 0,
01374          .allow_collect_calls = 0,
01375          .charge_calls = 1,
01376          .accept_on_offer = 1,
01377          .forced_release = 0,
01378          .double_answer = 0,
01379          .immediate_accept = -1,
01380          .logdir = "",
01381          .r2proto_file = "",
01382          .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
01383          .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
01384       },
01385 #endif
01386       .chan = {
01387          .context = "default",
01388          .cid_num = "",
01389          .cid_name = "",
01390          .cid_tag = "",
01391          .mohinterpret = "default",
01392          .mohsuggest = "",
01393          .parkinglot = "",
01394          .transfertobusy = 1,
01395 
01396          .cid_signalling = CID_SIG_BELL,
01397          .cid_start = CID_START_RING,
01398          .dahditrcallerid = 0,
01399          .use_callerid = 1,
01400          .sig = -1,
01401          .outsigmod = -1,
01402 
01403          .cid_rxgain = +5.0,
01404 
01405          .tonezone = -1,
01406 
01407          .echocancel.head.tap_length = 1,
01408 
01409          .busycount = 3,
01410 
01411          .accountcode = "",
01412 
01413          .mailbox = "",
01414 
01415 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01416          .mwisend_fsk = 1,
01417 #endif
01418          .polarityonanswerdelay = 600,
01419 
01420          .sendcalleridafter = DEFAULT_CIDRINGS,
01421 
01422          .buf_policy = DAHDI_POLICY_IMMEDIATE,
01423          .buf_no = numbufs,
01424          .usefaxbuffers = 0,
01425          .cc_params = ast_cc_config_params_init(),
01426       },
01427       .timing = {
01428          .prewinktime = -1,
01429          .preflashtime = -1,
01430          .winktime = -1,
01431          .flashtime = -1,
01432          .starttime = -1,
01433          .rxwinktime = -1,
01434          .rxflashtime = -1,
01435          .debouncetime = -1
01436       },
01437       .is_sig_auto = 1,
01438       .smdi_port = "/dev/ttyS0",
01439    };
01440 
01441    return conf;
01442 }
01443 
01444 
01445 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01446 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
01447 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
01448 static int dahdi_sendtext(struct ast_channel *c, const char *text);
01449 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
01450 static int dahdi_hangup(struct ast_channel *ast);
01451 static int dahdi_answer(struct ast_channel *ast);
01452 static struct ast_frame *dahdi_read(struct ast_channel *ast);
01453 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
01454 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
01455 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
01456 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01457 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01458 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01459 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
01460 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value);
01461 static int dahdi_devicestate(void *data);
01462 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback);
01463 
01464 static const struct ast_channel_tech dahdi_tech = {
01465    .type = "DAHDI",
01466    .description = tdesc,
01467    .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
01468    .requester = dahdi_request,
01469    .send_digit_begin = dahdi_digit_begin,
01470    .send_digit_end = dahdi_digit_end,
01471    .send_text = dahdi_sendtext,
01472    .call = dahdi_call,
01473    .hangup = dahdi_hangup,
01474    .answer = dahdi_answer,
01475    .read = dahdi_read,
01476    .write = dahdi_write,
01477    .bridge = dahdi_bridge,
01478    .exception = dahdi_exception,
01479    .indicate = dahdi_indicate,
01480    .fixup = dahdi_fixup,
01481    .setoption = dahdi_setoption,
01482    .queryoption = dahdi_queryoption,
01483    .func_channel_read = dahdi_func_read,
01484    .func_channel_write = dahdi_func_write,
01485    .devicestate = dahdi_devicestate,
01486    .cc_callback = dahdi_cc_callback,
01487 };
01488 
01489 #define GET_CHANNEL(p) ((p)->channel)
01490 
01491 #define SIG_PRI_LIB_HANDLE_CASES \
01492    SIG_PRI:                \
01493    case SIG_BRI:              \
01494    case SIG_BRI_PTMP
01495 
01496 /*!
01497  * \internal
01498  * \brief Determine if sig_pri handles the signaling.
01499  * \since 1.8
01500  *
01501  * \param signaling Signaling to determine if is for sig_pri.
01502  *
01503  * \return TRUE if the signaling is for sig_pri.
01504  */
01505 static inline int dahdi_sig_pri_lib_handles(int signaling)
01506 {
01507    int handles;
01508 
01509    switch (signaling) {
01510    case SIG_PRI_LIB_HANDLE_CASES:
01511       handles = 1;
01512       break;
01513    default:
01514       handles = 0;
01515       break;
01516    }
01517 
01518    return handles;
01519 }
01520 
01521 static enum analog_sigtype dahdisig_to_analogsig(int sig)
01522 {
01523    switch (sig) {
01524    case SIG_FXOLS:
01525       return ANALOG_SIG_FXOLS;
01526    case SIG_FXOGS:
01527       return ANALOG_SIG_FXOGS;
01528    case SIG_FXOKS:
01529       return ANALOG_SIG_FXOKS;
01530    case SIG_FXSLS:
01531       return ANALOG_SIG_FXSLS;
01532    case SIG_FXSGS:
01533       return ANALOG_SIG_FXSGS;
01534    case SIG_FXSKS:
01535       return ANALOG_SIG_FXSKS;
01536    case SIG_EMWINK:
01537       return ANALOG_SIG_EMWINK;
01538    case SIG_EM:
01539       return ANALOG_SIG_EM;
01540    case SIG_EM_E1:
01541       return ANALOG_SIG_EM_E1;
01542    case SIG_FEATD:
01543       return ANALOG_SIG_FEATD;
01544    case SIG_FEATDMF:
01545       return ANALOG_SIG_FEATDMF;
01546    case SIG_E911:
01547       return SIG_E911;
01548    case SIG_FGC_CAMA:
01549       return ANALOG_SIG_FGC_CAMA;
01550    case SIG_FGC_CAMAMF:
01551       return ANALOG_SIG_FGC_CAMAMF;
01552    case SIG_FEATB:
01553       return ANALOG_SIG_FEATB;
01554    case SIG_SFWINK:
01555       return ANALOG_SIG_SFWINK;
01556    case SIG_SF:
01557       return ANALOG_SIG_SF;
01558    case SIG_SF_FEATD:
01559       return ANALOG_SIG_SF_FEATD;
01560    case SIG_SF_FEATDMF:
01561       return ANALOG_SIG_SF_FEATDMF;
01562    case SIG_FEATDMF_TA:
01563       return ANALOG_SIG_FEATDMF_TA;
01564    case SIG_SF_FEATB:
01565       return ANALOG_SIG_FEATB;
01566    default:
01567       return -1;
01568    }
01569 }
01570 
01571 
01572 static int analog_tone_to_dahditone(enum analog_tone tone)
01573 {
01574    switch (tone) {
01575    case ANALOG_TONE_RINGTONE:
01576       return DAHDI_TONE_RINGTONE;
01577    case ANALOG_TONE_STUTTER:
01578       return DAHDI_TONE_STUTTER;
01579    case ANALOG_TONE_CONGESTION:
01580       return DAHDI_TONE_CONGESTION;
01581    case ANALOG_TONE_DIALTONE:
01582       return DAHDI_TONE_DIALTONE;
01583    case ANALOG_TONE_DIALRECALL:
01584       return DAHDI_TONE_DIALRECALL;
01585    case ANALOG_TONE_INFO:
01586       return DAHDI_TONE_INFO;
01587    default:
01588       return -1;
01589    }
01590 }
01591 
01592 static int analogsub_to_dahdisub(enum analog_sub analogsub)
01593 {
01594    int index;
01595 
01596    switch (analogsub) {
01597    case ANALOG_SUB_REAL:
01598       index = SUB_REAL;
01599       break;
01600    case ANALOG_SUB_CALLWAIT:
01601       index = SUB_CALLWAIT;
01602       break;
01603    case ANALOG_SUB_THREEWAY:
01604       index = SUB_THREEWAY;
01605       break;
01606    default:
01607       ast_log(LOG_ERROR, "Unidentified sub!\n");
01608       index = SUB_REAL;
01609    }
01610 
01611    return index;
01612 }
01613 
01614 static enum analog_event dahdievent_to_analogevent(int event);
01615 static int bump_gains(struct dahdi_pvt *p);
01616 static int dahdi_setlinear(int dfd, int linear);
01617 
01618 static int my_start_cid_detect(void *pvt, int cid_signalling)
01619 {
01620    struct dahdi_pvt *p = pvt;
01621    int index = SUB_REAL;
01622    p->cs = callerid_new(cid_signalling);
01623    if (!p->cs) {
01624       ast_log(LOG_ERROR, "Unable to alloc callerid\n");
01625       return -1;
01626    }
01627    bump_gains(p);
01628    dahdi_setlinear(p->subs[index].dfd, 0);
01629 
01630    return 0;
01631 }
01632 
01633 static int my_stop_cid_detect(void *pvt)
01634 {
01635    struct dahdi_pvt *p = pvt;
01636    int index = SUB_REAL;
01637    if (p->cs)
01638       callerid_free(p->cs);
01639    dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
01640    return 0;
01641 }
01642 
01643 static int my_get_callerid(void *pvt, char *namebuf, char *numbuf, enum analog_event *ev, size_t timeout)
01644 {
01645    struct dahdi_pvt *p = pvt;
01646    struct analog_pvt *analog_p = p->sig_pvt;
01647    struct pollfd poller;
01648    char *name, *num;
01649    int index = SUB_REAL;
01650    int res;
01651    unsigned char buf[256];
01652    int flags;
01653 
01654    poller.fd = p->subs[SUB_REAL].dfd;
01655    poller.events = POLLPRI | POLLIN;
01656    poller.revents = 0;
01657 
01658    res = poll(&poller, 1, timeout);
01659 
01660    if (poller.revents & POLLPRI) {
01661       *ev = dahdievent_to_analogevent(dahdi_get_event(p->subs[SUB_REAL].dfd));
01662       return 1;
01663    }
01664 
01665    if (poller.revents & POLLIN) {
01666       /*** NOTES ***/
01667       /* Change API: remove cid_signalling from get_callerid, add a new start_cid_detect and stop_cid_detect function
01668        * to enable slin mode and allocate cid detector. get_callerid should be able to be called any number of times until
01669        * either a timeout occurs or CID is detected (returns 0). returning 1 should be event received, and -1 should be
01670        * a failure and die, and returning 2 means no event was received. */
01671       res = read(p->subs[index].dfd, buf, sizeof(buf));
01672       if (res < 0) {
01673          if (errno != ELAST) {
01674             ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
01675             callerid_free(p->cs);
01676             return -1;
01677          }
01678       }
01679 
01680       if (analog_p->ringt > 0) {
01681          if (!(--analog_p->ringt)) {
01682             /* only return if we timeout from a ring event */
01683             return -1;
01684          }
01685       }
01686 
01687       if (p->cid_signalling == CID_SIG_V23_JP) {
01688          res = callerid_feed_jp(p->cs, buf, res, AST_LAW(p));
01689       } else {
01690          res = callerid_feed(p->cs, buf, res, AST_LAW(p));
01691       }
01692       if (res < 0) {
01693          /*
01694           * The previous diagnostic message output likely
01695           * explains why it failed.
01696           */
01697          ast_log(LOG_WARNING, "Failed to decode CallerID\n");
01698          return -1;
01699       }
01700 
01701       if (res == 1) {
01702          callerid_get(p->cs, &name, &num, &flags);
01703          if (name)
01704             ast_copy_string(namebuf, name, ANALOG_MAX_CID);
01705          if (num)
01706             ast_copy_string(numbuf, num, ANALOG_MAX_CID);
01707 
01708          ast_log(LOG_DEBUG, "CallerID number: %s, name: %s, flags=%d\n", num, name, flags);
01709          return 0;
01710       }
01711    }
01712 
01713    *ev = ANALOG_EVENT_NONE;
01714    return 2;
01715 }
01716 
01717 static const char *event2str(int event);
01718 static int restore_gains(struct dahdi_pvt *p);
01719 
01720 static int my_distinctive_ring(struct ast_channel *chan, void *pvt, int idx, int *ringdata)
01721 {
01722    unsigned char buf[256];
01723    int distMatches;
01724    int curRingData[RING_PATTERNS];
01725    int receivedRingT;
01726    int counter1;
01727    int counter;
01728    int i;
01729    int res;
01730    int checkaftercid = 0;
01731 
01732    struct dahdi_pvt *p = pvt;
01733    struct analog_pvt *analog_p = p->sig_pvt;
01734 
01735    if (ringdata == NULL) {
01736       ringdata = curRingData;
01737    } else {
01738       checkaftercid = 1;
01739    }
01740 
01741    /* We must have a ring by now, so, if configured, lets try to listen for
01742     * distinctive ringing */
01743    if ((checkaftercid && distinctiveringaftercid) || !checkaftercid) {
01744       /* Clear the current ring data array so we don't have old data in it. */
01745       for (receivedRingT = 0; receivedRingT < RING_PATTERNS; receivedRingT++)
01746          ringdata[receivedRingT] = 0;
01747       receivedRingT = 0;
01748       if (checkaftercid && distinctiveringaftercid)
01749          ast_verb(3, "Detecting post-CID distinctive ring\n");
01750       /* Check to see if context is what it should be, if not set to be. */
01751       else if (strcmp(p->context,p->defcontext) != 0) {
01752          ast_copy_string(p->context, p->defcontext, sizeof(p->context));
01753          ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
01754       }
01755 
01756       for (;;) {
01757          i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
01758          if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
01759             ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
01760             ast_hangup(chan);
01761             return 1;
01762          }
01763          if (i & DAHDI_IOMUX_SIGEVENT) {
01764             res = dahdi_get_event(p->subs[idx].dfd);
01765             if (res == DAHDI_EVENT_NOALARM) {
01766                p->inalarm = 0;
01767                analog_p->inalarm = 0;
01768             }
01769             ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
01770             res = 0;
01771             /* Let us detect distinctive ring */
01772 
01773             ringdata[receivedRingT] = analog_p->ringt;
01774 
01775             if (analog_p->ringt < analog_p->ringt_base/2)
01776                break;
01777             /* Increment the ringT counter so we can match it against
01778                values in chan_dahdi.conf for distinctive ring */
01779             if (++receivedRingT == RING_PATTERNS)
01780                break;
01781          } else if (i & DAHDI_IOMUX_READ) {
01782             res = read(p->subs[idx].dfd, buf, sizeof(buf));
01783             if (res < 0) {
01784                if (errno != ELAST) {
01785                   ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
01786                   ast_hangup(chan);
01787                   return 1;
01788                }
01789                break;
01790             }
01791             if (analog_p->ringt > 0) {
01792                if (!(--analog_p->ringt)) {
01793                   res = -1;
01794                   break;
01795                }
01796             }
01797          }
01798       }
01799    }
01800    if ((checkaftercid && usedistinctiveringdetection) || !checkaftercid) {
01801       /* this only shows up if you have n of the dring patterns filled in */
01802       ast_verb(3, "Detected ring pattern: %d,%d,%d\n",ringdata[0],ringdata[1],ringdata[2]);
01803       for (counter = 0; counter < 3; counter++) {
01804       /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this channel */
01805          distMatches = 0;
01806          /* this only shows up if you have n of the dring patterns filled in */
01807          ast_verb(3, "Checking %d,%d,%d\n",
01808                p->drings.ringnum[counter].ring[0],
01809                p->drings.ringnum[counter].ring[1],
01810                p->drings.ringnum[counter].ring[2]);
01811          for (counter1 = 0; counter1 < 3; counter1++) {
01812             ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
01813             if (p->drings.ringnum[counter].ring[counter1] == -1) {
01814                ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
01815                ringdata[counter1]);
01816                distMatches++;
01817             } else if (ringdata[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
01818                               ringdata[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
01819                ast_verb(3, "Ring pattern matched in range: %d to %d\n",
01820                (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
01821                (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
01822                distMatches++;
01823             }
01824          }
01825 
01826          if (distMatches == 3) {
01827             /* The ring matches, set the context to whatever is for distinctive ring.. */
01828             ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
01829             ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
01830             ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
01831             break;
01832          }
01833       }
01834    }
01835    /* Restore linear mode (if appropriate) for Caller*ID processing */
01836    dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
01837    restore_gains(p);
01838 
01839    return 0;
01840 }
01841 
01842 static int send_callerid(struct dahdi_pvt *p);
01843 
01844 static int my_stop_callwait(void *pvt)
01845 {
01846    struct dahdi_pvt *p = pvt;
01847    p->callwaitingrepeat = 0;
01848    p->cidcwexpire = 0;
01849 
01850    return 0;
01851 }
01852 
01853 static int save_conference(struct dahdi_pvt *p);
01854 
01855 static int my_callwait(void *pvt)
01856 {
01857    struct dahdi_pvt *p = pvt;
01858    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
01859    if (p->cidspill) {
01860       ast_log(LOG_WARNING, "Spill already exists?!?\n");
01861       ast_free(p->cidspill);
01862    }
01863    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
01864       return -1;
01865    save_conference(p);
01866    /* Silence */
01867    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
01868    if (!p->callwaitrings && p->callwaitingcallerid) {
01869       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
01870       p->callwaitcas = 1;
01871       p->cidlen = 2400 + 680 + READ_SIZE * 4;
01872    } else {
01873       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
01874       p->callwaitcas = 0;
01875       p->cidlen = 2400 + READ_SIZE * 4;
01876    }
01877    p->cidpos = 0;
01878    send_callerid(p);
01879 
01880    return 0;
01881 }
01882 
01883 static int my_send_callerid(void *pvt, int cwcid, struct ast_party_caller *caller)
01884 {
01885    struct dahdi_pvt *p = pvt;
01886 
01887    ast_debug(2, "Starting cid spill\n");
01888 
01889    if (p->cidspill) {
01890       ast_log(LOG_WARNING, "cidspill already exists??\n");
01891       ast_free(p->cidspill);
01892    }
01893 
01894    if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
01895       if (cwcid == 0) {
01896          p->cidlen = ast_callerid_generate(p->cidspill,
01897             caller->id.name.str,
01898             caller->id.number.str,
01899             AST_LAW(p));
01900       } else {
01901          p->callwaitcas = 0;
01902          p->cidcwexpire = 0;
01903          p->cidlen = ast_callerid_callwaiting_generate(p->cidspill,
01904             caller->id.name.str,
01905             caller->id.number.str,
01906             AST_LAW(p));
01907          p->cidlen += READ_SIZE * 4;
01908       }
01909       p->cidpos = 0;
01910       send_callerid(p);
01911    }
01912    return 0;
01913 }
01914 
01915 static int my_dsp_reset_and_flush_digits(void *pvt)
01916 {
01917    struct dahdi_pvt *p = pvt;
01918    if (p->dsp)
01919       ast_dsp_digitreset(p->dsp);
01920 
01921    return 0;
01922 }
01923 
01924 static int my_dsp_set_digitmode(void *pvt, enum analog_dsp_digitmode mode)
01925 {
01926    struct dahdi_pvt *p = pvt;
01927 
01928    if (p->channel == CHAN_PSEUDO)
01929       ast_log(LOG_ERROR, "You have assumed incorrectly sir!\n");
01930 
01931    if (mode == ANALOG_DIGITMODE_DTMF) {
01932       /* If we do hardware dtmf, no need for a DSP */
01933       if (p->hardwaredtmf) {
01934          if (p->dsp) {
01935             ast_dsp_free(p->dsp);
01936             p->dsp = NULL;
01937          }
01938          return 0;
01939       }
01940 
01941       if (!p->dsp) {
01942          p->dsp = ast_dsp_new();
01943          if (!p->dsp) {
01944             ast_log(LOG_ERROR, "Unable to allocate DSP\n");
01945             return -1;
01946          }
01947       }
01948 
01949       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
01950    } else if (mode == ANALOG_DIGITMODE_MF) {
01951       if (!p->dsp) {
01952          p->dsp = ast_dsp_new();
01953          if (!p->dsp) {
01954             ast_log(LOG_ERROR, "Unable to allocate DSP\n");
01955             return -1;
01956          }
01957       }
01958       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
01959    }
01960    return 0;
01961 }
01962 
01963 static int dahdi_wink(struct dahdi_pvt *p, int index);
01964 
01965 static int my_wink(void *pvt, enum analog_sub sub)
01966 {
01967    struct dahdi_pvt *p = pvt;
01968    int index = analogsub_to_dahdisub(sub);
01969    if (index != SUB_REAL) {
01970       ast_log(LOG_ERROR, "We used a sub other than SUB_REAL (incorrect assumption sir)\n");
01971    }
01972    return dahdi_wink(p, index);
01973 }
01974 
01975 static void wakeup_sub(struct dahdi_pvt *p, int a);
01976 
01977 static int reset_conf(struct dahdi_pvt *p);
01978 
01979 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted);
01980 
01981 static void my_handle_dtmfup(void *pvt, struct ast_channel *ast, enum analog_sub analog_index, struct ast_frame **dest)
01982 {
01983    struct ast_frame *f = *dest;
01984    struct dahdi_pvt *p = pvt;
01985    int idx = analogsub_to_dahdisub(analog_index);
01986 
01987    ast_debug(1, "DTMF digit: %c on %s\n", f->subclass.integer, ast->name);
01988 
01989    if (f->subclass.integer == 'f') {
01990       /* Fax tone -- Handle and return NULL */
01991       if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
01992          /* If faxbuffers are configured, use them for the fax transmission */
01993          if (p->usefaxbuffers && !p->bufferoverrideinuse) {
01994             struct dahdi_bufferinfo bi = {
01995                .txbufpolicy = p->faxbuf_policy,
01996                .bufsize = p->bufsize,
01997                .numbufs = p->faxbuf_no
01998             };
01999             int res;
02000 
02001             if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
02002                ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
02003             } else {
02004                p->bufferoverrideinuse = 1;
02005             }
02006          }
02007          p->faxhandled = 1;
02008          if (p->dsp) {
02009             p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
02010             ast_dsp_set_features(p->dsp, p->dsp_features);
02011             ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
02012          }
02013          if (strcmp(ast->exten, "fax")) {
02014             const char *target_context = S_OR(ast->macrocontext, ast->context);
02015 
02016             /* We need to unlock 'ast' here because ast_exists_extension has the
02017              * potential to start autoservice on the channel. Such action is prone
02018              * to deadlock.
02019              */
02020             ast_mutex_unlock(&p->lock);
02021             ast_channel_unlock(ast);
02022             if (ast_exists_extension(ast, target_context, "fax", 1,
02023                S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
02024                ast_channel_lock(ast);
02025                ast_mutex_lock(&p->lock);
02026                ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
02027                /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
02028                pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
02029                if (ast_async_goto(ast, target_context, "fax", 1))
02030                   ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
02031             } else {
02032                ast_channel_lock(ast);
02033                ast_mutex_lock(&p->lock);
02034                ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
02035             }
02036          } else {
02037             ast_debug(1, "Already in a fax extension, not redirecting\n");
02038          }
02039       } else {
02040          ast_debug(1, "Fax already handled\n");
02041       }
02042       dahdi_confmute(p, 0);
02043       p->subs[idx].f.frametype = AST_FRAME_NULL;
02044       p->subs[idx].f.subclass.integer = 0;
02045       *dest = &p->subs[idx].f;
02046    }
02047 }
02048 
02049 static void my_lock_private(void *pvt)
02050 {
02051    struct dahdi_pvt *p = pvt;
02052    ast_mutex_lock(&p->lock);
02053 }
02054 
02055 static void my_unlock_private(void *pvt)
02056 {
02057    struct dahdi_pvt *p = pvt;
02058    ast_mutex_unlock(&p->lock);
02059 }
02060 
02061 static void my_deadlock_avoidance_private(void *pvt)
02062 {
02063    struct dahdi_pvt *p = pvt;
02064 
02065    DEADLOCK_AVOIDANCE(&p->lock);
02066 }
02067 
02068 /* linear_mode = 0 - turn linear mode off, >0 - turn linear mode on
02069 *  returns the last value of the linear setting 
02070 */ 
02071 static int my_set_linear_mode(void *pvt, int idx, int linear_mode)
02072 {
02073    struct dahdi_pvt *p = pvt;
02074    int oldval;
02075    
02076     if (0 > linear_mode || !dahdi_setlinear(p->subs[idx].dfd, linear_mode)) {
02077         return -1;
02078     }
02079    oldval = p->subs[idx].linear;
02080    p->subs[idx].linear = linear_mode;
02081    return oldval;
02082 }
02083 
02084 static int get_alarms(struct dahdi_pvt *p);
02085 static void handle_alarms(struct dahdi_pvt *p, int alms);
02086 static void my_get_and_handle_alarms(void *pvt)
02087 {
02088    int res;
02089    struct dahdi_pvt *p = pvt;
02090 
02091    res = get_alarms(p);
02092    handle_alarms(p, res);
02093 }
02094 
02095 static void *my_get_sigpvt_bridged_channel(struct ast_channel *chan)
02096 {
02097    struct dahdi_pvt *p = ast_bridged_channel(chan)->tech_pvt;
02098    if (p)
02099       return p->sig_pvt;
02100    else
02101       return NULL;
02102 }
02103 
02104 static int my_get_sub_fd(void *pvt, enum analog_sub sub)
02105 {
02106    struct dahdi_pvt *p = pvt;
02107    int dahdi_sub = analogsub_to_dahdisub(sub);
02108    return p->subs[dahdi_sub].dfd;
02109 }
02110 
02111 static void my_set_cadence(void *pvt, int *cidrings, struct ast_channel *ast)
02112 {
02113    struct dahdi_pvt *p = pvt;
02114 
02115    /* Choose proper cadence */
02116    if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
02117       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
02118          ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast->name, strerror(errno));
02119       *cidrings = cidrings[p->distinctivering - 1];
02120    } else {
02121       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
02122          ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast->name, strerror(errno));
02123       *cidrings = p->sendcalleridafter;
02124    }
02125 }
02126 
02127 static void my_set_alarm(void *pvt, int in_alarm)
02128 {
02129    struct dahdi_pvt *p = pvt;
02130 
02131    p->inalarm = in_alarm;
02132 }
02133 
02134 static void my_set_dialing(void *pvt, int is_dialing)
02135 {
02136    struct dahdi_pvt *p = pvt;
02137 
02138    p->dialing = is_dialing;
02139 }
02140 
02141 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02142 static void my_set_digital(void *pvt, int is_digital)
02143 {
02144    struct dahdi_pvt *p = pvt;
02145 
02146    p->digital = is_digital;
02147 }
02148 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02149 
02150 #if defined(HAVE_SS7)
02151 static void my_set_inservice(void *pvt, int is_inservice)
02152 {
02153    struct dahdi_pvt *p = pvt;
02154 
02155    p->inservice = is_inservice;
02156 }
02157 #endif   /* defined(HAVE_SS7) */
02158 
02159 #if defined(HAVE_SS7)
02160 static void my_set_locallyblocked(void *pvt, int is_blocked)
02161 {
02162    struct dahdi_pvt *p = pvt;
02163 
02164    p->locallyblocked = is_blocked;
02165 }
02166 #endif   /* defined(HAVE_SS7) */
02167 
02168 #if defined(HAVE_SS7)
02169 static void my_set_remotelyblocked(void *pvt, int is_blocked)
02170 {
02171    struct dahdi_pvt *p = pvt;
02172 
02173    p->remotelyblocked = is_blocked;
02174 }
02175 #endif   /* defined(HAVE_SS7) */
02176 
02177 static void my_set_ringtimeout(void *pvt, int ringt)
02178 {
02179    struct dahdi_pvt *p = pvt;
02180    p->ringt = ringt;
02181 }
02182 
02183 static void my_set_waitingfordt(void *pvt, struct ast_channel *ast)
02184 {
02185    struct dahdi_pvt *p = pvt;
02186 
02187    if (p->waitfordialtone && CANPROGRESSDETECT(p) && p->dsp) {
02188       ast_log(LOG_DEBUG, "Defer dialing for %dms or dialtone\n", p->waitfordialtone);
02189       gettimeofday(&p->waitingfordt, NULL);
02190       ast_setstate(ast, AST_STATE_OFFHOOK);
02191    }
02192 }
02193 
02194 static int my_check_waitingfordt(void *pvt)
02195 {
02196    struct dahdi_pvt *p = pvt;
02197 
02198    if (p->waitingfordt.tv_usec) {
02199       return 1;
02200    }
02201 
02202    return 0;
02203 }
02204 
02205 static void my_set_confirmanswer(void *pvt, int flag)
02206 {
02207    struct dahdi_pvt *p = pvt;
02208    p->confirmanswer = flag;
02209 }
02210 
02211 static int my_check_confirmanswer(void *pvt)
02212 {
02213    struct dahdi_pvt *p = pvt;
02214    if (p->confirmanswer) {
02215       return 1;
02216    }
02217 
02218    return 0;
02219 }
02220 
02221 static void my_cancel_cidspill(void *pvt)
02222 {
02223    struct dahdi_pvt *p = pvt;
02224    if (p->cidspill) {
02225       ast_free(p->cidspill);
02226       p->cidspill = NULL;
02227    }
02228 }
02229 
02230 static int my_confmute(void *pvt, int mute)
02231 {
02232    struct dahdi_pvt *p = pvt;
02233    return dahdi_confmute(p, mute);
02234 }
02235 
02236 static void my_set_pulsedial(void *pvt, int flag)
02237 {
02238    struct dahdi_pvt *p = pvt;
02239    p->pulsedial = flag;
02240 }
02241 
02242 static const char *my_get_orig_dialstring(void *pvt)
02243 {
02244    struct dahdi_pvt *p = pvt;
02245 
02246    return p->dialstring;
02247 }
02248 
02249 static void my_increase_ss_count(void)
02250 {
02251    ast_mutex_lock(&ss_thread_lock);
02252    ss_thread_count++;
02253    ast_mutex_unlock(&ss_thread_lock);
02254 }
02255 
02256 static void my_decrease_ss_count(void)
02257 {
02258    ast_mutex_lock(&ss_thread_lock);
02259    ss_thread_count--;
02260    ast_cond_signal(&ss_thread_complete);
02261    ast_mutex_unlock(&ss_thread_lock);
02262 }
02263 
02264 static void my_all_subchannels_hungup(void *pvt)
02265 {
02266    struct dahdi_pvt *p = pvt;
02267    int res, law;
02268 
02269    p->faxhandled = 0;
02270    p->didtdd = 0;
02271 
02272    if (p->dsp) {
02273       ast_dsp_free(p->dsp);
02274       p->dsp = NULL;
02275    }
02276 
02277    p->law = p->law_default;
02278    law = p->law_default;
02279    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
02280    if (res < 0)
02281       ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
02282 
02283    dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
02284 
02285 #if 1
02286    {
02287    int i;
02288    p->owner = NULL;
02289    /* Cleanup owners here */
02290    for (i = 0; i < 3; i++) {
02291       p->subs[i].owner = NULL;
02292    }
02293    }
02294 #endif
02295 
02296    reset_conf(p);
02297    if (num_restart_pending == 0) {
02298       restart_monitor();
02299    }
02300 }
02301 
02302 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index);
02303 
02304 static int my_conf_del(void *pvt, enum analog_sub sub)
02305 {
02306    struct dahdi_pvt *p = pvt;
02307    int x = analogsub_to_dahdisub(sub);
02308 
02309    return conf_del(p, &p->subs[x], x);
02310 }
02311 
02312 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index, int slavechannel);
02313 
02314 static int my_conf_add(void *pvt, enum analog_sub sub)
02315 {
02316    struct dahdi_pvt *p = pvt;
02317    int x = analogsub_to_dahdisub(sub);
02318 
02319    return conf_add(p, &p->subs[x], x, 0);
02320 }
02321 
02322 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out);
02323 
02324 static int my_complete_conference_update(void *pvt, int needconference)
02325 {
02326    struct dahdi_pvt *p = pvt;
02327    int needconf = needconference;
02328    int x;
02329    int useslavenative;
02330    struct dahdi_pvt *slave = NULL;
02331 
02332    useslavenative = isslavenative(p, &slave);
02333 
02334    /* If we have a slave, add him to our conference now. or DAX
02335       if this is slave native */
02336    for (x = 0; x < MAX_SLAVES; x++) {
02337       if (p->slaves[x]) {
02338          if (useslavenative)
02339             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
02340          else {
02341             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
02342             needconf++;
02343          }
02344       }
02345    }
02346    /* If we're supposed to be in there, do so now */
02347    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
02348       if (useslavenative)
02349          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
02350       else {
02351          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
02352          needconf++;
02353       }
02354    }
02355    /* If we have a master, add ourselves to his conference */
02356    if (p->master) {
02357       if (isslavenative(p->master, NULL)) {
02358          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
02359       } else {
02360          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
02361       }
02362    }
02363    if (!needconf) {
02364       /* Nobody is left (or should be left) in our conference.
02365          Kill it. */
02366       p->confno = -1;
02367    }
02368 
02369    return 0;
02370 }
02371 
02372 static int check_for_conference(struct dahdi_pvt *p);
02373 
02374 static int my_check_for_conference(void *pvt)
02375 {
02376    struct dahdi_pvt *p = pvt;
02377    return check_for_conference(p);
02378 }
02379 
02380 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)
02381 {
02382    struct dahdi_pvt *p = pvt;
02383    int da, db;
02384    int tchan;
02385 
02386    da = analogsub_to_dahdisub(a);
02387    db = analogsub_to_dahdisub(b);
02388 
02389    tchan = p->subs[da].chan;
02390 
02391    p->subs[da].chan = p->subs[db].chan;
02392 
02393    p->subs[db].chan = tchan;
02394 
02395    if (ast_a)
02396       ast_channel_set_fd(ast_a, 0, p->subs[da].dfd);
02397    if (ast_b)
02398       ast_channel_set_fd(ast_b, 0, p->subs[db].dfd);
02399 
02400    p->subs[da].owner = ast_a;
02401    p->subs[db].owner = ast_b;
02402 
02403    wakeup_sub(p, a);
02404    wakeup_sub(p, b);
02405 
02406    return;
02407 }
02408 
02409 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid);
02410 
02411 static struct ast_channel *my_new_analog_ast_channel(void *pvt, int state, int startpbx, enum analog_sub sub, const struct ast_channel *requestor)
02412 {
02413    struct dahdi_pvt *p = pvt;
02414    int dsub = analogsub_to_dahdisub(sub);
02415 
02416    return dahdi_new(p, state, startpbx, dsub, 0, requestor ? requestor->linkedid : "");
02417 }
02418 
02419 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02420 static int dahdi_setlaw(int dfd, int law)
02421 {
02422    int res;
02423    res = ioctl(dfd, DAHDI_SETLAW, &law);
02424    if (res)
02425       return res;
02426    return 0;
02427 }
02428 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02429 
02430 #if defined(HAVE_PRI)
02431 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)
02432 {
02433    struct dahdi_pvt *p = pvt;
02434    int audio;
02435    int newlaw = -1;
02436 
02437    switch (p->sig) {
02438    case SIG_PRI_LIB_HANDLE_CASES:
02439       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
02440          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
02441          break;
02442       }
02443       /* Fall through */
02444    default:
02445       /* Set to audio mode at this point */
02446       audio = 1;
02447       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1) {
02448          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
02449             p->channel, audio, strerror(errno));
02450       }
02451       break;
02452    }
02453 
02454    if (law != SIG_PRI_DEFLAW) {
02455       dahdi_setlaw(p->subs[SUB_REAL].dfd, (law == SIG_PRI_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
02456    }
02457 
02458    ast_copy_string(p->exten, exten, sizeof(p->exten));
02459 
02460    switch (law) {
02461       case SIG_PRI_DEFLAW:
02462          newlaw = 0;
02463          break;
02464       case SIG_PRI_ALAW:
02465          newlaw = DAHDI_LAW_ALAW;
02466          break;
02467       case SIG_PRI_ULAW:
02468          newlaw = DAHDI_LAW_MULAW;
02469          break;
02470    }
02471    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
02472 }
02473 #endif   /* defined(HAVE_PRI) */
02474 
02475 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law);
02476 
02477 #if defined(HAVE_PRI)
02478 /*!
02479  * \internal
02480  * \brief Open the PRI channel media path.
02481  * \since 1.8
02482  *
02483  * \param p Channel private control structure.
02484  *
02485  * \return Nothing
02486  */
02487 static void my_pri_open_media(void *p)
02488 {
02489    struct dahdi_pvt *pvt = p;
02490    int res;
02491    int dfd;
02492    int set_val;
02493 
02494    dfd = pvt->subs[SUB_REAL].dfd;
02495 
02496    /* Open the media path. */
02497    set_val = 1;
02498    res = ioctl(dfd, DAHDI_AUDIOMODE, &set_val);
02499    if (res < 0) {
02500       ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n",
02501          pvt->channel, strerror(errno));
02502    }
02503 
02504    /* Set correct companding law for this call. */
02505    res = dahdi_setlaw(dfd, pvt->law);
02506    if (res < 0) {
02507       ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pvt->channel);
02508    }
02509 
02510    /* Set correct gain for this call. */
02511    if (pvt->digital) {
02512       res = set_actual_gain(dfd, 0, 0, pvt->rxdrc, pvt->txdrc, pvt->law);
02513    } else {
02514       res = set_actual_gain(dfd, pvt->rxgain, pvt->txgain, pvt->rxdrc, pvt->txdrc,
02515          pvt->law);
02516    }
02517    if (res < 0) {
02518       ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pvt->channel);
02519    }
02520 
02521    if (pvt->dsp_features && pvt->dsp) {
02522       ast_dsp_set_features(pvt->dsp, pvt->dsp_features);
02523       pvt->dsp_features = 0;
02524    }
02525 }
02526 #endif   /* defined(HAVE_PRI) */
02527 
02528 static int unalloc_sub(struct dahdi_pvt *p, int x);
02529 
02530 static int my_unallocate_sub(void *pvt, enum analog_sub analogsub)
02531 {
02532    struct dahdi_pvt *p = pvt;
02533 
02534    return unalloc_sub(p, analogsub_to_dahdisub(analogsub));
02535 }
02536 
02537 static int alloc_sub(struct dahdi_pvt *p, int x);
02538 
02539 static int my_allocate_sub(void *pvt, enum analog_sub analogsub)
02540 {
02541    struct dahdi_pvt *p = pvt;
02542 
02543    return alloc_sub(p, analogsub_to_dahdisub(analogsub));
02544 }
02545 
02546 static int has_voicemail(struct dahdi_pvt *p);
02547 
02548 static int my_has_voicemail(void *pvt)
02549 {
02550    struct dahdi_pvt *p = pvt;
02551 
02552    return has_voicemail(p);
02553 }
02554 
02555 static int my_play_tone(void *pvt, enum analog_sub sub, enum analog_tone tone)
02556 {
02557    struct dahdi_pvt *p = pvt;
02558    int index;
02559 
02560    index = analogsub_to_dahdisub(sub);
02561 
02562    return tone_zone_play_tone(p->subs[index].dfd, analog_tone_to_dahditone(tone));
02563 }
02564 
02565 static enum analog_event dahdievent_to_analogevent(int event)
02566 {
02567    enum analog_event res;
02568 
02569    switch (event) {
02570    case DAHDI_EVENT_ONHOOK:
02571       res = ANALOG_EVENT_ONHOOK;
02572       break;
02573    case DAHDI_EVENT_RINGOFFHOOK:
02574       res = ANALOG_EVENT_RINGOFFHOOK;
02575       break;
02576    case DAHDI_EVENT_WINKFLASH:
02577       res = ANALOG_EVENT_WINKFLASH;
02578       break;
02579    case DAHDI_EVENT_ALARM:
02580       res = ANALOG_EVENT_ALARM;
02581       break;
02582    case DAHDI_EVENT_NOALARM:
02583       res = ANALOG_EVENT_NOALARM;
02584       break;
02585    case DAHDI_EVENT_DIALCOMPLETE:
02586       res = ANALOG_EVENT_DIALCOMPLETE;
02587       break;
02588    case DAHDI_EVENT_RINGERON:
02589       res = ANALOG_EVENT_RINGERON;
02590       break;
02591    case DAHDI_EVENT_RINGEROFF:
02592       res = ANALOG_EVENT_RINGEROFF;
02593       break;
02594    case DAHDI_EVENT_HOOKCOMPLETE:
02595       res = ANALOG_EVENT_HOOKCOMPLETE;
02596       break;
02597    case DAHDI_EVENT_PULSE_START:
02598       res = ANALOG_EVENT_PULSE_START;
02599       break;
02600    case DAHDI_EVENT_POLARITY:
02601       res = ANALOG_EVENT_POLARITY;
02602       break;
02603    case DAHDI_EVENT_RINGBEGIN:
02604       res = ANALOG_EVENT_RINGBEGIN;
02605       break;
02606    case DAHDI_EVENT_EC_DISABLED:
02607       res = ANALOG_EVENT_EC_DISABLED;
02608       break;
02609    case DAHDI_EVENT_REMOVED:
02610       res = ANALOG_EVENT_REMOVED;
02611       break;
02612    case DAHDI_EVENT_NEONMWI_ACTIVE:
02613       res = ANALOG_EVENT_NEONMWI_ACTIVE;
02614       break;
02615    case DAHDI_EVENT_NEONMWI_INACTIVE:
02616       res = ANALOG_EVENT_NEONMWI_INACTIVE;
02617       break;
02618 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
02619    case DAHDI_EVENT_TX_CED_DETECTED:
02620       res = ANALOG_EVENT_TX_CED_DETECTED;
02621       break;
02622    case DAHDI_EVENT_RX_CED_DETECTED:
02623       res = ANALOG_EVENT_RX_CED_DETECTED;
02624       break;
02625    case DAHDI_EVENT_EC_NLP_DISABLED:
02626       res = ANALOG_EVENT_EC_NLP_DISABLED;
02627       break;
02628    case DAHDI_EVENT_EC_NLP_ENABLED:
02629       res = ANALOG_EVENT_EC_NLP_ENABLED;
02630       break;
02631 #endif
02632    case DAHDI_EVENT_PULSEDIGIT:
02633       res = ANALOG_EVENT_PULSEDIGIT;
02634       break;
02635    case DAHDI_EVENT_DTMFDOWN:
02636       res = ANALOG_EVENT_DTMFDOWN;
02637       break;
02638    case DAHDI_EVENT_DTMFUP:
02639       res = ANALOG_EVENT_DTMFUP;
02640       break;
02641    default:
02642       switch(event & 0xFFFF0000) {
02643       case DAHDI_EVENT_PULSEDIGIT:
02644       case DAHDI_EVENT_DTMFDOWN:
02645       case DAHDI_EVENT_DTMFUP:
02646          /* The event includes a digit number in the low word.
02647           * Converting it to a 'enum analog_event' would remove
02648           * that information. Thus it is returned as-is.
02649           */
02650          return event;
02651       }
02652 
02653       res = ANALOG_EVENT_ERROR;
02654       break;
02655    }
02656 
02657    return res;
02658 }
02659 
02660 static inline int dahdi_wait_event(int fd);
02661 
02662 static int my_wait_event(void *pvt)
02663 {
02664    struct dahdi_pvt *p = pvt;
02665 
02666    return dahdi_wait_event(p->subs[SUB_REAL].dfd);
02667 }
02668 
02669 static int my_get_event(void *pvt)
02670 {
02671    struct dahdi_pvt *p = pvt;
02672    int res;
02673 
02674    if (p->fake_event) {
02675       res = p->fake_event;
02676       p->fake_event = 0;
02677    } else
02678       res = dahdi_get_event(p->subs[SUB_REAL].dfd);
02679 
02680    return dahdievent_to_analogevent(res);
02681 }
02682 
02683 static int my_is_off_hook(void *pvt)
02684 {
02685    struct dahdi_pvt *p = pvt;
02686    int res;
02687    struct dahdi_params par;
02688 
02689    memset(&par, 0, sizeof(par));
02690 
02691    if (p->subs[SUB_REAL].dfd > -1)
02692       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
02693    else {
02694       /* Assume not off hook on CVRS */
02695       res = 0;
02696       par.rxisoffhook = 0;
02697    }
02698    if (res) {
02699       ast_log(LOG_WARNING, "Unable to check hook state on channel %d: %s\n", p->channel, strerror(errno));
02700    }
02701 
02702    if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
02703       /* When "onhook" that means no battery on the line, and thus
02704       it is out of service..., if it's on a TDM card... If it's a channel
02705       bank, there is no telling... */
02706       return (par.rxbits > -1) || par.rxisoffhook;
02707    }
02708 
02709    return par.rxisoffhook;
02710 }
02711 
02712 static void dahdi_enable_ec(struct dahdi_pvt *p);
02713 static void dahdi_disable_ec(struct dahdi_pvt *p);
02714 
02715 static int my_set_echocanceller(void *pvt, int enable)
02716 {
02717    struct dahdi_pvt *p = pvt;
02718 
02719    if (enable)
02720       dahdi_enable_ec(p);
02721    else
02722       dahdi_disable_ec(p);
02723 
02724    return 0;
02725 }
02726 
02727 static int dahdi_ring_phone(struct dahdi_pvt *p);
02728 
02729 static int my_ring(void *pvt)
02730 {
02731    struct dahdi_pvt *p = pvt;
02732 
02733    return dahdi_ring_phone(p);
02734 }
02735 
02736 static int my_flash(void *pvt)
02737 {
02738    struct dahdi_pvt *p = pvt;
02739    int func = DAHDI_FLASH;
02740    return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &func);
02741 }
02742 
02743 static inline int dahdi_set_hook(int fd, int hs);
02744 
02745 static int my_off_hook(void *pvt)
02746 {
02747    struct dahdi_pvt *p = pvt;
02748    return dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
02749 }
02750 
02751 static void my_set_needringing(void *pvt, int value)
02752 {
02753    struct dahdi_pvt *p = pvt;
02754    p->subs[SUB_REAL].needringing = value;
02755 }
02756 
02757 static void my_set_polarity(void *pvt, int value)
02758 {
02759    struct dahdi_pvt *p = pvt;
02760 
02761    if (p->channel == CHAN_PSEUDO) {
02762       return;
02763    }
02764    p->polarity = value;
02765    ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETPOLARITY, &value);
02766 }
02767 
02768 static void my_start_polarityswitch(void *pvt)
02769 {
02770    struct dahdi_pvt *p = pvt;
02771 
02772    if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
02773       my_set_polarity(pvt, 0);
02774    }
02775 }
02776 
02777 static void my_answer_polarityswitch(void *pvt)
02778 {
02779    struct dahdi_pvt *p = pvt;
02780 
02781    if (!p->answeronpolarityswitch) {
02782       return;
02783    }
02784 
02785    my_set_polarity(pvt, 1);
02786 }
02787 
02788 static void my_hangup_polarityswitch(void *pvt)
02789 {
02790    struct dahdi_pvt *p = pvt;
02791 
02792    if (!p->hanguponpolarityswitch) {
02793       return;
02794    }
02795 
02796    if (p->answeronpolarityswitch) {
02797       my_set_polarity(pvt, 0);
02798    } else {
02799       my_set_polarity(pvt, 1);
02800    }
02801 }
02802 
02803 static int my_start(void *pvt)
02804 {
02805    struct dahdi_pvt *p = pvt;
02806    int x = DAHDI_START;
02807 
02808    return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
02809 }
02810 
02811 static int my_dial_digits(void *pvt, enum analog_sub sub, struct analog_dialoperation *dop)
02812 {
02813    int index = analogsub_to_dahdisub(sub);
02814    int res;
02815    struct dahdi_pvt *p = pvt;
02816    struct dahdi_dialoperation ddop;
02817 
02818    if (dop->op != ANALOG_DIAL_OP_REPLACE) {
02819       ast_log(LOG_ERROR, "Fix the dial_digits callback!\n");
02820       return -1;
02821    }
02822 
02823    if (sub != ANALOG_SUB_REAL)
02824       printf("Trying to dial digits on sub %d\n", sub);
02825 
02826    ddop.op = DAHDI_DIAL_OP_REPLACE;
02827    strncpy(ddop.dialstr, dop->dialstr, sizeof(ddop.dialstr));
02828 
02829    printf("Dialing %s on %d\n", ddop.dialstr, p->channel);
02830 
02831    res = ioctl(p->subs[index].dfd, DAHDI_DIAL, &ddop);
02832 
02833    if (res == -1)
02834       ast_log(LOG_DEBUG, "DAHDI_DIAL ioctl failed on %s: %s\n", p->owner->name, strerror(errno));
02835 
02836    return res;
02837 }
02838 
02839 static void dahdi_train_ec(struct dahdi_pvt *p);
02840 
02841 static int my_train_echocanceller(void *pvt)
02842 {
02843    struct dahdi_pvt *p = pvt;
02844 
02845    dahdi_train_ec(p);
02846 
02847    return 0;
02848 }
02849 
02850 static int my_is_dialing(void *pvt, enum analog_sub sub)
02851 {
02852    struct dahdi_pvt *p = pvt;
02853    int index;
02854    int x;
02855 
02856    index = analogsub_to_dahdisub(sub);
02857 
02858    if (ioctl(p->subs[index].dfd, DAHDI_DIALING, &x)) {
02859       ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed!\n");
02860       return -1;
02861    }
02862 
02863    return x;
02864 }
02865 
02866 static int my_on_hook(void *pvt)
02867 {
02868    struct dahdi_pvt *p = pvt;
02869    return dahdi_set_hook(p->subs[ANALOG_SUB_REAL].dfd, DAHDI_ONHOOK);
02870 }
02871 
02872 #if defined(HAVE_PRI)
02873 static void my_pri_fixup_chans(void *chan_old, void *chan_new)
02874 {
02875    struct dahdi_pvt *old_chan = chan_old;
02876    struct dahdi_pvt *new_chan = chan_new;
02877 
02878    new_chan->owner = old_chan->owner;
02879    old_chan->owner = NULL;
02880    if (new_chan->owner) {
02881       new_chan->owner->tech_pvt = new_chan;
02882       new_chan->owner->fds[0] = new_chan->subs[SUB_REAL].dfd;
02883       new_chan->subs[SUB_REAL].owner = old_chan->subs[SUB_REAL].owner;
02884       old_chan->subs[SUB_REAL].owner = NULL;
02885    }
02886    /* Copy any DSP that may be present */
02887    new_chan->dsp = old_chan->dsp;
02888    new_chan->dsp_features = old_chan->dsp_features;
02889    old_chan->dsp = NULL;
02890    old_chan->dsp_features = 0;
02891 
02892    /* Transfer flags from the old channel. */
02893    new_chan->dialing = old_chan->dialing;
02894    new_chan->digital = old_chan->digital;
02895    new_chan->outgoing = old_chan->outgoing;
02896    old_chan->dialing = 0;
02897    old_chan->digital = 0;
02898    old_chan->outgoing = 0;
02899 
02900    /* More stuff to transfer to the new channel. */
02901    new_chan->law = old_chan->law;
02902    strcpy(new_chan->dialstring, old_chan->dialstring);
02903 }
02904 #endif   /* defined(HAVE_PRI) */
02905 
02906 #if defined(HAVE_PRI)
02907 static int sig_pri_tone_to_dahditone(enum sig_pri_tone tone)
02908 {
02909    switch (tone) {
02910    case SIG_PRI_TONE_RINGTONE:
02911       return DAHDI_TONE_RINGTONE;
02912    case SIG_PRI_TONE_STUTTER:
02913       return DAHDI_TONE_STUTTER;
02914    case SIG_PRI_TONE_CONGESTION:
02915       return DAHDI_TONE_CONGESTION;
02916    case SIG_PRI_TONE_DIALTONE:
02917       return DAHDI_TONE_DIALTONE;
02918    case SIG_PRI_TONE_DIALRECALL:
02919       return DAHDI_TONE_DIALRECALL;
02920    case SIG_PRI_TONE_INFO:
02921       return DAHDI_TONE_INFO;
02922    case SIG_PRI_TONE_BUSY:
02923       return DAHDI_TONE_BUSY;
02924    default:
02925       return -1;
02926    }
02927 }
02928 #endif   /* defined(HAVE_PRI) */
02929 
02930 #if defined(HAVE_PRI)
02931 static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
02932 {
02933    int x, res;
02934 
02935    res = ioctl(pri->fds[index], DAHDI_GETEVENT, &x);
02936    if (x) {
02937       ast_log(LOG_NOTICE, "PRI got event: %s (%d) on D-channel of span %d\n", event2str(x), x, pri->span);
02938    }
02939    /* Keep track of alarm state */
02940    switch (x) {
02941    case DAHDI_EVENT_ALARM:
02942       pri_event_alarm(pri, index, 0);
02943       break;
02944    case DAHDI_EVENT_NOALARM:
02945       pri_event_noalarm(pri, index, 0);
02946       break;
02947    default:
02948       break;
02949    }
02950 }
02951 #endif   /* defined(HAVE_PRI) */
02952 
02953 #if defined(HAVE_PRI)
02954 static int my_pri_play_tone(void *pvt, enum sig_pri_tone tone)
02955 {
02956    struct dahdi_pvt *p = pvt;
02957 
02958    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_pri_tone_to_dahditone(tone));
02959 }
02960 #endif   /* defined(HAVE_PRI) */
02961 
02962 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02963 /*!
02964  * \internal
02965  * \brief Set the caller id information.
02966  * \since 1.8
02967  *
02968  * \param pvt DAHDI private structure
02969  * \param caller Caller-id information to set.
02970  *
02971  * \return Nothing
02972  */
02973 static void my_set_callerid(void *pvt, const struct ast_party_caller *caller)
02974 {
02975    struct dahdi_pvt *p = pvt;
02976 
02977    ast_copy_string(p->cid_num,
02978       S_COR(caller->id.number.valid, caller->id.number.str, ""),
02979       sizeof(p->cid_num));
02980    ast_copy_string(p->cid_name,
02981       S_COR(caller->id.name.valid, caller->id.name.str, ""),
02982       sizeof(p->cid_name));
02983    ast_copy_string(p->cid_subaddr,
02984       S_COR(caller->id.subaddress.valid, caller->id.subaddress.str, ""),
02985       sizeof(p->cid_subaddr));
02986    p->cid_ton = caller->id.number.plan;
02987    p->callingpres = ast_party_id_presentation(&caller->id);
02988    if (caller->id.tag) {
02989       ast_copy_string(p->cid_tag, caller->id.tag, sizeof(p->cid_tag));
02990    }
02991    ast_copy_string(p->cid_ani,
02992       S_COR(caller->ani.number.valid, caller->ani.number.str, ""),
02993       sizeof(p->cid_ani));
02994    p->cid_ani2 = caller->ani2;
02995 }
02996 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
02997 
02998 #if defined(HAVE_PRI) || defined(HAVE_SS7)
02999 /*!
03000  * \internal
03001  * \brief Set the Dialed Number Identifier.
03002  * \since 1.8
03003  *
03004  * \param pvt DAHDI private structure
03005  * \param dnid Dialed Number Identifier string.
03006  *
03007  * \return Nothing
03008  */
03009 static void my_set_dnid(void *pvt, const char *dnid)
03010 {
03011    struct dahdi_pvt *p = pvt;
03012 
03013    ast_copy_string(p->dnid, dnid, sizeof(p->dnid));
03014 }
03015 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
03016 
03017 #if defined(HAVE_PRI)
03018 /*!
03019  * \internal
03020  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
03021  * \since 1.8
03022  *
03023  * \param pvt DAHDI private structure
03024  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
03025  *
03026  * \return Nothing
03027  */
03028 static void my_set_rdnis(void *pvt, const char *rdnis)
03029 {
03030    struct dahdi_pvt *p = pvt;
03031 
03032    ast_copy_string(p->rdnis, rdnis, sizeof(p->rdnis));
03033 }
03034 #endif   /* defined(HAVE_PRI) */
03035 
03036 #if defined(HAVE_PRI)
03037 /*!
03038  * \internal
03039  * \brief Make a dialstring for native ISDN CC to recall properly.
03040  * \since 1.8
03041  *
03042  * \param priv Channel private control structure.
03043  * \param buf Where to put the modified dialstring.
03044  * \param buf_size Size of modified dialstring buffer.
03045  *
03046  * \details
03047  * original dialstring:
03048  * DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03049  *
03050  * The modified dialstring will have prefixed the channel-group section
03051  * with the ISDN channel restriction.
03052  *
03053  * buf:
03054  * DAHDI/i<span>-(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
03055  *
03056  * The routine will check to see if the ISDN channel restriction is already
03057  * in the original dialstring.
03058  *
03059  * \return Nothing
03060  */
03061 static void my_pri_make_cc_dialstring(void *priv, char *buf, size_t buf_size)
03062 {
03063    char *dial;
03064    struct dahdi_pvt *pvt;
03065    AST_DECLARE_APP_ARGS(args,
03066       AST_APP_ARG(tech);   /* channel technology token */
03067       AST_APP_ARG(group);  /* channel/group token */
03068       //AST_APP_ARG(ext);  /* extension token */
03069       //AST_APP_ARG(opts); /* options token */
03070       //AST_APP_ARG(other);   /* Any remining unused arguments */
03071    );
03072 
03073    pvt = priv;
03074    dial = ast_strdupa(pvt->dialstring);
03075    AST_NONSTANDARD_APP_ARGS(args, dial, '/');
03076    if (!args.tech) {
03077       ast_copy_string(buf, pvt->dialstring, buf_size);
03078       return;
03079    }
03080    if (!args.group) {
03081       /* Append the ISDN span channel restriction to the dialstring. */
03082       snprintf(buf, buf_size, "%s/i%d-", args.tech, pvt->pri->span);
03083       return;
03084    }
03085    if (isdigit(args.group[0]) || args.group[0] == 'i' || strchr(args.group, '!')) {
03086       /* The ISDN span channel restriction is not needed or already
03087        * in the dialstring. */
03088       ast_copy_string(buf, pvt->dialstring, buf_size);
03089       return;
03090    }
03091    /* Insert the ISDN span channel restriction into the dialstring. */
03092    snprintf(buf, buf_size, "%s/i%d-%s", args.tech, pvt->pri->span, args.group);
03093 }
03094 #endif   /* defined(HAVE_PRI) */
03095 
03096 #if defined(HAVE_PRI)
03097 /*!
03098  * \internal
03099  * \brief Reevaluate the PRI span device state.
03100  * \since 1.8
03101  *
03102  * \param pri Asterisk D channel control structure.
03103  *
03104  * \return Nothing
03105  *
03106  * \note Assumes the pri->lock is already obtained.
03107  */
03108 static void dahdi_pri_update_span_devstate(struct sig_pri_span *pri)
03109 {
03110    unsigned idx;
03111    unsigned num_b_chans;   /* Number of B channels provisioned on the span. */
03112    unsigned in_use;     /* Number of B channels in use on the span. */
03113    unsigned in_alarm;      /* TRUE if the span is in alarm condition. */
03114    enum ast_device_state new_state;
03115 
03116    /* Count the number of B channels and the number of B channels in use. */
03117    num_b_chans = 0;
03118    in_use = 0;
03119    in_alarm = 1;
03120    for (idx = pri->numchans; idx--;) {
03121       if (pri->pvts[idx] && !pri->pvts[idx]->no_b_channel) {
03122          /* This is a B channel interface. */
03123          ++num_b_chans;
03124          if (pri->pvts[idx]->owner
03125 #if defined(HAVE_PRI_SERVICE_MESSAGES)
03126             /* Out-of-service B channels are "in-use". */
03127             || pri->pvts[idx]->service_status
03128 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
03129             ) {
03130             ++in_use;
03131          }
03132          if (!pri->pvts[idx]->inalarm) {
03133             /* There is a channel that is not in alarm. */
03134             in_alarm = 0;
03135          }
03136       }
03137    }
03138 
03139    /* Update the span congestion device state and report any change. */
03140    if (in_alarm) {
03141       new_state = AST_DEVICE_UNAVAILABLE;
03142    } else {
03143       new_state = num_b_chans == in_use ? AST_DEVICE_BUSY : AST_DEVICE_NOT_INUSE;
03144    }
03145    if (pri->congestion_devstate != new_state) {
03146       pri->congestion_devstate = new_state;
03147       ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/congestion", pri->span);
03148    }
03149 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
03150    /* Update the span threshold device state and report any change. */
03151    if (in_alarm) {
03152       new_state = AST_DEVICE_UNAVAILABLE;
03153    } else if (!in_use) {
03154       new_state = AST_DEVICE_NOT_INUSE;
03155    } else if (!pri->user_busy_threshold) {
03156       new_state = in_use < num_b_chans ? AST_DEVICE_INUSE : AST_DEVICE_BUSY;
03157    } else {
03158       new_state = in_use < pri->user_busy_threshold ? AST_DEVICE_INUSE
03159          : AST_DEVICE_BUSY;
03160    }
03161    if (pri->threshold_devstate != new_state) {
03162       pri->threshold_devstate = new_state;
03163       ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/threshold", pri->span);
03164    }
03165 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
03166 }
03167 #endif   /* defined(HAVE_PRI) */
03168 
03169 #if defined(HAVE_PRI)
03170 /*!
03171  * \internal
03172  * \brief Reference this module.
03173  * \since 1.8
03174  *
03175  * \return Nothing
03176  */
03177 static void my_module_ref(void)
03178 {
03179    ast_module_ref(ast_module_info->self);
03180 }
03181 #endif   /* defined(HAVE_PRI) */
03182 
03183 #if defined(HAVE_PRI)
03184 /*!
03185  * \internal
03186  * \brief Unreference this module.
03187  * \since 1.8
03188  *
03189  * \return Nothing
03190  */
03191 static void my_module_unref(void)
03192 {
03193    ast_module_unref(ast_module_info->self);
03194 }
03195 #endif   /* defined(HAVE_PRI) */
03196 
03197 #if defined(HAVE_PRI)
03198 #if defined(HAVE_PRI_CALL_WAITING)
03199 static void my_pri_init_config(void *priv, struct sig_pri_span *pri);
03200 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03201 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri);
03202 
03203 static struct sig_pri_callback dahdi_pri_callbacks =
03204 {
03205    .handle_dchan_exception = my_handle_dchan_exception,
03206    .play_tone = my_pri_play_tone,
03207    .set_echocanceller = my_set_echocanceller,
03208    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03209    .lock_private = my_lock_private,
03210    .unlock_private = my_unlock_private,
03211    .new_ast_channel = my_new_pri_ast_channel,
03212    .fixup_chans = my_pri_fixup_chans,
03213    .set_alarm = my_set_alarm,
03214    .set_dialing = my_set_dialing,
03215    .set_digital = my_set_digital,
03216    .set_callerid = my_set_callerid,
03217    .set_dnid = my_set_dnid,
03218    .set_rdnis = my_set_rdnis,
03219    .new_nobch_intf = dahdi_new_pri_nobch_channel,
03220 #if defined(HAVE_PRI_CALL_WAITING)
03221    .init_config = my_pri_init_config,
03222 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
03223    .get_orig_dialstring = my_get_orig_dialstring,
03224    .make_cc_dialstring = my_pri_make_cc_dialstring,
03225    .update_span_devstate = dahdi_pri_update_span_devstate,
03226    .module_ref = my_module_ref,
03227    .module_unref = my_module_unref,
03228    .open_media = my_pri_open_media,
03229 };
03230 #endif   /* defined(HAVE_PRI) */
03231 
03232 #if defined(HAVE_SS7)
03233 /*!
03234  * \internal
03235  * \brief Handle the SS7 link exception.
03236  * \since 1.8
03237  *
03238  * \param linkset Controlling linkset for the channel.
03239  * \param which Link index of the signaling channel.
03240  *
03241  * \return Nothing
03242  */
03243 static void my_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
03244 {
03245    int event;
03246 
03247    if (ioctl(linkset->fds[which], DAHDI_GETEVENT, &event)) {
03248       ast_log(LOG_ERROR, "SS7: Error in exception retrieval on span %d/%d!\n",
03249          linkset->span, which);
03250       return;
03251    }
03252    switch (event) {
03253    case DAHDI_EVENT_NONE:
03254       break;
03255    case DAHDI_EVENT_ALARM:
03256       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03257          event2str(event), event, linkset->span, which);
03258       sig_ss7_link_alarm(linkset, which);
03259       break;
03260    case DAHDI_EVENT_NOALARM:
03261       ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
03262          event2str(event), event, linkset->span, which);
03263       sig_ss7_link_noalarm(linkset, which);
03264       break;
03265    default:
03266       ast_log(LOG_NOTICE, "SS7 got event: %s(%d) on span %d/%d\n",
03267          event2str(event), event, linkset->span, which);
03268       break;
03269    }
03270 }
03271 #endif   /* defined(HAVE_SS7) */
03272 
03273 #if defined(HAVE_SS7)
03274 static void my_ss7_set_loopback(void *pvt, int enable)
03275 {
03276    struct dahdi_pvt *p = pvt;
03277 
03278    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
03279       ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel,
03280          strerror(errno));
03281    }
03282 }
03283 #endif   /* defined(HAVE_SS7) */
03284 
03285 #if defined(HAVE_SS7)
03286 /*!
03287  * \internal
03288  * \brief Create a new asterisk channel structure for SS7.
03289  * \since 1.8
03290  *
03291  * \param pvt Private channel structure.
03292  * \param state Initial state of new channel.
03293  * \param law Combanding law to use.
03294  * \param exten Dialplan extension for incoming call.
03295  * \param requestor Channel requesting this new channel.
03296  *
03297  * \retval ast_channel on success.
03298  * \retval NULL on error.
03299  */
03300 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)
03301 {
03302    struct dahdi_pvt *p = pvt;
03303    int audio;
03304    int newlaw;
03305 
03306    /* Set to audio mode at this point */
03307    audio = 1;
03308    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1)
03309       ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
03310          p->channel, audio, strerror(errno));
03311 
03312    if (law != SIG_SS7_DEFLAW) {
03313       dahdi_setlaw(p->subs[SUB_REAL].dfd,
03314          (law == SIG_SS7_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
03315    }
03316 
03317    ast_copy_string(p->exten, exten, sizeof(p->exten));
03318 
03319    newlaw = -1;
03320    switch (law) {
03321    case SIG_SS7_DEFLAW:
03322       newlaw = 0;
03323       break;
03324    case SIG_SS7_ALAW:
03325       newlaw = DAHDI_LAW_ALAW;
03326       break;
03327    case SIG_SS7_ULAW:
03328       newlaw = DAHDI_LAW_MULAW;
03329       break;
03330    }
03331    return dahdi_new(p, state, 0, SUB_REAL, newlaw, requestor ? requestor->linkedid : "");
03332 }
03333 #endif   /* defined(HAVE_SS7) */
03334 
03335 #if defined(HAVE_SS7)
03336 static int sig_ss7_tone_to_dahditone(enum sig_ss7_tone tone)
03337 {
03338    switch (tone) {
03339    case SIG_SS7_TONE_RINGTONE:
03340       return DAHDI_TONE_RINGTONE;
03341    case SIG_SS7_TONE_STUTTER:
03342       return DAHDI_TONE_STUTTER;
03343    case SIG_SS7_TONE_CONGESTION:
03344       return DAHDI_TONE_CONGESTION;
03345    case SIG_SS7_TONE_DIALTONE:
03346       return DAHDI_TONE_DIALTONE;
03347    case SIG_SS7_TONE_DIALRECALL:
03348       return DAHDI_TONE_DIALRECALL;
03349    case SIG_SS7_TONE_INFO:
03350       return DAHDI_TONE_INFO;
03351    case SIG_SS7_TONE_BUSY:
03352       return DAHDI_TONE_BUSY;
03353    default:
03354       return -1;
03355    }
03356 }
03357 #endif   /* defined(HAVE_SS7) */
03358 
03359 #if defined(HAVE_SS7)
03360 static int my_ss7_play_tone(void *pvt, enum sig_ss7_tone tone)
03361 {
03362    struct dahdi_pvt *p = pvt;
03363 
03364    return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_ss7_tone_to_dahditone(tone));
03365 }
03366 #endif   /* defined(HAVE_SS7) */
03367 
03368 #if defined(HAVE_SS7)
03369 static struct sig_ss7_callback dahdi_ss7_callbacks =
03370 {
03371    .lock_private = my_lock_private,
03372    .unlock_private = my_unlock_private,
03373 
03374    .set_echocanceller = my_set_echocanceller,
03375    .set_loopback = my_ss7_set_loopback,
03376 
03377    .new_ast_channel = my_new_ss7_ast_channel,
03378    .play_tone = my_ss7_play_tone,
03379 
03380    .handle_link_exception = my_handle_link_exception,
03381    .set_alarm = my_set_alarm,
03382    .set_dialing = my_set_dialing,
03383    .set_digital = my_set_digital,
03384    .set_inservice = my_set_inservice,
03385    .set_locallyblocked = my_set_locallyblocked,
03386    .set_remotelyblocked = my_set_remotelyblocked,
03387    .set_callerid = my_set_callerid,
03388    .set_dnid = my_set_dnid,
03389 };
03390 #endif   /* defined(HAVE_SS7) */
03391 
03392 /*!
03393  * \brief Send MWI state change
03394  *
03395  * \arg mailbox_full This is the mailbox associated with the FXO line that the
03396  *      MWI state has changed on.
03397  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
03398  *      whether there are messages waiting or not.
03399  *
03400  *  \return nothing
03401  *
03402  * This function does two things:
03403  *
03404  * 1) It generates an internal Asterisk event notifying any other module that
03405  *    cares about MWI that the state of a mailbox has changed.
03406  *
03407  * 2) It runs the script specified by the mwimonitornotify option to allow
03408  *    some custom handling of the state change.
03409  */
03410 static void notify_message(char *mailbox_full, int thereornot)
03411 {
03412    char s[sizeof(mwimonitornotify) + 80];
03413    struct ast_event *event;
03414    char *mailbox, *context;
03415 
03416    /* Strip off @default */
03417    context = mailbox = ast_strdupa(mailbox_full);
03418    strsep(&context, "@");
03419    if (ast_strlen_zero(context))
03420       context = "default";
03421 
03422    if (!(event = ast_event_new(AST_EVENT_MWI,
03423          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
03424          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
03425          AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03426          AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
03427          AST_EVENT_IE_END))) {
03428       return;
03429    }
03430 
03431    ast_event_queue_and_cache(event);
03432 
03433    if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
03434       snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
03435       ast_safe_system(s);
03436    }
03437 }
03438 
03439 static void my_handle_notify_message(struct ast_channel *chan, void *pvt, int cid_flags, int neon_mwievent)
03440 {
03441    struct dahdi_pvt *p = pvt;
03442 
03443    if (neon_mwievent > -1 && !p->mwimonitor_neon)
03444       return;
03445 
03446    if (neon_mwievent == ANALOG_EVENT_NEONMWI_ACTIVE || cid_flags & CID_MSGWAITING) {
03447       ast_log(LOG_NOTICE, "MWI: Channel %d message waiting, mailbox %s\n", p->channel, p->mailbox);
03448       notify_message(p->mailbox, 1);
03449    } else if (neon_mwievent == ANALOG_EVENT_NEONMWI_INACTIVE || cid_flags & CID_NOMSGWAITING) {
03450       ast_log(LOG_NOTICE, "MWI: Channel %d no message waiting, mailbox %s\n", p->channel, p->mailbox);
03451       notify_message(p->mailbox, 0);
03452    }
03453    /* If the CID had Message waiting payload, assume that this for MWI only and hangup the call */
03454    /* If generated using Ring Pulse Alert, then ring has been answered as a call and needs to be hungup */
03455    if (neon_mwievent == -1 && p->mwimonitor_rpas) {
03456       ast_hangup(chan);
03457       return;
03458    }
03459 }
03460 
03461 
03462 
03463 static struct analog_callback dahdi_analog_callbacks =
03464 {
03465    .play_tone = my_play_tone,
03466    .get_event = my_get_event,
03467    .wait_event = my_wait_event,
03468    .is_off_hook = my_is_off_hook,
03469    .set_echocanceller = my_set_echocanceller,
03470    .ring = my_ring,
03471    .flash = my_flash,
03472    .off_hook = my_off_hook,
03473    .dial_digits = my_dial_digits,
03474    .train_echocanceller = my_train_echocanceller,
03475    .on_hook = my_on_hook,
03476    .is_dialing = my_is_dialing,
03477    .allocate_sub = my_allocate_sub,
03478    .unallocate_sub = my_unallocate_sub,
03479    .swap_subs = my_swap_subchannels,
03480    .has_voicemail = my_has_voicemail,
03481    .check_for_conference = my_check_for_conference,
03482    .conf_add = my_conf_add,
03483    .conf_del = my_conf_del,
03484    .complete_conference_update = my_complete_conference_update,
03485    .start = my_start,
03486    .all_subchannels_hungup = my_all_subchannels_hungup,
03487    .lock_private = my_lock_private,
03488    .unlock_private = my_unlock_private,
03489    .deadlock_avoidance_private = my_deadlock_avoidance_private,
03490    .handle_dtmfup = my_handle_dtmfup,
03491    .wink = my_wink,
03492    .new_ast_channel = my_new_analog_ast_channel,
03493    .dsp_set_digitmode = my_dsp_set_digitmode,
03494    .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
03495    .send_callerid = my_send_callerid,
03496    .callwait = my_callwait,
03497    .stop_callwait = my_stop_callwait,
03498    .get_callerid = my_get_callerid,
03499    .start_cid_detect = my_start_cid_detect,
03500    .stop_cid_detect = my_stop_cid_detect,
03501    .handle_notify_message = my_handle_notify_message,
03502    .increase_ss_count = my_increase_ss_count,
03503    .decrease_ss_count = my_decrease_ss_count,
03504    .distinctive_ring = my_distinctive_ring,
03505    .set_linear_mode = my_set_linear_mode,
03506    .get_and_handle_alarms = my_get_and_handle_alarms,
03507    .get_sigpvt_bridged_channel = my_get_sigpvt_bridged_channel,
03508    .get_sub_fd = my_get_sub_fd,
03509    .set_cadence = my_set_cadence,
03510    .set_alarm = my_set_alarm,
03511    .set_dialing = my_set_dialing,
03512    .set_ringtimeout = my_set_ringtimeout,
03513    .set_waitingfordt = my_set_waitingfordt,
03514    .check_waitingfordt = my_check_waitingfordt,
03515    .set_confirmanswer = my_set_confirmanswer,
03516    .check_confirmanswer = my_check_confirmanswer,
03517    .cancel_cidspill = my_cancel_cidspill,
03518    .confmute = my_confmute,
03519    .set_pulsedial = my_set_pulsedial,
03520    .get_orig_dialstring = my_get_orig_dialstring,
03521    .set_needringing = my_set_needringing,
03522    .set_polarity = my_set_polarity,
03523    .start_polarityswitch = my_start_polarityswitch,
03524    .answer_polarityswitch = my_answer_polarityswitch,
03525    .hangup_polarityswitch = my_hangup_polarityswitch,
03526 };
03527 
03528 /*! Round robin search locations. */
03529 static struct dahdi_pvt *round_robin[32];
03530 
03531 static int dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok)
03532 {
03533    int res;
03534    if (p->subs[SUB_REAL].owner == ast)
03535       res = 0;
03536    else if (p->subs[SUB_CALLWAIT].owner == ast)
03537       res = 1;
03538    else if (p->subs[SUB_THREEWAY].owner == ast)
03539       res = 2;
03540    else {
03541       res = -1;
03542       if (!nullok)
03543          ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
03544    }
03545    return res;
03546 }
03547 
03548 /*!
03549  * \internal
03550  * \brief Obtain the specified subchannel owner lock if the owner exists.
03551  *
03552  * \param pvt Channel private struct.
03553  * \param sub_idx Subchannel owner to lock.
03554  *
03555  * \note Assumes the pvt->lock is already obtained.
03556  *
03557  * \note
03558  * Because deadlock avoidance may have been necessary, you need to confirm
03559  * the state of things before continuing.
03560  *
03561  * \return Nothing
03562  */
03563 static void dahdi_lock_sub_owner(struct dahdi_pvt *pvt, int sub_idx)
03564 {
03565    for (;;) {
03566       if (!pvt->subs[sub_idx].owner) {
03567          /* No subchannel owner pointer */
03568          break;
03569       }
03570       if (!ast_channel_trylock(pvt->subs[sub_idx].owner)) {
03571          /* Got subchannel owner lock */
03572          break;
03573       }
03574       /* We must unlock the private to avoid the possibility of a deadlock */
03575       DEADLOCK_AVOIDANCE(&pvt->lock);
03576    }
03577 }
03578 
03579 static void wakeup_sub(struct dahdi_pvt *p, int a)
03580 {
03581    dahdi_lock_sub_owner(p, a);
03582    if (p->subs[a].owner) {
03583       ast_queue_frame(p->subs[a].owner, &ast_null_frame);
03584       ast_channel_unlock(p->subs[a].owner);
03585    }
03586 }
03587 
03588 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f)
03589 {
03590    for (;;) {
03591       if (p->owner) {
03592          if (ast_channel_trylock(p->owner)) {
03593             DEADLOCK_AVOIDANCE(&p->lock);
03594          } else {
03595             ast_queue_frame(p->owner, f);
03596             ast_channel_unlock(p->owner);
03597             break;
03598          }
03599       } else
03600          break;
03601    }
03602 }
03603 
03604 static void handle_clear_alarms(struct dahdi_pvt *p)
03605 {
03606    if (report_alarms & REPORT_CHANNEL_ALARMS) {
03607       ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
03608       manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
03609    }
03610    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
03611       ast_log(LOG_NOTICE, "Alarm cleared on span %d\n", p->span);
03612       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarmClear", "Span: %d\r\n", p->span);
03613    }
03614 }
03615 
03616 #ifdef HAVE_OPENR2
03617 
03618 static int dahdi_r2_answer(struct dahdi_pvt *p)
03619 {
03620    int res = 0;
03621    /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
03622    * and does not has support for openr2_chan_answer_call_with_mode
03623    *  */
03624 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
03625    const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
03626    int wants_double_answer = ast_true(double_answer) ? 1 : 0;
03627    if (!double_answer) {
03628       /* this still can result in double answer if the channel context
03629       * was configured that way */
03630       res = openr2_chan_answer_call(p->r2chan);
03631    } else if (wants_double_answer) {
03632       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
03633    } else {
03634       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
03635    }
03636 #else
03637    res = openr2_chan_answer_call(p->r2chan);
03638 #endif
03639    return res;
03640 }
03641 
03642 
03643 
03644 /* should be called with the ast_channel locked */
03645 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
03646 {
03647    openr2_calling_party_category_t cat;
03648    const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
03649    struct dahdi_pvt *p = c->tech_pvt;
03650    if (ast_strlen_zero(catstr)) {
03651       ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
03652             c->name, openr2_proto_get_category_string(p->mfcr2_category));
03653       return p->mfcr2_category;
03654    }
03655    if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
03656       ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
03657             catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
03658       return p->mfcr2_category;
03659    }
03660    ast_debug(1, "Using category %s\n", catstr);
03661    return cat;
03662 }
03663 
03664 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
03665 {
03666    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03667    ast_mutex_lock(&p->lock);
03668    if (p->mfcr2call) {
03669       ast_mutex_unlock(&p->lock);
03670       /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
03671          interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
03672          can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
03673          the other end will see our seize as a forced release and drop the call, we will see an invalid
03674          pattern that will be seen and treated as protocol error. */
03675       ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
03676       return;
03677    }
03678    p->mfcr2call = 1;
03679    /* better safe than sorry ... */
03680    p->cid_name[0] = '\0';
03681    p->cid_num[0] = '\0';
03682    p->cid_subaddr[0] = '\0';
03683    p->rdnis[0] = '\0';
03684    p->exten[0] = '\0';
03685    p->mfcr2_ani_index = '\0';
03686    p->mfcr2_dnis_index = '\0';
03687    p->mfcr2_dnis_matched = 0;
03688    p->mfcr2_answer_pending = 0;
03689    p->mfcr2_call_accepted = 0;
03690    ast_mutex_unlock(&p->lock);
03691    ast_verbose("New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
03692 }
03693 
03694 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
03695 {
03696    int res;
03697    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03698    ast_mutex_lock(&p->lock);
03699    p->inalarm = alarm ? 1 : 0;
03700    if (p->inalarm) {
03701       res = get_alarms(p);
03702       handle_alarms(p, res);
03703    } else {
03704       handle_clear_alarms(p);
03705    }
03706    ast_mutex_unlock(&p->lock);
03707 }
03708 
03709 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
03710 {
03711    ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
03712 }
03713 
03714 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
03715 {
03716    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03717    ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
03718    if (p->owner) {
03719       p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
03720       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03721    }
03722    ast_mutex_lock(&p->lock);
03723    p->mfcr2call = 0;
03724    ast_mutex_unlock(&p->lock);
03725 }
03726 
03727 static void dahdi_r2_disconnect_call(struct dahdi_pvt *p, openr2_call_disconnect_cause_t cause)
03728 {
03729    if (openr2_chan_disconnect_call(p->r2chan, cause)) {
03730       ast_log(LOG_NOTICE, "Bad! failed to disconnect call on channel %d with reason %s, hope for the best!\n",
03731          p->channel, openr2_proto_get_disconnect_string(cause));
03732       /* force the chan to idle and release the call flag now since we will not see a clean on_call_end */
03733       openr2_chan_set_idle(p->r2chan);
03734       ast_mutex_lock(&p->lock);
03735       p->mfcr2call = 0;
03736       ast_mutex_unlock(&p->lock);
03737    }
03738 }
03739 
03740 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
03741 {
03742    struct dahdi_pvt *p;
03743    struct ast_channel *c;
03744    ast_verbose("MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
03745          openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
03746          openr2_proto_get_category_string(category));
03747    p = openr2_chan_get_client_data(r2chan);
03748    /* if collect calls are not allowed and this is a collect call, reject it! */
03749    if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
03750       ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
03751       dahdi_r2_disconnect_call(p, OR2_CAUSE_COLLECT_CALL_REJECTED);
03752       return;
03753    }
03754    ast_mutex_lock(&p->lock);
03755    p->mfcr2_recvd_category = category;
03756    /* if we're not supposed to use CID, clear whatever we have */
03757    if (!p->use_callerid) {
03758       ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
03759       p->cid_num[0] = 0;
03760       p->cid_name[0] = 0;
03761    }
03762    /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
03763    if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
03764       ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
03765       p->exten[0] = 's';
03766       p->exten[1] = 0;
03767    }
03768    ast_mutex_unlock(&p->lock);
03769    if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
03770       ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
03771             p->channel, p->exten, p->context);
03772       dahdi_r2_disconnect_call(p, OR2_CAUSE_UNALLOCATED_NUMBER);
03773       return;
03774    }
03775    if (!p->mfcr2_accept_on_offer) {
03776       /* The user wants us to start the PBX thread right away without accepting the call first */
03777       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
03778       if (c) {
03779          /* Done here, don't disable reading now since we still need to generate MF tones to accept
03780             the call or reject it and detect the tone off condition of the other end, all of this
03781             will be done in the PBX thread now */
03782          return;
03783       }
03784       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
03785       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
03786    } else if (p->mfcr2_charge_calls) {
03787       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
03788       openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
03789    } else {
03790       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
03791       openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
03792    }
03793 }
03794 
03795 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
03796 {
03797    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03798    ast_verbose("MFC/R2 call end on channel %d\n", p->channel);
03799    ast_mutex_lock(&p->lock);
03800    p->mfcr2call = 0;
03801    ast_mutex_unlock(&p->lock);
03802 }
03803 
03804 static void dahdi_enable_ec(struct dahdi_pvt *p);
03805 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
03806 {
03807    struct dahdi_pvt *p = NULL;
03808    struct ast_channel *c = NULL;
03809    p = openr2_chan_get_client_data(r2chan);
03810    dahdi_enable_ec(p);
03811    p->mfcr2_call_accepted = 1;
03812    /* if it's an incoming call ... */
03813    if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
03814       ast_verbose("MFC/R2 call has been accepted on backward channel %d\n", openr2_chan_get_number(r2chan));
03815       /* If accept on offer is not set, it means at this point the PBX thread is already
03816          launched (was launched in the 'on call offered' handler) and therefore this callback
03817          is being executed already in the PBX thread rather than the monitor thread, don't launch
03818          any other thread, just disable the openr2 reading and answer the call if needed */
03819       if (!p->mfcr2_accept_on_offer) {
03820          openr2_chan_disable_read(r2chan);
03821          if (p->mfcr2_answer_pending) {
03822             ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
03823             dahdi_r2_answer(p);
03824          }
03825          return;
03826       }
03827       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, NULL);
03828       if (c) {
03829          /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
03830             library to forget about it */
03831          openr2_chan_disable_read(r2chan);
03832          return;
03833       }
03834       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
03835       /* failed to create the channel, bail out and report it as an out of order line */
03836       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
03837       return;
03838    }
03839    /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
03840    ast_verbose("MFC/R2 call has been accepted on forward channel %d\n", p->channel);
03841    p->subs[SUB_REAL].needringing = 1;
03842    p->dialing = 0;
03843    /* chan_dahdi will take care of reading from now on in the PBX thread, tell the library to forget about it */
03844    openr2_chan_disable_read(r2chan);
03845 }
03846 
03847 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
03848 {
03849    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03850    ast_verbose("MFC/R2 call has been answered on channel %d\n", openr2_chan_get_number(r2chan));
03851    p->subs[SUB_REAL].needanswer = 1;
03852 }
03853 
03854 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
03855 {
03856    /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
03857 }
03858 
03859 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
03860 {
03861    switch (cause) {
03862    case OR2_CAUSE_BUSY_NUMBER:
03863       return AST_CAUSE_BUSY;
03864    case OR2_CAUSE_NETWORK_CONGESTION:
03865       return AST_CAUSE_CONGESTION;
03866    case OR2_CAUSE_OUT_OF_ORDER:
03867       return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03868    case OR2_CAUSE_UNALLOCATED_NUMBER:
03869       return AST_CAUSE_UNREGISTERED;
03870    case OR2_CAUSE_NO_ANSWER:
03871       return AST_CAUSE_NO_ANSWER;
03872    case OR2_CAUSE_NORMAL_CLEARING:
03873       return AST_CAUSE_NORMAL_CLEARING;
03874    case OR2_CAUSE_UNSPECIFIED:
03875    default:
03876       return AST_CAUSE_NOTDEFINED;
03877    }
03878 }
03879 
03880 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
03881 {
03882    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03883    ast_verbose("MFC/R2 call disconnected on channel %d\n", openr2_chan_get_number(r2chan));
03884    ast_mutex_lock(&p->lock);
03885    if (!p->owner) {
03886       ast_mutex_unlock(&p->lock);
03887       /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
03888       dahdi_r2_disconnect_call(p, OR2_CAUSE_NORMAL_CLEARING);
03889       return;
03890    }
03891    /* when we have an owner we don't call dahdi_r2_disconnect_call here, that will
03892       be done in dahdi_hangup */
03893    if (p->owner->_state == AST_STATE_UP) {
03894       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03895       ast_mutex_unlock(&p->lock);
03896    } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
03897       /* being the forward side we must report what happened to the call to whoever requested it */
03898       switch (cause) {
03899       case OR2_CAUSE_BUSY_NUMBER:
03900          p->subs[SUB_REAL].needbusy = 1;
03901          break;
03902       case OR2_CAUSE_NETWORK_CONGESTION:
03903       case OR2_CAUSE_OUT_OF_ORDER:
03904       case OR2_CAUSE_UNALLOCATED_NUMBER:
03905       case OR2_CAUSE_NO_ANSWER:
03906       case OR2_CAUSE_UNSPECIFIED:
03907       case OR2_CAUSE_NORMAL_CLEARING:
03908          p->subs[SUB_REAL].needcongestion = 1;
03909          break;
03910       default:
03911          p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03912       }
03913       ast_mutex_unlock(&p->lock);
03914    } else {
03915       ast_mutex_unlock(&p->lock);
03916       /* being the backward side and not UP yet, we only need to request hangup */
03917       /* TODO: what about doing this same thing when were AST_STATE_UP? */
03918       ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
03919    }
03920 }
03921 
03922 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
03923 {
03924    switch (level) {
03925    case OR2_LOG_NOTICE:
03926       ast_verbose("%s", logmessage);
03927       break;
03928    case OR2_LOG_WARNING:
03929       ast_log(LOG_WARNING, "%s", logmessage);
03930       break;
03931    case OR2_LOG_ERROR:
03932       ast_log(LOG_ERROR, "%s", logmessage);
03933       break;
03934    case OR2_LOG_STACK_TRACE:
03935    case OR2_LOG_MF_TRACE:
03936    case OR2_LOG_CAS_TRACE:
03937    case OR2_LOG_DEBUG:
03938    case OR2_LOG_EX_DEBUG:
03939       ast_log(LOG_DEBUG, "%s", logmessage);
03940       break;
03941    default:
03942       ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
03943       ast_log(LOG_DEBUG, "%s", logmessage);
03944       break;
03945    }
03946 }
03947 
03948 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
03949 {
03950    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03951    ast_mutex_lock(&p->lock);
03952    p->remotelyblocked = 1;
03953    ast_mutex_unlock(&p->lock);
03954    ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
03955 }
03956 
03957 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
03958 {
03959    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03960    ast_mutex_lock(&p->lock);
03961    p->remotelyblocked = 0;
03962    ast_mutex_unlock(&p->lock);
03963    ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
03964 }
03965 
03966 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
03967    __attribute__((format (printf, 3, 0)));
03968 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
03969 {
03970 #define CONTEXT_TAG "Context - "
03971    char logmsg[256];
03972    char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
03973    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
03974    snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
03975    dahdi_r2_write_log(level, completemsg);
03976 #undef CONTEXT_TAG
03977 }
03978 
03979 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
03980    __attribute__((format (printf, 3, 0)));
03981 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
03982 {
03983 #define CHAN_TAG "Chan "
03984    char logmsg[256];
03985    char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
03986    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
03987    snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
03988    dahdi_r2_write_log(level, completemsg);
03989 }
03990 
03991 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
03992 {
03993    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
03994    /* if 'immediate' is set, let's stop requesting DNIS */
03995    if (p->immediate) {
03996       return 0;
03997    }
03998    p->exten[p->mfcr2_dnis_index] = digit;
03999    p->rdnis[p->mfcr2_dnis_index] = digit;
04000    p->mfcr2_dnis_index++;
04001    p->exten[p->mfcr2_dnis_index] = 0;
04002    p->rdnis[p->mfcr2_dnis_index] = 0;
04003    /* if the DNIS is a match and cannot match more, stop requesting DNIS */
04004    if ((p->mfcr2_dnis_matched ||
04005        (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
04006        !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
04007       return 0;
04008    }
04009    /* otherwise keep going */
04010    return 1;
04011 }
04012 
04013 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
04014 {
04015    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
04016    p->cid_num[p->mfcr2_ani_index] = digit;
04017    p->cid_name[p->mfcr2_ani_index] = digit;
04018    p->mfcr2_ani_index++;
04019    p->cid_num[p->mfcr2_ani_index] = 0;
04020    p->cid_name[p->mfcr2_ani_index] = 0;
04021 }
04022 
04023 static void dahdi_r2_on_billing_pulse_received(openr2_chan_t *r2chan)
04024 {
04025    ast_verbose("MFC/R2 billing pulse received on channel %d\n", openr2_chan_get_number(r2chan));
04026 }
04027 
04028 static openr2_event_interface_t dahdi_r2_event_iface = {
04029    .on_call_init = dahdi_r2_on_call_init,
04030    .on_call_offered = dahdi_r2_on_call_offered,
04031    .on_call_accepted = dahdi_r2_on_call_accepted,
04032    .on_call_answered = dahdi_r2_on_call_answered,
04033    .on_call_disconnect = dahdi_r2_on_call_disconnect,
04034    .on_call_end = dahdi_r2_on_call_end,
04035    .on_call_read = dahdi_r2_on_call_read,
04036    .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
04037    .on_os_error = dahdi_r2_on_os_error,
04038    .on_protocol_error = dahdi_r2_on_protocol_error,
04039    .on_line_blocked = dahdi_r2_on_line_blocked,
04040    .on_line_idle = dahdi_r2_on_line_idle,
04041    /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
04042    .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
04043    .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
04044    .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
04045    /* so far we do nothing with billing pulses */
04046    .on_billing_pulse_received = dahdi_r2_on_billing_pulse_received
04047 };
04048 
04049 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
04050 {
04051    return AST_ALAW(sample);
04052 }
04053 
04054 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
04055 {
04056    return AST_LIN2A(sample);
04057 }
04058 
04059 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
04060    dahdi_r2_alaw_to_linear,
04061    dahdi_r2_linear_to_alaw
04062 };
04063 
04064 #endif /* HAVE_OPENR2 */
04065 
04066 static void swap_subs(struct dahdi_pvt *p, int a, int b)
04067 {
04068    int tchan;
04069    int tinthreeway;
04070    struct ast_channel *towner;
04071 
04072    ast_debug(1, "Swapping %d and %d\n", a, b);
04073 
04074    tchan = p->subs[a].chan;
04075    towner = p->subs[a].owner;
04076    tinthreeway = p->subs[a].inthreeway;
04077 
04078    p->subs[a].chan = p->subs[b].chan;
04079    p->subs[a].owner = p->subs[b].owner;
04080    p->subs[a].inthreeway = p->subs[b].inthreeway;
04081 
04082    p->subs[b].chan = tchan;
04083    p->subs[b].owner = towner;
04084    p->subs[b].inthreeway = tinthreeway;
04085 
04086    if (p->subs[a].owner)
04087       ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
04088    if (p->subs[b].owner)
04089       ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
04090    wakeup_sub(p, a);
04091    wakeup_sub(p, b);
04092 }
04093 
04094 static int dahdi_open(char *fn)
04095 {
04096    int fd;
04097    int isnum;
04098    int chan = 0;
04099    int bs;
04100    int x;
04101    isnum = 1;
04102    for (x = 0; x < strlen(fn); x++) {
04103       if (!isdigit(fn[x])) {
04104          isnum = 0;
04105          break;
04106       }
04107    }
04108    if (isnum) {
04109       chan = atoi(fn);
04110       if (chan < 1) {
04111          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
04112          return -1;
04113       }
04114       fn = "/dev/dahdi/channel";
04115    }
04116    fd = open(fn, O_RDWR | O_NONBLOCK);
04117    if (fd < 0) {
04118       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
04119       return -1;
04120    }
04121    if (chan) {
04122       if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
04123          x = errno;
04124          close(fd);
04125          errno = x;
04126          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
04127          return -1;
04128       }
04129    }
04130    bs = READ_SIZE;
04131    if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
04132       ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
04133       x = errno;
04134       close(fd);
04135       errno = x;
04136       return -1;
04137    }
04138    return fd;
04139 }
04140 
04141 static void dahdi_close(int fd)
04142 {
04143    if (fd > 0)
04144       close(fd);
04145 }
04146 
04147 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
04148 {
04149    dahdi_close(chan_pvt->subs[sub_num].dfd);
04150    chan_pvt->subs[sub_num].dfd = -1;
04151 }
04152 
04153 #if defined(HAVE_PRI)
04154 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
04155 {
04156    dahdi_close(pri->pri.fds[fd_num]);
04157    pri->pri.fds[fd_num] = -1;
04158 }
04159 #endif   /* defined(HAVE_PRI) */
04160 
04161 #if defined(HAVE_SS7)
04162 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
04163 {
04164    dahdi_close(ss7->ss7.fds[fd_num]);
04165    ss7->ss7.fds[fd_num] = -1;
04166 }
04167 #endif   /* defined(HAVE_SS7) */
04168 
04169 static int dahdi_setlinear(int dfd, int linear)
04170 {
04171    return ioctl(dfd, DAHDI_SETLINEAR, &linear);
04172 }
04173 
04174 
04175 static int alloc_sub(struct dahdi_pvt *p, int x)
04176 {
04177    struct dahdi_bufferinfo bi;
04178    int res;
04179    if (p->subs[x].dfd >= 0) {
04180       ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
04181       return -1;
04182    }
04183 
04184    p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
04185    if (p->subs[x].dfd <= -1) {
04186       ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
04187       return -1;
04188    }
04189 
04190    res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
04191    if (!res) {
04192       bi.txbufpolicy = p->buf_policy;
04193       bi.rxbufpolicy = p->buf_policy;
04194       bi.numbufs = p->buf_no;
04195       res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
04196       if (res < 0) {
04197          ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
04198       }
04199    } else
04200       ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
04201 
04202    if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
04203       ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
04204       dahdi_close_sub(p, x);
04205       p->subs[x].dfd = -1;
04206       return -1;
04207    }
04208    ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
04209    return 0;
04210 }
04211 
04212 static int unalloc_sub(struct dahdi_pvt *p, int x)
04213 {
04214    if (!x) {
04215       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
04216       return -1;
04217    }
04218    ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
04219    dahdi_close_sub(p, x);
04220    p->subs[x].linear = 0;
04221    p->subs[x].chan = 0;
04222    p->subs[x].owner = NULL;
04223    p->subs[x].inthreeway = 0;
04224    p->polarity = POLARITY_IDLE;
04225    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
04226    return 0;
04227 }
04228 
04229 static int digit_to_dtmfindex(char digit)
04230 {
04231    if (isdigit(digit))
04232       return DAHDI_TONE_DTMF_BASE + (digit - '0');
04233    else if (digit >= 'A' && digit <= 'D')
04234       return DAHDI_TONE_DTMF_A + (digit - 'A');
04235    else if (digit >= 'a' && digit <= 'd')
04236       return DAHDI_TONE_DTMF_A + (digit - 'a');
04237    else if (digit == '*')
04238       return DAHDI_TONE_DTMF_s;
04239    else if (digit == '#')
04240       return DAHDI_TONE_DTMF_p;
04241    else
04242       return -1;
04243 }
04244 
04245 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
04246 {
04247    struct dahdi_pvt *pvt;
04248    int idx;
04249    int dtmf = -1;
04250    int res;
04251 
04252    pvt = chan->tech_pvt;
04253 
04254    ast_mutex_lock(&pvt->lock);
04255 
04256    idx = dahdi_get_index(chan, pvt, 0);
04257 
04258    if ((idx != SUB_REAL) || !pvt->owner)
04259       goto out;
04260 
04261 #ifdef HAVE_PRI
04262    switch (pvt->sig) {
04263    case SIG_PRI_LIB_HANDLE_CASES:
04264       res = sig_pri_digit_begin(pvt->sig_pvt, chan, digit);
04265       if (!res)
04266          goto out;
04267       break;
04268    default:
04269       break;
04270    }
04271 #endif
04272    if ((dtmf = digit_to_dtmfindex(digit)) == -1)
04273       goto out;
04274 
04275    if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
04276       struct dahdi_dialoperation zo = {
04277          .op = DAHDI_DIAL_OP_APPEND,
04278       };
04279 
04280       zo.dialstr[0] = 'T';
04281       zo.dialstr[1] = digit;
04282       zo.dialstr[2] = '\0';
04283       if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
04284          ast_log(LOG_WARNING, "Couldn't dial digit %c: %s\n", digit, strerror(errno));
04285       else
04286          pvt->dialing = 1;
04287    } else {
04288       ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
04289       pvt->dialing = 1;
04290       pvt->begindigit = digit;
04291    }
04292 
04293 out:
04294    ast_mutex_unlock(&pvt->lock);
04295 
04296    return 0;
04297 }
04298 
04299 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
04300 {
04301    struct dahdi_pvt *pvt;
04302    int res = 0;
04303    int idx;
04304    int x;
04305 
04306    pvt = chan->tech_pvt;
04307 
04308    ast_mutex_lock(&pvt->lock);
04309 
04310    idx = dahdi_get_index(chan, pvt, 0);
04311 
04312    if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
04313       goto out;
04314 
04315 #ifdef HAVE_PRI
04316    /* This means that the digit was already sent via PRI signalling */
04317    if (dahdi_sig_pri_lib_handles(pvt->sig) && !pvt->begindigit) {
04318       goto out;
04319    }
04320 #endif
04321 
04322    if (pvt->begindigit) {
04323       x = -1;
04324       ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
04325       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
04326       pvt->dialing = 0;
04327       pvt->begindigit = 0;
04328    }
04329 
04330 out:
04331    ast_mutex_unlock(&pvt->lock);
04332 
04333    return res;
04334 }
04335 
04336 static const char * const events[] = {
04337    "No event",
04338    "On hook",
04339    "Ring/Answered",
04340    "Wink/Flash",
04341    "Alarm",
04342    "No more alarm",
04343    "HDLC Abort",
04344    "HDLC Overrun",
04345    "HDLC Bad FCS",
04346    "Dial Complete",
04347    "Ringer On",
04348    "Ringer Off",
04349    "Hook Transition Complete",
04350    "Bits Changed",
04351    "Pulse Start",
04352    "Timer Expired",
04353    "Timer Ping",
04354    "Polarity Reversal",
04355    "Ring Begin",
04356 };
04357 
04358 static struct {
04359    int alarm;
04360    char *name;
04361 } alarms[] = {
04362    { DAHDI_ALARM_RED, "Red Alarm" },
04363    { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
04364    { DAHDI_ALARM_BLUE, "Blue Alarm" },
04365    { DAHDI_ALARM_RECOVER, "Recovering" },
04366    { DAHDI_ALARM_LOOPBACK, "Loopback" },
04367    { DAHDI_ALARM_NOTOPEN, "Not Open" },
04368    { DAHDI_ALARM_NONE, "None" },
04369 };
04370 
04371 static char *alarm2str(int alm)
04372 {
04373    int x;
04374    for (x = 0; x < ARRAY_LEN(alarms); x++) {
04375       if (alarms[x].alarm & alm)
04376          return alarms[x].name;
04377    }
04378    return alm ? "Unknown Alarm" : "No Alarm";
04379 }
04380 
04381 static const char *event2str(int event)
04382 {
04383    static char buf[256];
04384    if ((event < (ARRAY_LEN(events))) && (event > -1))
04385       return events[event];
04386    sprintf(buf, "Event %d", event); /* safe */
04387    return buf;
04388 }
04389 
04390 static char *dahdi_sig2str(int sig)
04391 {
04392    static char buf[256];
04393    switch (sig) {
04394    case SIG_EM:
04395       return "E & M Immediate";
04396    case SIG_EMWINK:
04397       return "E & M Wink";
04398    case SIG_EM_E1:
04399       return "E & M E1";
04400    case SIG_FEATD:
04401       return "Feature Group D (DTMF)";
04402    case SIG_FEATDMF:
04403       return "Feature Group D (MF)";
04404    case SIG_FEATDMF_TA:
04405       return "Feature Groud D (MF) Tandem Access";
04406    case SIG_FEATB:
04407       return "Feature Group B (MF)";
04408    case SIG_E911:
04409       return "E911 (MF)";
04410    case SIG_FGC_CAMA:
04411       return "FGC/CAMA (Dialpulse)";
04412    case SIG_FGC_CAMAMF:
04413       return "FGC/CAMA (MF)";
04414    case SIG_FXSLS:
04415       return "FXS Loopstart";
04416    case SIG_FXSGS:
04417       return "FXS Groundstart";
04418    case SIG_FXSKS:
04419       return "FXS Kewlstart";
04420    case SIG_FXOLS:
04421       return "FXO Loopstart";
04422    case SIG_FXOGS:
04423       return "FXO Groundstart";
04424    case SIG_FXOKS:
04425       return "FXO Kewlstart";
04426    case SIG_PRI:
04427       return "ISDN PRI";
04428    case SIG_BRI:
04429       return "ISDN BRI Point to Point";
04430    case SIG_BRI_PTMP:
04431       return "ISDN BRI Point to MultiPoint";
04432    case SIG_SS7:
04433       return "SS7";
04434    case SIG_MFCR2:
04435       return "MFC/R2";
04436    case SIG_SF:
04437       return "SF (Tone) Immediate";
04438    case SIG_SFWINK:
04439       return "SF (Tone) Wink";
04440    case SIG_SF_FEATD:
04441       return "SF (Tone) with Feature Group D (DTMF)";
04442    case SIG_SF_FEATDMF:
04443       return "SF (Tone) with Feature Group D (MF)";
04444    case SIG_SF_FEATB:
04445       return "SF (Tone) with Feature Group B (MF)";
04446    case 0:
04447       return "Pseudo";
04448    default:
04449       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
04450       return buf;
04451    }
04452 }
04453 
04454 #define sig2str dahdi_sig2str
04455 
04456 static int analog_lib_handles(int signalling, int radio, int oprmode)
04457 {
04458    switch (signalling) {
04459    case SIG_FXOLS:
04460    case SIG_FXOGS:
04461    case SIG_FXOKS:
04462    case SIG_FXSLS:
04463    case SIG_FXSGS:
04464    case SIG_FXSKS:
04465    case SIG_EMWINK:
04466    case SIG_EM:
04467    case SIG_EM_E1:
04468    case SIG_FEATD:
04469    case SIG_FEATDMF:
04470    case SIG_E911:
04471    case SIG_FGC_CAMA:
04472    case SIG_FGC_CAMAMF:
04473    case SIG_FEATB:
04474    case SIG_SFWINK:
04475    case SIG_SF:
04476    case SIG_SF_FEATD:
04477    case SIG_SF_FEATDMF:
04478    case SIG_FEATDMF_TA:
04479    case SIG_SF_FEATB:
04480       break;
04481    default:
04482       /* The rest of the function should cover the remainder of signalling types */
04483       return 0;
04484    }
04485 
04486    if (radio)
04487       return 0;
04488 
04489    if (oprmode)
04490       return 0;
04491 
04492    return 1;
04493 }
04494 
04495 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
04496 {
04497    /* If the conference already exists, and we're already in it
04498       don't bother doing anything */
04499    struct dahdi_confinfo zi;
04500 
04501    memset(&zi, 0, sizeof(zi));
04502    zi.chan = 0;
04503 
04504    if (slavechannel > 0) {
04505       /* If we have only one slave, do a digital mon */
04506       zi.confmode = DAHDI_CONF_DIGITALMON;
04507       zi.confno = slavechannel;
04508    } else {
04509       if (!idx) {
04510          /* Real-side and pseudo-side both participate in conference */
04511          zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
04512             DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
04513       } else
04514          zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
04515       zi.confno = p->confno;
04516    }
04517    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
04518       return 0;
04519    if (c->dfd < 0)
04520       return 0;
04521    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04522       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
04523       return -1;
04524    }
04525    if (slavechannel < 1) {
04526       p->confno = zi.confno;
04527    }
04528    c->curconf = zi;
04529    ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04530    return 0;
04531 }
04532 
04533 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
04534 {
04535    /* If they're listening to our channel, they're ours */
04536    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
04537       return 1;
04538    /* If they're a talker on our (allocated) conference, they're ours */
04539    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
04540       return 1;
04541    return 0;
04542 }
04543 
04544 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
04545 {
04546    struct dahdi_confinfo zi;
04547    if (/* Can't delete if there's no dfd */
04548       (c->dfd < 0) ||
04549       /* Don't delete from the conference if it's not our conference */
04550       !isourconf(p, c)
04551       /* Don't delete if we don't think it's conferenced at all (implied) */
04552       ) return 0;
04553    memset(&zi, 0, sizeof(zi));
04554    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
04555       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
04556       return -1;
04557    }
04558    ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
04559    memcpy(&c->curconf, &zi, sizeof(c->curconf));
04560    return 0;
04561 }
04562 
04563 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
04564 {
04565    int x;
04566    int useslavenative;
04567    struct dahdi_pvt *slave = NULL;
04568    /* Start out optimistic */
04569    useslavenative = 1;
04570    /* Update conference state in a stateless fashion */
04571    for (x = 0; x < 3; x++) {
04572       /* Any three-way calling makes slave native mode *definitely* out
04573          of the question */
04574       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
04575          useslavenative = 0;
04576    }
04577    /* If we don't have any 3-way calls, check to see if we have
04578       precisely one slave */
04579    if (useslavenative) {
04580       for (x = 0; x < MAX_SLAVES; x++) {
04581          if (p->slaves[x]) {
04582             if (slave) {
04583                /* Whoops already have a slave!  No
04584                   slave native and stop right away */
04585                slave = NULL;
04586                useslavenative = 0;
04587                break;
04588             } else {
04589                /* We have one slave so far */
04590                slave = p->slaves[x];
04591             }
04592          }
04593       }
04594    }
04595    /* If no slave, slave native definitely out */
04596    if (!slave)
04597       useslavenative = 0;
04598    else if (slave->law != p->law) {
04599       useslavenative = 0;
04600       slave = NULL;
04601    }
04602    if (out)
04603       *out = slave;
04604    return useslavenative;
04605 }
04606 
04607 static int reset_conf(struct dahdi_pvt *p)
04608 {
04609    p->confno = -1;
04610    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
04611    if (p->subs[SUB_REAL].dfd > -1) {
04612       struct dahdi_confinfo zi;
04613 
04614       memset(&zi, 0, sizeof(zi));
04615       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
04616          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
04617    }
04618    return 0;
04619 }
04620 
04621 static int update_conf(struct dahdi_pvt *p)
04622 {
04623    int needconf = 0;
04624    int x;
04625    int useslavenative;
04626    struct dahdi_pvt *slave = NULL;
04627 
04628    useslavenative = isslavenative(p, &slave);
04629    /* Start with the obvious, general stuff */
04630    for (x = 0; x < 3; x++) {
04631       /* Look for three way calls */
04632       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
04633          conf_add(p, &p->subs[x], x, 0);
04634          needconf++;
04635       } else {
04636          conf_del(p, &p->subs[x], x);
04637       }
04638    }
04639    /* If we have a slave, add him to our conference now. or DAX
04640       if this is slave native */
04641    for (x = 0; x < MAX_SLAVES; x++) {
04642       if (p->slaves[x]) {
04643          if (useslavenative)
04644             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
04645          else {
04646             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
04647             needconf++;
04648          }
04649       }
04650    }
04651    /* If we're supposed to be in there, do so now */
04652    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
04653       if (useslavenative)
04654          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
04655       else {
04656          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
04657          needconf++;
04658       }
04659    }
04660    /* If we have a master, add ourselves to his conference */
04661    if (p->master) {
04662       if (isslavenative(p->master, NULL)) {
04663          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
04664       } else {
04665          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
04666       }
04667    }
04668    if (!needconf) {
04669       /* Nobody is left (or should be left) in our conference.
04670          Kill it. */
04671       p->confno = -1;
04672    }
04673    ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
04674    return 0;
04675 }
04676 
04677 static void dahdi_enable_ec(struct dahdi_pvt *p)
04678 {
04679    int res;
04680    if (!p)
04681       return;
04682    if (p->echocanon) {
04683       ast_debug(1, "Echo cancellation already on\n");
04684       return;
04685    }
04686    if (p->digital) {
04687       ast_debug(1, "Echo cancellation isn't required on digital connection\n");
04688       return;
04689    }
04690    if (p->echocancel.head.tap_length) {
04691 #if defined(HAVE_PRI) || defined(HAVE_SS7)
04692       switch (p->sig) {
04693 #if defined(HAVE_PRI)
04694       case SIG_PRI_LIB_HANDLE_CASES:
04695          if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
04696             /*
04697              * PRI nobch pseudo channel.  Does not need ec anyway.
04698              * Does not handle ioctl(DAHDI_AUDIOMODE)
04699              */
04700             return;
04701          }
04702          /* Fall through */
04703 #endif   /* defined(HAVE_PRI) */
04704 #if defined(HAVE_SS7)
04705       case SIG_SS7:
04706 #endif   /* defined(HAVE_SS7) */
04707          {
04708             int x = 1;
04709 
04710             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
04711             if (res)
04712                ast_log(LOG_WARNING,
04713                   "Unable to enable audio mode on channel %d (%s)\n",
04714                   p->channel, strerror(errno));
04715          }
04716          break;
04717       default:
04718          break;
04719       }
04720 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
04721       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
04722       if (res) {
04723          ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
04724       } else {
04725          p->echocanon = 1;
04726          ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
04727       }
04728    } else
04729       ast_debug(1, "No echo cancellation requested\n");
04730 }
04731 
04732 static void dahdi_train_ec(struct dahdi_pvt *p)
04733 {
04734    int x;
04735    int res;
04736 
04737    if (p && p->echocanon && p->echotraining) {
04738       x = p->echotraining;
04739       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
04740       if (res)
04741          ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
04742       else
04743          ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
04744    } else {
04745       ast_debug(1, "No echo training requested\n");
04746    }
04747 }
04748 
04749 static void dahdi_disable_ec(struct dahdi_pvt *p)
04750 {
04751    int res;
04752 
04753    if (p->echocanon) {
04754       struct dahdi_echocanparams ecp = { .tap_length = 0 };
04755 
04756       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
04757 
04758       if (res)
04759          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
04760       else
04761          ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
04762    }
04763 
04764    p->echocanon = 0;
04765 }
04766 
04767 /* perform a dynamic range compression transform on the given sample */
04768 static int drc_sample(int sample, float drc)
04769 {
04770    float neg;
04771    float shallow, steep;
04772    float max = SHRT_MAX;
04773    
04774    neg = (sample < 0 ? -1 : 1);
04775    steep = drc*sample;
04776    shallow = neg*(max-max/drc)+(float)sample/drc;
04777    if (abs(steep) < abs(shallow)) {
04778       sample = steep;
04779    }
04780    else {
04781       sample = shallow;
04782    }
04783 
04784    return sample;
04785 }
04786 
04787 
04788 static void fill_txgain(struct dahdi_gains *g, float gain, float drc, int law)
04789 {
04790    int j;
04791    int k;
04792 
04793    float linear_gain = pow(10.0, gain / 20.0);
04794 
04795    switch (law) {
04796    case DAHDI_LAW_ALAW:
04797       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
04798          if (gain || drc) {
04799             k = AST_ALAW(j);
04800             if (drc) {
04801                k = drc_sample(k, drc);
04802             }
04803             k = (float)k*linear_gain;
04804             if (k > 32767) k = 32767;
04805             if (k < -32767) k = -32767;
04806             g->txgain[j] = AST_LIN2A(k);
04807          } else {
04808             g->txgain[j] = j;
04809          }
04810       }
04811       break;
04812    case DAHDI_LAW_MULAW:
04813       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
04814          if (gain || drc) {
04815             k = AST_MULAW(j);
04816             if (drc) {
04817                k = drc_sample(k, drc);
04818             }
04819             k = (float)k*linear_gain;
04820             if (k > 32767) k = 32767;
04821             if (k < -32767) k = -32767;
04822             g->txgain[j] = AST_LIN2MU(k);
04823 
04824          } else {
04825             g->txgain[j] = j;
04826          }
04827       }
04828       break;
04829    }
04830 }
04831 
04832 static void fill_rxgain(struct dahdi_gains *g, float gain, float drc, int law)
04833 {
04834    int j;
04835    int k;
04836    float linear_gain = pow(10.0, gain / 20.0);
04837 
04838    switch (law) {
04839    case DAHDI_LAW_ALAW:
04840       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
04841          if (gain || drc) {
04842             k = AST_ALAW(j);
04843             if (drc) {
04844                k = drc_sample(k, drc);
04845             }
04846             k = (float)k*linear_gain;
04847             if (k > 32767) k = 32767;
04848             if (k < -32767) k = -32767;
04849             g->rxgain[j] = AST_LIN2A(k);
04850          } else {
04851             g->rxgain[j] = j;
04852          }
04853       }
04854       break;
04855    case DAHDI_LAW_MULAW:
04856       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
04857          if (gain || drc) {
04858             k = AST_MULAW(j);
04859             if (drc) {
04860                k = drc_sample(k, drc);
04861             }
04862             k = (float)k*linear_gain;
04863             if (k > 32767) k = 32767;
04864             if (k < -32767) k = -32767;
04865             g->rxgain[j] = AST_LIN2MU(k);
04866          } else {
04867             g->rxgain[j] = j;
04868          }
04869       }
04870       break;
04871    }
04872 }
04873 
04874 static int set_actual_txgain(int fd, float gain, float drc, int law)
04875 {
04876    struct dahdi_gains g;
04877    int res;
04878 
04879    memset(&g, 0, sizeof(g));
04880    res = ioctl(fd, DAHDI_GETGAINS, &g);
04881    if (res) {
04882       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
04883       return res;
04884    }
04885 
04886    fill_txgain(&g, gain, drc, law);
04887 
04888    return ioctl(fd, DAHDI_SETGAINS, &g);
04889 }
04890 
04891 static int set_actual_rxgain(int fd, float gain, float drc, int law)
04892 {
04893    struct dahdi_gains g;
04894    int res;
04895 
04896    memset(&g, 0, sizeof(g));
04897    res = ioctl(fd, DAHDI_GETGAINS, &g);
04898    if (res) {
04899       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
04900       return res;
04901    }
04902 
04903    fill_rxgain(&g, gain, drc, law);
04904 
04905    return ioctl(fd, DAHDI_SETGAINS, &g);
04906 }
04907 
04908 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law)
04909 {
04910    return set_actual_txgain(fd, txgain, txdrc, law) | set_actual_rxgain(fd, rxgain, rxdrc, law);
04911 }
04912 
04913 static int bump_gains(struct dahdi_pvt *p)
04914 {
04915    int res;
04916 
04917    /* Bump receive gain by value stored in cid_rxgain */
04918    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain + p->cid_rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
04919    if (res) {
04920       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
04921       return -1;
04922    }
04923 
04924    return 0;
04925 }
04926 
04927 static int restore_gains(struct dahdi_pvt *p)
04928 {
04929    int res;
04930 
04931    res = set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
04932    if (res) {
04933       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
04934       return -1;
04935    }
04936 
04937    return 0;
04938 }
04939 
04940 static inline int dahdi_set_hook(int fd, int hs)
04941 {
04942    int x, res;
04943 
04944    x = hs;
04945    res = ioctl(fd, DAHDI_HOOK, &x);
04946 
04947    if (res < 0) {
04948       if (errno == EINPROGRESS)
04949          return 0;
04950       ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
04951       /* will expectedly fail if phone is off hook during operation, such as during a restart */
04952    }
04953 
04954    return res;
04955 }
04956 
04957 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
04958 {
04959    int x, res;
04960 
04961    x = muted;
04962 #if defined(HAVE_PRI) || defined(HAVE_SS7)
04963    switch (p->sig) {
04964 #if defined(HAVE_PRI)
04965    case SIG_PRI_LIB_HANDLE_CASES:
04966       if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
04967          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
04968          break;
04969       }
04970       /* Fall through */
04971 #endif   /* defined(HAVE_PRI) */
04972 #if defined(HAVE_SS7)
04973    case SIG_SS7:
04974 #endif   /* defined(HAVE_SS7) */
04975       {
04976          int y = 1;
04977 
04978          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
04979          if (res)
04980             ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n",
04981                p->channel, strerror(errno));
04982       }
04983       break;
04984    default:
04985       break;
04986    }
04987 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
04988    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
04989    if (res < 0)
04990       ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
04991    return res;
04992 }
04993 
04994 static int save_conference(struct dahdi_pvt *p)
04995 {
04996    struct dahdi_confinfo c;
04997    int res;
04998    if (p->saveconf.confmode) {
04999       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
05000       return -1;
05001    }
05002    p->saveconf.chan = 0;
05003    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
05004    if (res) {
05005       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
05006       p->saveconf.confmode = 0;
05007       return -1;
05008    }
05009    memset(&c, 0, sizeof(c));
05010    c.confmode = DAHDI_CONF_NORMAL;
05011    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
05012    if (res) {
05013       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
05014       return -1;
05015    }
05016    ast_debug(1, "Disabled conferencing\n");
05017    return 0;
05018 }
05019 
05020 static int restore_conference(struct dahdi_pvt *p)
05021 {
05022    int res;
05023    if (p->saveconf.confmode) {
05024       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
05025       p->saveconf.confmode = 0;
05026       if (res) {
05027          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
05028          return -1;
05029       }
05030    }
05031    ast_debug(1, "Restored conferencing\n");
05032    return 0;
05033 }
05034 
05035 static int send_callerid(struct dahdi_pvt *p);
05036 
05037 static int send_cwcidspill(struct dahdi_pvt *p)
05038 {
05039    p->callwaitcas = 0;
05040    p->cidcwexpire = 0;
05041    if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
05042       return -1;
05043    p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
05044    /* Make sure we account for the end */
05045    p->cidlen += READ_SIZE * 4;
05046    p->cidpos = 0;
05047    send_callerid(p);
05048    ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
05049    return 0;
05050 }
05051 
05052 static int has_voicemail(struct dahdi_pvt *p)
05053 {
05054    int new_msgs;
05055    struct ast_event *event;
05056    char *mailbox, *context;
05057 
05058    mailbox = context = ast_strdupa(p->mailbox);
05059    strsep(&context, "@");
05060    if (ast_strlen_zero(context))
05061       context = "default";
05062 
05063    event = ast_event_get_cached(AST_EVENT_MWI,
05064       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
05065       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
05066       AST_EVENT_IE_END);
05067 
05068    if (event) {
05069       new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
05070       ast_event_destroy(event);
05071    } else
05072       new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
05073 
05074    return new_msgs;
05075 }
05076 
05077 
05078 
05079 static int send_callerid(struct dahdi_pvt *p)
05080 {
05081    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
05082    int res;
05083    /* Take out of linear mode if necessary */
05084    if (p->subs[SUB_REAL].linear) {
05085       p->subs[SUB_REAL].linear = 0;
05086       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
05087    }
05088    while (p->cidpos < p->cidlen) {
05089       res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
05090       ast_debug(4, "writing callerid at pos %d of %d, res = %d\n", p->cidpos, p->cidlen, res);
05091       if (res < 0) {
05092          if (errno == EAGAIN)
05093             return 0;
05094          else {
05095             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
05096             return -1;
05097          }
05098       }
05099       if (!res)
05100          return 0;
05101       p->cidpos += res;
05102    }
05103    ast_free(p->cidspill);
05104    p->cidspill = NULL;
05105    if (p->callwaitcas) {
05106       /* Wait for CID/CW to expire */
05107       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
05108    } else
05109       restore_conference(p);
05110    return 0;
05111 }
05112 
05113 static int dahdi_callwait(struct ast_channel *ast)
05114 {
05115    struct dahdi_pvt *p = ast->tech_pvt;
05116    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
05117    if (p->cidspill) {
05118       ast_log(LOG_WARNING, "Spill already exists?!?\n");
05119       ast_free(p->cidspill);
05120    }
05121    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
05122       return -1;
05123    save_conference(p);
05124    /* Silence */
05125    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
05126    if (!p->callwaitrings && p->callwaitingcallerid) {
05127       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
05128       p->callwaitcas = 1;
05129       p->cidlen = 2400 + 680 + READ_SIZE * 4;
05130    } else {
05131       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
05132       p->callwaitcas = 0;
05133       p->cidlen = 2400 + READ_SIZE * 4;
05134    }
05135    p->cidpos = 0;
05136    send_callerid(p);
05137 
05138    return 0;
05139 }
05140 
05141 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
05142 {
05143    struct dahdi_pvt *p = ast->tech_pvt;
05144    int x, res, mysig;
05145    char dest[256]; /* must be same length as p->dialdest */
05146 
05147    ast_mutex_lock(&p->lock);
05148    ast_copy_string(dest, rdest, sizeof(dest));
05149    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
05150    if ((ast->_state == AST_STATE_BUSY)) {
05151       p->subs[SUB_REAL].needbusy = 1;
05152       ast_mutex_unlock(&p->lock);
05153       return 0;
05154    }
05155    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05156       ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
05157       ast_mutex_unlock(&p->lock);
05158       return -1;
05159    }
05160    p->waitingfordt.tv_sec = 0;
05161    p->dialednone = 0;
05162    if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
05163    {
05164       /* Special pseudo -- automatically up */
05165       ast_setstate(ast, AST_STATE_UP);
05166       ast_mutex_unlock(&p->lock);
05167       return 0;
05168    }
05169    x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
05170    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
05171    if (res)
05172       ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
05173    p->outgoing = 1;
05174 
05175    if (IS_DIGITAL(ast->transfercapability)){
05176       set_actual_gain(p->subs[SUB_REAL].dfd, 0, 0, p->rxdrc, p->txdrc, p->law);
05177    } else {
05178       set_actual_gain(p->subs[SUB_REAL].dfd, p->rxgain, p->txgain, p->rxdrc, p->txdrc, p->law);
05179    }  
05180 
05181 #ifdef HAVE_PRI
05182    if (dahdi_sig_pri_lib_handles(p->sig)) {
05183       res = sig_pri_call(p->sig_pvt, ast, rdest, timeout,
05184          (p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW);
05185       ast_mutex_unlock(&p->lock);
05186       return res;
05187    }
05188 #endif
05189 
05190 #if defined(HAVE_SS7)
05191    if (p->sig == SIG_SS7) {
05192       res = sig_ss7_call(p->sig_pvt, ast, rdest);
05193       ast_mutex_unlock(&p->lock);
05194       return res;
05195    }
05196 #endif   /* defined(HAVE_SS7) */
05197 
05198    /* If this is analog signalling we can exit here */
05199    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
05200       p->callwaitrings = 0;
05201       res = analog_call(p->sig_pvt, ast, rdest, timeout);
05202       ast_mutex_unlock(&p->lock);
05203       return res;
05204    }
05205 
05206    mysig = p->outsigmod > -1 ? p->outsigmod : p->sig;
05207    switch (mysig) {
05208    case 0:
05209       /* Special pseudo -- automatically up*/
05210       ast_setstate(ast, AST_STATE_UP);
05211       break;
05212    case SIG_MFCR2:
05213       break;
05214    default:
05215       ast_debug(1, "not yet implemented\n");
05216       ast_mutex_unlock(&p->lock);
05217       return -1;
05218    }
05219 
05220 #ifdef HAVE_OPENR2
05221    if (p->mfcr2) {
05222       openr2_calling_party_category_t chancat;
05223       int callres = 0;
05224       char *c, *l;
05225 
05226       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
05227       p->dialdest[0] = '\0';
05228 
05229       c = strchr(dest, '/');
05230       if (c) {
05231          c++;
05232       } else {
05233          c = "";
05234       }
05235       if (!p->hidecallerid) {
05236          l = ast->caller.id.number.valid ? ast->caller.id.number.str : NULL;
05237       } else {
05238          l = NULL;
05239       }
05240       if (strlen(c) < p->stripmsd) {
05241          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
05242          ast_mutex_unlock(&p->lock);
05243          return -1;
05244       }
05245       p->dialing = 1;
05246       chancat = dahdi_r2_get_channel_category(ast);
05247       callres = openr2_chan_make_call(p->r2chan, l, (c + p->stripmsd), chancat);
05248       if (-1 == callres) {
05249          ast_mutex_unlock(&p->lock);
05250          ast_log(LOG_ERROR, "unable to make new MFC/R2 call!\n");
05251          return -1;
05252       }
05253       ast_setstate(ast, AST_STATE_DIALING);
05254    }
05255 #endif /* HAVE_OPENR2 */
05256    ast_mutex_unlock(&p->lock);
05257    return 0;
05258 }
05259 
05260 /*!
05261  * \internal
05262  * \brief Insert the given chan_dahdi interface structure into the interface list.
05263  * \since 1.8
05264  *
05265  * \param pvt chan_dahdi private interface structure to insert.
05266  *
05267  * \details
05268  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05269  * Any duplicates are inserted after the existing entries.
05270  *
05271  * \note The new interface must not already be in the list.
05272  *
05273  * \return Nothing
05274  */
05275 static void dahdi_iflist_insert(struct dahdi_pvt *pvt)
05276 {
05277    struct dahdi_pvt *cur;
05278 
05279    pvt->which_iflist = DAHDI_IFLIST_MAIN;
05280 
05281    /* Find place in middle of list for the new interface. */
05282    for (cur = iflist; cur; cur = cur->next) {
05283       if (pvt->channel < cur->channel) {
05284          /* New interface goes before the current interface. */
05285          pvt->prev = cur->prev;
05286          pvt->next = cur;
05287          if (cur->prev) {
05288             /* Insert into the middle of the list. */
05289             cur->prev->next = pvt;
05290          } else {
05291             /* Insert at head of list. */
05292             iflist = pvt;
05293          }
05294          cur->prev = pvt;
05295          return;
05296       }
05297    }
05298 
05299    /* New interface goes onto the end of the list */
05300    pvt->prev = ifend;
05301    pvt->next = NULL;
05302    if (ifend) {
05303       ifend->next = pvt;
05304    }
05305    ifend = pvt;
05306    if (!iflist) {
05307       /* List was empty */
05308       iflist = pvt;
05309    }
05310 }
05311 
05312 /*!
05313  * \internal
05314  * \brief Extract the given chan_dahdi interface structure from the interface list.
05315  * \since 1.8
05316  *
05317  * \param pvt chan_dahdi private interface structure to extract.
05318  *
05319  * \note
05320  * The given interface structure can be either in the interface list or a stand alone
05321  * structure that has not been put in the list if the next and prev pointers are NULL.
05322  *
05323  * \return Nothing
05324  */
05325 static void dahdi_iflist_extract(struct dahdi_pvt *pvt)
05326 {
05327    /* Extract from the forward chain. */
05328    if (pvt->prev) {
05329       pvt->prev->next = pvt->next;
05330    } else if (iflist == pvt) {
05331       /* Node is at the head of the list. */
05332       iflist = pvt->next;
05333    }
05334 
05335    /* Extract from the reverse chain. */
05336    if (pvt->next) {
05337       pvt->next->prev = pvt->prev;
05338    } else if (ifend == pvt) {
05339       /* Node is at the end of the list. */
05340       ifend = pvt->prev;
05341    }
05342 
05343    /* Node is no longer in the list. */
05344    pvt->which_iflist = DAHDI_IFLIST_NONE;
05345    pvt->prev = NULL;
05346    pvt->next = NULL;
05347 }
05348 
05349 #if defined(HAVE_PRI)
05350 /*!
05351  * \internal
05352  * \brief Insert the given chan_dahdi interface structure into the no B channel list.
05353  * \since 1.8
05354  *
05355  * \param pri sig_pri span control structure holding no B channel list.
05356  * \param pvt chan_dahdi private interface structure to insert.
05357  *
05358  * \details
05359  * The interface list is a doubly linked list sorted by the chan_dahdi channel number.
05360  * Any duplicates are inserted after the existing entries.
05361  *
05362  * \note The new interface must not already be in the list.
05363  *
05364  * \return Nothing
05365  */
05366 static void dahdi_nobch_insert(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05367 {
05368    struct dahdi_pvt *cur;
05369 
05370    pvt->which_iflist = DAHDI_IFLIST_NO_B_CHAN;
05371 
05372    /* Find place in middle of list for the new interface. */
05373    for (cur = pri->no_b_chan_iflist; cur; cur = cur->next) {
05374       if (pvt->channel < cur->channel) {
05375          /* New interface goes before the current interface. */
05376          pvt->prev = cur->prev;
05377          pvt->next = cur;
05378          if (cur->prev) {
05379             /* Insert into the middle of the list. */
05380             cur->prev->next = pvt;
05381          } else {
05382             /* Insert at head of list. */
05383             pri->no_b_chan_iflist = pvt;
05384          }
05385          cur->prev = pvt;
05386          return;
05387       }
05388    }
05389 
05390    /* New interface goes onto the end of the list */
05391    pvt->prev = pri->no_b_chan_end;
05392    pvt->next = NULL;
05393    if (pri->no_b_chan_end) {
05394       ((struct dahdi_pvt *) pri->no_b_chan_end)->next = pvt;
05395    }
05396    pri->no_b_chan_end = pvt;
05397    if (!pri->no_b_chan_iflist) {
05398       /* List was empty */
05399       pri->no_b_chan_iflist = pvt;
05400    }
05401 }
05402 #endif   /* defined(HAVE_PRI) */
05403 
05404 #if defined(HAVE_PRI)
05405 /*!
05406  * \internal
05407  * \brief Extract the given chan_dahdi interface structure from the no B channel list.
05408  * \since 1.8
05409  *
05410  * \param pri sig_pri span control structure holding no B channel list.
05411  * \param pvt chan_dahdi private interface structure to extract.
05412  *
05413  * \note
05414  * The given interface structure can be either in the interface list or a stand alone
05415  * structure that has not been put in the list if the next and prev pointers are NULL.
05416  *
05417  * \return Nothing
05418  */
05419 static void dahdi_nobch_extract(struct sig_pri_span *pri, struct dahdi_pvt *pvt)
05420 {
05421    /* Extract from the forward chain. */
05422    if (pvt->prev) {
05423       pvt->prev->next = pvt->next;
05424    } else if (pri->no_b_chan_iflist == pvt) {
05425       /* Node is at the head of the list. */
05426       pri->no_b_chan_iflist = pvt->next;
05427    }
05428 
05429    /* Extract from the reverse chain. */
05430    if (pvt->next) {
05431       pvt->next->prev = pvt->prev;
05432    } else if (pri->no_b_chan_end == pvt) {
05433       /* Node is at the end of the list. */
05434       pri->no_b_chan_end = pvt->prev;
05435    }
05436 
05437    /* Node is no longer in the list. */
05438    pvt->which_iflist = DAHDI_IFLIST_NONE;
05439    pvt->prev = NULL;
05440    pvt->next = NULL;
05441 }
05442 #endif   /* defined(HAVE_PRI) */
05443 
05444 #if defined(HAVE_PRI)
05445 /*!
05446  * \internal
05447  * \brief Unlink the channel interface from the PRI private pointer array.
05448  * \since 1.8
05449  *
05450  * \param pvt chan_dahdi private interface structure to unlink.
05451  *
05452  * \return Nothing
05453  */
05454 static void dahdi_unlink_pri_pvt(struct dahdi_pvt *pvt)
05455 {
05456    unsigned idx;
05457    struct sig_pri_span *pri;
05458 
05459    pri = pvt->pri;
05460    if (!pri) {
05461       /* Not PRI signaling so cannot be in a PRI private pointer array. */
05462       return;
05463    }
05464    ast_mutex_lock(&pri->lock);
05465    for (idx = 0; idx < pri->numchans; ++idx) {
05466       if (pri->pvts[idx] == pvt->sig_pvt) {
05467          pri->pvts[idx] = NULL;
05468          ast_mutex_unlock(&pri->lock);
05469          return;
05470       }
05471    }
05472    ast_mutex_unlock(&pri->lock);
05473 }
05474 #endif   /* defined(HAVE_PRI) */
05475 
05476 #if defined(HAVE_SS7)
05477 /*!
05478  * \internal
05479  * \brief Unlink the channel interface from the SS7 private pointer array.
05480  * \since 1.8
05481  *
05482  * \param pvt chan_dahdi private interface structure to unlink.
05483  *
05484  * \return Nothing
05485  */
05486 static void dahdi_unlink_ss7_pvt(struct dahdi_pvt *pvt)
05487 {
05488    unsigned idx;
05489    struct sig_ss7_linkset *ss7;
05490 
05491    ss7 = pvt->ss7;
05492    if (!ss7) {
05493       /* Not SS7 signaling so cannot be in a SS7 private pointer array. */
05494       return;
05495    }
05496    ast_mutex_lock(&ss7->lock);
05497    for (idx = 0; idx < ss7->numchans; ++idx) {
05498       if (ss7->pvts[idx] == pvt->sig_pvt) {
05499          ss7->pvts[idx] = NULL;
05500          ast_mutex_unlock(&ss7->lock);
05501          return;
05502       }
05503    }
05504    ast_mutex_unlock(&ss7->lock);
05505 }
05506 #endif   /* defined(HAVE_SS7) */
05507 
05508 static struct dahdi_pvt *find_next_iface_in_span(struct dahdi_pvt *cur)
05509 {
05510    if (cur->next && cur->next->span == cur->span) {
05511       return cur->next;
05512    } else if (cur->prev && cur->prev->span == cur->span) {
05513       return cur->prev;
05514    }
05515 
05516    return NULL;
05517 }
05518 
05519 static void destroy_dahdi_pvt(struct dahdi_pvt *pvt)
05520 {
05521    struct dahdi_pvt *p = pvt;
05522 
05523    if (p->manages_span_alarms) {
05524       struct dahdi_pvt *next = find_next_iface_in_span(p);
05525       if (next) {
05526          next->manages_span_alarms = 1;
05527       }
05528    }
05529 
05530    /* Remove channel from the list */
05531 #if defined(HAVE_PRI)
05532    dahdi_unlink_pri_pvt(p);
05533 #endif   /* defined(HAVE_PRI) */
05534 #if defined(HAVE_SS7)
05535    dahdi_unlink_ss7_pvt(p);
05536 #endif   /* defined(HAVE_SS7) */
05537    switch (pvt->which_iflist) {
05538    case DAHDI_IFLIST_NONE:
05539       break;
05540    case DAHDI_IFLIST_MAIN:
05541       dahdi_iflist_extract(p);
05542       break;
05543 #if defined(HAVE_PRI)
05544    case DAHDI_IFLIST_NO_B_CHAN:
05545       if (p->pri) {
05546          dahdi_nobch_extract(p->pri, p);
05547       }
05548       break;
05549 #endif   /* defined(HAVE_PRI) */
05550    }
05551 
05552    if (p->sig_pvt) {
05553       if (analog_lib_handles(p->sig, 0, 0)) {
05554          analog_delete(p->sig_pvt);
05555       }
05556       switch (p->sig) {
05557 #if defined(HAVE_PRI)
05558       case SIG_PRI_LIB_HANDLE_CASES:
05559          sig_pri_chan_delete(p->sig_pvt);
05560          break;
05561 #endif   /* defined(HAVE_PRI) */
05562 #if defined(HAVE_SS7)
05563       case SIG_SS7:
05564          sig_ss7_chan_delete(p->sig_pvt);
05565          break;
05566 #endif   /* defined(HAVE_SS7) */
05567       default:
05568          break;
05569       }
05570    }
05571    if (p->cidspill) {
05572       ast_free(p->cidspill);
05573    }
05574    if (p->use_smdi)
05575       ast_smdi_interface_unref(p->smdi_iface);
05576    if (p->mwi_event_sub)
05577       ast_event_unsubscribe(p->mwi_event_sub);
05578    if (p->vars) {
05579       ast_variables_destroy(p->vars);
05580    }
05581    if (p->cc_params) {
05582       ast_cc_config_params_destroy(p->cc_params);
05583    }
05584    ast_mutex_destroy(&p->lock);
05585    dahdi_close_sub(p, SUB_REAL);
05586    if (p->owner)
05587       p->owner->tech_pvt = NULL;
05588    ast_free(p);
05589 }
05590 
05591 static void destroy_channel(struct dahdi_pvt *cur, int now)
05592 {
05593    int i;
05594 
05595    if (!now) {
05596       /* Do not destroy the channel now if it is owned by someone. */
05597       if (cur->owner) {
05598          return;
05599       }
05600       for (i = 0; i < 3; i++) {
05601          if (cur->subs[i].owner) {
05602             return;
05603          }
05604       }
05605    }
05606    destroy_dahdi_pvt(cur);
05607 }
05608 
05609 static void destroy_all_channels(void)
05610 {
05611    int chan;
05612 #if defined(HAVE_PRI)
05613    unsigned span;
05614    struct sig_pri_span *pri;
05615 #endif   /* defined(HAVE_PRI) */
05616    struct dahdi_pvt *p;
05617 
05618    while (num_restart_pending) {
05619       usleep(1);
05620    }
05621 
05622    ast_mutex_lock(&iflock);
05623    /* Destroy all the interfaces and free their memory */
05624    while (iflist) {
05625       p = iflist;
05626 
05627       chan = p->channel;
05628 #if defined(HAVE_PRI_SERVICE_MESSAGES)
05629       {
05630          char db_chan_name[20];
05631          char db_answer[5];
05632          char state;
05633          int why = -1;
05634 
05635          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, p->span, chan);
05636          if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
05637             sscanf(db_answer, "%1c:%30d", &state, &why);
05638          }
05639          if (!why) {
05640             /* SRVST persistence is not required */
05641             ast_db_del(db_chan_name, SRVST_DBKEY);
05642          }
05643       }
05644 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
05645       /* Free associated memory */
05646       destroy_dahdi_pvt(p);
05647       ast_verb(3, "Unregistered channel %d\n", chan);
05648    }
05649    ifcount = 0;
05650    ast_mutex_unlock(&iflock);
05651 
05652 #if defined(HAVE_PRI)
05653    /* Destroy all of the no B channel interface lists */
05654    for (span = 0; span < NUM_SPANS; ++span) {
05655       if (!pris[span].dchannels[0]) {
05656          break;
05657       }
05658       pri = &pris[span].pri;
05659       ast_mutex_lock(&pri->lock);
05660       while (pri->no_b_chan_iflist) {
05661          p = pri->no_b_chan_iflist;
05662 
05663          /* Free associated memory */
05664          destroy_dahdi_pvt(p);
05665       }
05666       ast_mutex_unlock(&pri->lock);
05667    }
05668 #endif   /* defined(HAVE_PRI) */
05669 }
05670 
05671 #if defined(HAVE_PRI)
05672 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
05673 
05674 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, const char *digits)
05675 {
05676    /* Data will be our digit string */
05677    struct dahdi_pvt *p;
05678 
05679    if (ast_strlen_zero(digits)) {
05680       ast_debug(1, "No digit string sent to application!\n");
05681       return -1;
05682    }
05683 
05684    p = (struct dahdi_pvt *)chan->tech_pvt;
05685 
05686    if (!p) {
05687       ast_debug(1, "Unable to find technology private\n");
05688       return -1;
05689    }
05690 
05691    pri_send_keypad_facility_exec(p->sig_pvt, digits);
05692 
05693    return 0;
05694 }
05695 #endif   /* defined(HAVE_PRI) */
05696 
05697 #if defined(HAVE_PRI)
05698 #if defined(HAVE_PRI_PROG_W_CAUSE)
05699 static char *dahdi_send_callrerouting_facility_app = "DAHDISendCallreroutingFacility";
05700 
05701 static int dahdi_send_callrerouting_facility_exec(struct ast_channel *chan, const char *data)
05702 {
05703    /* Data will be our digit string */
05704    struct dahdi_pvt *pvt;
05705    char *parse;
05706    int res = -1;
05707    AST_DECLARE_APP_ARGS(args,
05708       AST_APP_ARG(destination);
05709       AST_APP_ARG(original);
05710       AST_APP_ARG(reason);
05711    );
05712 
05713    if (ast_strlen_zero(data)) {
05714       ast_log(LOG_DEBUG, "No data sent to application!\n");
05715       return -1;
05716    }
05717    if (chan->tech != &dahdi_tech) {
05718       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05719       return -1;
05720    }
05721    pvt = (struct dahdi_pvt *) chan->tech_pvt;
05722    if (!pvt) {
05723       ast_log(LOG_DEBUG, "Unable to find technology private\n");
05724       return -1;
05725    }
05726    switch (pvt->sig) {
05727    case SIG_PRI_LIB_HANDLE_CASES:
05728       break;
05729    default:
05730       ast_log(LOG_DEBUG, "callrerouting attempted on non-ISDN channel %s\n",
05731          chan->name);
05732       return -1;
05733    }
05734 
05735    parse = ast_strdupa(data);
05736    AST_STANDARD_APP_ARGS(args, parse);
05737 
05738    if (ast_strlen_zero(args.destination)) {
05739       ast_log(LOG_WARNING, "callrerouting facility requires at least destination number argument\n");
05740       return -1;
05741    }
05742 
05743    if (ast_strlen_zero(args.original)) {
05744       ast_log(LOG_WARNING, "Callrerouting Facility without original called number argument\n");
05745       args.original = NULL;
05746    }
05747 
05748    if (ast_strlen_zero(args.reason)) {
05749       ast_log(LOG_NOTICE, "Callrerouting Facility without diversion reason argument, defaulting to unknown\n");
05750       args.reason = NULL;
05751    }
05752 
05753    pri_send_callrerouting_facility_exec(pvt->sig_pvt, chan->_state, args.destination,
05754       args.original, args.reason);
05755 
05756    return res;
05757 }
05758 #endif   /* defined(HAVE_PRI_PROG_W_CAUSE) */
05759 #endif   /* defined(HAVE_PRI) */
05760 
05761 #if defined(HAVE_OPENR2)
05762 static const char * const dahdi_accept_r2_call_app = "DAHDIAcceptR2Call";
05763 
05764 static int dahdi_accept_r2_call_exec(struct ast_channel *chan, const char *data)
05765 {
05766    /* data is whether to accept with charge or no charge */
05767    openr2_call_mode_t accept_mode;
05768    int res, timeout, maxloops;
05769    struct ast_frame *f;
05770    struct dahdi_pvt *p;
05771    char *parse;
05772    AST_DECLARE_APP_ARGS(args,
05773          AST_APP_ARG(charge);
05774    );
05775 
05776    if (ast_strlen_zero(data)) {
05777       ast_log(LOG_DEBUG, "No data sent to application!\n");
05778       return -1;
05779    }
05780 
05781    if (chan->tech != &dahdi_tech) {
05782       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
05783       return -1;
05784    }
05785 
05786    p = (struct dahdi_pvt *)chan->tech_pvt;
05787    if (!p) {
05788       ast_log(LOG_DEBUG, "Unable to find technology private!\n");
05789       return -1;
05790    }
05791 
05792    parse = ast_strdupa(data);
05793    AST_STANDARD_APP_ARGS(args, parse);
05794 
05795    if (ast_strlen_zero(args.charge)) {
05796       ast_log(LOG_WARNING, "DAHDIAcceptR2Call requires 'yes' or 'no' for the charge parameter\n");
05797       return -1;
05798    }
05799 
05800    ast_mutex_lock(&p->lock);
05801    if (!p->mfcr2 || !p->mfcr2call) {
05802       ast_mutex_unlock(&p->lock);
05803       ast_log(LOG_DEBUG, "Channel %s does not seems to be an R2 active channel!\n", chan->name);
05804       return -1;
05805    }
05806 
05807    if (p->mfcr2_call_accepted) {
05808       ast_mutex_unlock(&p->lock);
05809       ast_log(LOG_DEBUG, "MFC/R2 call already accepted on channel %s!\n", chan->name);
05810       return 0;
05811    }
05812    accept_mode = ast_true(args.charge) ? OR2_CALL_WITH_CHARGE : OR2_CALL_NO_CHARGE;
05813    if (openr2_chan_accept_call(p->r2chan, accept_mode)) {
05814       ast_mutex_unlock(&p->lock);
05815       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
05816       return -1;
05817    }
05818    ast_mutex_unlock(&p->lock);
05819 
05820    res = 0;
05821    timeout = 100;
05822    maxloops = 50; /* wait up to 5 seconds */
05823    /* we need to read() until the call is accepted */
05824    while (maxloops > 0) {
05825       maxloops--;
05826       if (ast_check_hangup(chan)) {
05827          break;
05828       }
05829       res = ast_waitfor(chan, timeout);
05830       if (res < 0) {
05831          ast_log(LOG_DEBUG, "ast_waitfor failed on channel %s, going out ...\n", chan->name);
05832          res = -1;
05833          break;
05834       }
05835       if (res == 0) {
05836          continue;
05837       }
05838       f = ast_read(chan);
05839       if (!f) {
05840          ast_log(LOG_DEBUG, "No frame read on channel %s, going out ...\n", chan->name);
05841          res = -1;
05842          break;
05843       }
05844       if (f->frametype == AST_FRAME_CONTROL && f->subclass.integer == AST_CONTROL_HANGUP) {
05845          ast_log(LOG_DEBUG, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
05846          ast_frfree(f);
05847          res = -1;
05848          break;
05849       }
05850       ast_frfree(f);
05851       ast_mutex_lock(&p->lock);
05852       if (p->mfcr2_call_accepted) {
05853          ast_mutex_unlock(&p->lock);
05854          ast_log(LOG_DEBUG, "Accepted MFC/R2 call!\n");
05855          break;
05856       }
05857       ast_mutex_unlock(&p->lock);
05858    }
05859    if (res == -1) {
05860       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
05861    }
05862    return res;
05863 }
05864 
05865 static openr2_call_disconnect_cause_t dahdi_ast_cause_to_r2_cause(int cause)
05866 {
05867    openr2_call_disconnect_cause_t r2cause = OR2_CAUSE_NORMAL_CLEARING;
05868    switch (cause) {
05869    case AST_CAUSE_USER_BUSY:
05870    case AST_CAUSE_CALL_REJECTED:
05871    case AST_CAUSE_INTERWORKING: /* I don't know wtf is this but is used sometimes when ekiga rejects a call */
05872       r2cause = OR2_CAUSE_BUSY_NUMBER;
05873       break;
05874 
05875    case AST_CAUSE_NORMAL_CIRCUIT_CONGESTION:
05876    case AST_CAUSE_SWITCH_CONGESTION:
05877       r2cause = OR2_CAUSE_NETWORK_CONGESTION;
05878       break;
05879 
05880    case AST_CAUSE_UNALLOCATED:
05881       r2cause = OR2_CAUSE_UNALLOCATED_NUMBER;
05882       break;
05883 
05884    case AST_CAUSE_NETWORK_OUT_OF_ORDER:
05885    case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05886       r2cause = OR2_CAUSE_OUT_OF_ORDER;
05887       break;
05888 
05889    case AST_CAUSE_NO_ANSWER:
05890    case AST_CAUSE_NO_USER_RESPONSE:
05891       r2cause = OR2_CAUSE_NO_ANSWER;
05892       break;
05893 
05894    default:
05895       r2cause = OR2_CAUSE_NORMAL_CLEARING;
05896       break;
05897    }
05898    ast_log(LOG_DEBUG, "ast cause %d resulted in openr2 cause %d/%s\n",
05899          cause, r2cause, openr2_proto_get_disconnect_string(r2cause));
05900    return r2cause;
05901 }
05902 #endif
05903 
05904 static int revert_fax_buffers(struct dahdi_pvt *p, struct ast_channel *ast)
05905 {
05906    if (p->bufferoverrideinuse) {
05907       /* faxbuffers are in use, revert them */
05908       struct dahdi_bufferinfo bi = {
05909          .txbufpolicy = p->buf_policy,
05910          .rxbufpolicy = p->buf_policy,
05911          .bufsize = p->bufsize,
05912          .numbufs = p->buf_no
05913       };
05914       int bpres;
05915 
05916       if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
05917          ast_log(LOG_WARNING, "Channel '%s' unable to revert buffer policy: %s\n", ast->name, strerror(errno));
05918       }
05919       p->bufferoverrideinuse = 0;
05920       return bpres;
05921    }
05922 
05923    return -1;
05924 }
05925 
05926 static int dahdi_hangup(struct ast_channel *ast)
05927 {
05928    int res = 0;
05929    int idx,x;
05930    int law;
05931    /*static int restore_gains(struct dahdi_pvt *p);*/
05932    struct dahdi_pvt *p = ast->tech_pvt;
05933    struct dahdi_params par;
05934 
05935    ast_debug(1, "dahdi_hangup(%s)\n", ast->name);
05936    if (!ast->tech_pvt) {
05937       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
05938       return 0;
05939    }
05940 
05941    ast_mutex_lock(&p->lock);
05942    p->exten[0] = '\0';
05943    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
05944       dahdi_confmute(p, 0);
05945       restore_gains(p);
05946       p->ignoredtmf = 0;
05947       p->waitingfordt.tv_sec = 0;
05948 
05949       res = analog_hangup(p->sig_pvt, ast);
05950       revert_fax_buffers(p, ast);
05951 
05952       goto hangup_out;
05953    } else {
05954       p->cid_num[0] = '\0';
05955       p->cid_name[0] = '\0';
05956       p->cid_subaddr[0] = '\0';
05957    }
05958 
05959 #ifdef HAVE_PRI
05960    if (dahdi_sig_pri_lib_handles(p->sig)) {
05961       x = 1;
05962       ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
05963       dahdi_confmute(p, 0);
05964       p->muting = 0;
05965       restore_gains(p);
05966       if (p->dsp) {
05967          ast_dsp_free(p->dsp);
05968          p->dsp = NULL;
05969       }
05970       p->ignoredtmf = 0;
05971       revert_fax_buffers(p, ast);
05972       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
05973       p->law = p->law_default;
05974       law = p->law_default;
05975       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
05976       dahdi_disable_ec(p);
05977       update_conf(p);
05978       reset_conf(p);
05979       sig_pri_hangup(p->sig_pvt, ast);
05980       p->subs[SUB_REAL].owner = NULL;
05981       p->subs[SUB_REAL].needbusy = 0;
05982       p->owner = NULL;
05983       p->cid_tag[0] = '\0';
05984       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
05985       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
05986       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
05987       p->outgoing = 0;
05988       p->digital = 0;
05989       p->faxhandled = 0;
05990       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
05991       goto hangup_out;
05992    }
05993 #endif
05994 
05995 #if defined(HAVE_SS7)
05996    if (p->sig == SIG_SS7) {
05997       x = 1;
05998       ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
05999 
06000       dahdi_confmute(p, 0);
06001       p->muting = 0;
06002       restore_gains(p);
06003       if (p->dsp) {
06004          ast_dsp_free(p->dsp);
06005          p->dsp = NULL;
06006       }
06007       p->ignoredtmf = 0;
06008 
06009       /* Real channel, do some fixup */
06010       p->subs[SUB_REAL].owner = NULL;
06011       p->subs[SUB_REAL].needbusy = 0;
06012       p->polarity = POLARITY_IDLE;
06013       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
06014 
06015       p->owner = NULL;
06016       p->ringt = 0;/* Probably not used in this mode.  Reset anyway. */
06017       p->distinctivering = 0;/* Probably not used in this mode. Reset anyway. */
06018       p->confirmanswer = 0;/* Probably not used in this mode. Reset anyway. */
06019       p->outgoing = 0;
06020       p->digital = 0;
06021       p->faxhandled = 0;
06022       p->pulsedial = 0;/* Probably not used in this mode. Reset anyway. */
06023 
06024       revert_fax_buffers(p, ast);
06025 
06026       p->law = p->law_default;
06027       law = p->law_default;
06028       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06029       if (res < 0)
06030          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
06031 
06032       sig_ss7_hangup(p->sig_pvt, ast);
06033 
06034       tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06035       dahdi_disable_ec(p);
06036       x = 0;
06037       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
06038       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
06039       p->didtdd = 0;/* Probably not used in this mode. Reset anyway. */
06040       update_conf(p);
06041       reset_conf(p);
06042 
06043       /* Restore data mode */
06044       x = 0;
06045       ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
06046 
06047       if (num_restart_pending == 0)
06048          restart_monitor();
06049 
06050       ast->tech_pvt = NULL;
06051       goto hangup_out;
06052    }
06053 #endif   /* defined(HAVE_SS7) */
06054 
06055    idx = dahdi_get_index(ast, p, 1);
06056 
06057    dahdi_confmute(p, 0);
06058    p->muting = 0;
06059    restore_gains(p);
06060    if (p->origcid_num) {
06061       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
06062       ast_free(p->origcid_num);
06063       p->origcid_num = NULL;
06064    }
06065    if (p->origcid_name) {
06066       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
06067       ast_free(p->origcid_name);
06068       p->origcid_name = NULL;
06069    }
06070    if (p->dsp)
06071       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
06072 
06073    ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
06074       p->channel, idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
06075    p->ignoredtmf = 0;
06076 
06077    if (idx > -1) {
06078       /* Real channel, do some fixup */
06079       p->subs[idx].owner = NULL;
06080       p->subs[idx].needanswer = 0;
06081       p->subs[idx].needflash = 0;
06082       p->subs[idx].needringing = 0;
06083       p->subs[idx].needbusy = 0;
06084       p->subs[idx].needcongestion = 0;
06085       p->subs[idx].linear = 0;
06086       p->polarity = POLARITY_IDLE;
06087       dahdi_setlinear(p->subs[idx].dfd, 0);
06088       if (idx == SUB_REAL) {
06089          if ((p->subs[SUB_CALLWAIT].dfd > -1) && (p->subs[SUB_THREEWAY].dfd > -1)) {
06090             ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
06091             if (p->subs[SUB_CALLWAIT].inthreeway) {
06092                /* We had flipped over to answer a callwait and now it's gone */
06093                ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
06094                /* Move to the call-wait, but un-own us until they flip back. */
06095                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06096                unalloc_sub(p, SUB_CALLWAIT);
06097                p->owner = NULL;
06098             } else {
06099                /* The three way hung up, but we still have a call wait */
06100                ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
06101                swap_subs(p, SUB_THREEWAY, SUB_REAL);
06102                unalloc_sub(p, SUB_THREEWAY);
06103                if (p->subs[SUB_REAL].inthreeway) {
06104                   /* This was part of a three way call.  Immediately make way for
06105                      another call */
06106                   ast_debug(1, "Call was complete, setting owner to former third call\n");
06107                   p->owner = p->subs[SUB_REAL].owner;
06108                } else {
06109                   /* This call hasn't been completed yet...  Set owner to NULL */
06110                   ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06111                   p->owner = NULL;
06112                }
06113                p->subs[SUB_REAL].inthreeway = 0;
06114             }
06115          } else if (p->subs[SUB_CALLWAIT].dfd > -1) {
06116             /* Move to the call-wait and switch back to them. */
06117             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06118             unalloc_sub(p, SUB_CALLWAIT);
06119             p->owner = p->subs[SUB_REAL].owner;
06120             if (p->owner->_state != AST_STATE_UP)
06121                p->subs[SUB_REAL].needanswer = 1;
06122             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
06123                ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
06124          } else if (p->subs[SUB_THREEWAY].dfd > -1) {
06125             swap_subs(p, SUB_THREEWAY, SUB_REAL);
06126             unalloc_sub(p, SUB_THREEWAY);
06127             if (p->subs[SUB_REAL].inthreeway) {
06128                /* This was part of a three way call.  Immediately make way for
06129                   another call */
06130                ast_debug(1, "Call was complete, setting owner to former third call\n");
06131                p->owner = p->subs[SUB_REAL].owner;
06132             } else {
06133                /* This call hasn't been completed yet...  Set owner to NULL */
06134                ast_debug(1, "Call was incomplete, setting owner to NULL\n");
06135                p->owner = NULL;
06136             }
06137             p->subs[SUB_REAL].inthreeway = 0;
06138          }
06139       } else if (idx == SUB_CALLWAIT) {
06140          /* Ditch the holding callwait call, and immediately make it availabe */
06141          if (p->subs[SUB_CALLWAIT].inthreeway) {
06142             /* This is actually part of a three way, placed on hold.  Place the third part
06143                on music on hold now */
06144             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
06145                ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
06146                   S_OR(p->mohsuggest, NULL),
06147                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06148             }
06149             p->subs[SUB_THREEWAY].inthreeway = 0;
06150             /* Make it the call wait now */
06151             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
06152             unalloc_sub(p, SUB_THREEWAY);
06153          } else
06154             unalloc_sub(p, SUB_CALLWAIT);
06155       } else if (idx == SUB_THREEWAY) {
06156          if (p->subs[SUB_CALLWAIT].inthreeway) {
06157             /* The other party of the three way call is currently in a call-wait state.
06158                Start music on hold for them, and take the main guy out of the third call */
06159             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
06160                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
06161                   S_OR(p->mohsuggest, NULL),
06162                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06163             }
06164             p->subs[SUB_CALLWAIT].inthreeway = 0;
06165          }
06166          p->subs[SUB_REAL].inthreeway = 0;
06167          /* If this was part of a three way call index, let us make
06168             another three way call */
06169          unalloc_sub(p, SUB_THREEWAY);
06170       } else {
06171          /* This wasn't any sort of call, but how are we an index? */
06172          ast_log(LOG_WARNING, "Index found but not any type of call?\n");
06173       }
06174    }
06175 
06176    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
06177       p->owner = NULL;
06178       p->ringt = 0;
06179       p->distinctivering = 0;
06180       p->confirmanswer = 0;
06181       p->outgoing = 0;
06182       p->digital = 0;
06183       p->faxhandled = 0;
06184       p->pulsedial = 0;
06185       if (p->dsp) {
06186          ast_dsp_free(p->dsp);
06187          p->dsp = NULL;
06188       }
06189 
06190       revert_fax_buffers(p, ast);
06191 
06192       p->law = p->law_default;
06193       law = p->law_default;
06194       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
06195       if (res < 0)
06196          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
06197       /* Perform low level hangup if no owner left */
06198 #ifdef HAVE_OPENR2
06199       if (p->mfcr2 && p->mfcr2call && openr2_chan_get_direction(p->r2chan) != OR2_DIR_STOPPED) {
06200          ast_log(LOG_DEBUG, "disconnecting MFC/R2 call on chan %d\n", p->channel);
06201          /* If it's an incoming call, check the mfcr2_forced_release setting */
06202          if (openr2_chan_get_direction(p->r2chan) == OR2_DIR_BACKWARD && p->mfcr2_forced_release) {
06203             dahdi_r2_disconnect_call(p, OR2_CAUSE_FORCED_RELEASE);
06204          } else {
06205             const char *r2causestr = pbx_builtin_getvar_helper(ast, "MFCR2_CAUSE");
06206             int r2cause_user = r2causestr ? atoi(r2causestr) : 0;
06207             openr2_call_disconnect_cause_t r2cause = r2cause_user ? dahdi_ast_cause_to_r2_cause(r2cause_user)
06208                                                              : dahdi_ast_cause_to_r2_cause(ast->hangupcause);
06209             dahdi_r2_disconnect_call(p, r2cause);
06210          }
06211       } else if (p->mfcr2call) {
06212          ast_log(LOG_DEBUG, "Clearing call request on channel %d\n", p->channel);
06213          /* since ast_request() was called but not ast_call() we have not yet dialed
06214          and the openr2 stack will not call on_call_end callback, we need to unset
06215          the mfcr2call flag and bump the monitor count so the monitor thread can take
06216          care of this channel events from now on */
06217          p->mfcr2call = 0;
06218       }
06219 #endif
06220       switch (p->sig) {
06221       case SIG_SS7:
06222       case SIG_MFCR2:
06223       case SIG_PRI_LIB_HANDLE_CASES:
06224       case 0:
06225          break;
06226       default:
06227          res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
06228          break;
06229       }
06230       if (res < 0) {
06231          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
06232       }
06233       switch (p->sig) {
06234       case SIG_FXOGS:
06235       case SIG_FXOLS:
06236       case SIG_FXOKS:
06237          memset(&par, 0, sizeof(par));
06238          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
06239          if (!res) {
06240             struct analog_pvt *analog_p = p->sig_pvt;
06241 #if 0
06242             ast_debug(1, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
06243 #endif
06244             /* If they're off hook, try playing congestion */
06245             if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
06246                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
06247             else
06248                tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06249             analog_p->fxsoffhookstate = par.rxisoffhook;
06250          }
06251          break;
06252       case SIG_FXSGS:
06253       case SIG_FXSLS:
06254       case SIG_FXSKS:
06255          /* Make sure we're not made available for at least two seconds assuming
06256          we were actually used for an inbound or outbound call. */
06257          if (ast->_state != AST_STATE_RESERVED) {
06258             time(&p->guardtime);
06259             p->guardtime += 2;
06260          }
06261          break;
06262       default:
06263          tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06264       }
06265       if (p->sig)
06266          dahdi_disable_ec(p);
06267       x = 0;
06268       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
06269       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
06270       p->didtdd = 0;
06271       p->callwaitcas = 0;
06272       p->callwaiting = p->permcallwaiting;
06273       p->hidecallerid = p->permhidecallerid;
06274       p->waitingfordt.tv_sec = 0;
06275       p->dialing = 0;
06276       p->rdnis[0] = '\0';
06277       update_conf(p);
06278       reset_conf(p);
06279       /* Restore data mode */
06280       switch (p->sig) {
06281       case SIG_PRI_LIB_HANDLE_CASES:
06282       case SIG_SS7:
06283          x = 0;
06284          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
06285          break;
06286       default:
06287          break;
06288       }
06289       if (num_restart_pending == 0)
06290          restart_monitor();
06291    }
06292 
06293    p->callwaitingrepeat = 0;
06294    p->cidcwexpire = 0;
06295    p->oprmode = 0;
06296    ast->tech_pvt = NULL;
06297 hangup_out:
06298    if (p->cidspill)
06299       ast_free(p->cidspill);
06300    p->cidspill = NULL;
06301 
06302    ast_mutex_unlock(&p->lock);
06303    ast_module_unref(ast_module_info->self);
06304    ast_verb(3, "Hungup '%s'\n", ast->name);
06305 
06306    ast_mutex_lock(&iflock);
06307 
06308    if (p->restartpending) {
06309       num_restart_pending--;
06310    }
06311 
06312    if (p->destroy) {
06313       destroy_channel(p, 0);
06314    }
06315    ast_mutex_unlock(&iflock);
06316    return 0;
06317 }
06318 
06319 static int dahdi_answer(struct ast_channel *ast)
06320 {
06321    struct dahdi_pvt *p = ast->tech_pvt;
06322    int res = 0;
06323    int idx;
06324    ast_setstate(ast, AST_STATE_UP);/*! \todo XXX this is redundantly set by the analog and PRI submodules! */
06325    ast_mutex_lock(&p->lock);
06326    idx = dahdi_get_index(ast, p, 0);
06327    if (idx < 0)
06328       idx = SUB_REAL;
06329    /* nothing to do if a radio channel */
06330    if ((p->radio || (p->oprmode < 0))) {
06331       ast_mutex_unlock(&p->lock);
06332       return 0;
06333    }
06334 
06335    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
06336       res = analog_answer(p->sig_pvt, ast);
06337       ast_mutex_unlock(&p->lock);
06338       return res;
06339    }
06340 
06341    switch (p->sig) {
06342 #if defined(HAVE_PRI)
06343    case SIG_PRI_LIB_HANDLE_CASES:
06344       res = sig_pri_answer(p->sig_pvt, ast);
06345       break;
06346 #endif   /* defined(HAVE_PRI) */
06347 #if defined(HAVE_SS7)
06348    case SIG_SS7:
06349       res = sig_ss7_answer(p->sig_pvt, ast);
06350       break;
06351 #endif   /* defined(HAVE_SS7) */
06352 #ifdef HAVE_OPENR2
06353    case SIG_MFCR2:
06354       if (!p->mfcr2_call_accepted) {
06355          /* The call was not accepted on offer nor the user, so it must be accepted now before answering,
06356             openr2_chan_answer_call will be called when the callback on_call_accepted is executed */
06357          p->mfcr2_answer_pending = 1;
06358          if (p->mfcr2_charge_calls) {
06359             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge before answering on chan %d\n", p->channel);
06360             openr2_chan_accept_call(p->r2chan, OR2_CALL_WITH_CHARGE);
06361          } else {
06362             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge before answering on chan %d\n", p->channel);
06363             openr2_chan_accept_call(p->r2chan, OR2_CALL_NO_CHARGE);
06364          }
06365       } else {
06366          ast_log(LOG_DEBUG, "Answering MFC/R2 call on chan %d\n", p->channel);
06367          dahdi_r2_answer(p);
06368       }
06369       break;
06370 #endif
06371    case 0:
06372       ast_mutex_unlock(&p->lock);
06373       return 0;
06374    default:
06375       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
06376       res = -1;
06377       break;
06378    }
06379    ast_mutex_unlock(&p->lock);
06380    return res;
06381 }
06382 
06383 static void disable_dtmf_detect(struct dahdi_pvt *p)
06384 {
06385    int val = 0;
06386 
06387    p->ignoredtmf = 1;
06388 
06389    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06390 
06391    if (!p->hardwaredtmf && p->dsp) {
06392       p->dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
06393       ast_dsp_set_features(p->dsp, p->dsp_features);
06394    }
06395 }
06396 
06397 static void enable_dtmf_detect(struct dahdi_pvt *p)
06398 {
06399    int val = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
06400 
06401    if (p->channel == CHAN_PSEUDO)
06402       return;
06403 
06404    p->ignoredtmf = 0;
06405 
06406    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
06407 
06408    if (!p->hardwaredtmf && p->dsp) {
06409       p->dsp_features |= DSP_FEATURE_DIGIT_DETECT;
06410       ast_dsp_set_features(p->dsp, p->dsp_features);
06411    }
06412 }
06413 
06414 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
06415 {
06416    char *cp;
06417    struct dahdi_pvt *p = chan->tech_pvt;
06418 
06419    /* all supported options require data */
06420    if (!data || (*datalen < 1)) {
06421       errno = EINVAL;
06422       return -1;
06423    }
06424 
06425    switch (option) {
06426    case AST_OPTION_DIGIT_DETECT:
06427       cp = (char *) data;
06428       *cp = p->ignoredtmf ? 0 : 1;
06429       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06430       break;
06431    case AST_OPTION_FAX_DETECT:
06432       cp = (char *) data;
06433       *cp = (p->dsp_features & DSP_FEATURE_FAX_DETECT) ? 0 : 1;
06434       ast_debug(1, "Reporting fax tone detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
06435       break;
06436    case AST_OPTION_CC_AGENT_TYPE:
06437 #if defined(HAVE_PRI)
06438 #if defined(HAVE_PRI_CCSS)
06439       if (dahdi_sig_pri_lib_handles(p->sig)) {
06440          ast_copy_string((char *) data, dahdi_pri_cc_type, *datalen);
06441          break;
06442       }
06443 #endif   /* defined(HAVE_PRI_CCSS) */
06444 #endif   /* defined(HAVE_PRI) */
06445       return -1;
06446    default:
06447       return -1;
06448    }
06449 
06450    errno = 0;
06451 
06452    return 0;
06453 }
06454 
06455 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen)
06456 {
06457    char *cp;
06458    signed char *scp;
06459    int x;
06460    int idx;
06461    struct dahdi_pvt *p = chan->tech_pvt, *pp;
06462    struct oprmode *oprmode;
06463 
06464 
06465    /* all supported options require data */
06466    if (!data || (datalen < 1)) {
06467       errno = EINVAL;
06468       return -1;
06469    }
06470 
06471    switch (option) {
06472    case AST_OPTION_TXGAIN:
06473       scp = (signed char *) data;
06474       idx = dahdi_get_index(chan, p, 0);
06475       if (idx < 0) {
06476          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
06477          return -1;
06478       }
06479       ast_debug(1, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
06480       return set_actual_txgain(p->subs[idx].dfd, p->txgain + (float) *scp, p->txdrc, p->law);
06481    case AST_OPTION_RXGAIN:
06482       scp = (signed char *) data;
06483       idx = dahdi_get_index(chan, p, 0);
06484       if (idx < 0) {
06485          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
06486          return -1;
06487       }
06488       ast_debug(1, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
06489       return set_actual_rxgain(p->subs[idx].dfd, p->rxgain + (float) *scp, p->rxdrc, p->law);
06490    case AST_OPTION_TONE_VERIFY:
06491       if (!p->dsp)
06492          break;
06493       cp = (char *) data;
06494       switch (*cp) {
06495       case 1:
06496          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
06497          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
06498          break;
06499       case 2:
06500          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
06501          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
06502          break;
06503       default:
06504          ast_debug(1, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
06505          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
06506          break;
06507       }
06508       break;
06509    case AST_OPTION_TDD:
06510       /* turn on or off TDD */
06511       cp = (char *) data;
06512       p->mate = 0;
06513       if (!*cp) { /* turn it off */
06514          ast_debug(1, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
06515          if (p->tdd)
06516             tdd_free(p->tdd);
06517          p->tdd = 0;
06518          break;
06519       }
06520       ast_debug(1, "Set option TDD MODE, value: %s(%d) on %s\n",
06521          (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
06522       dahdi_disable_ec(p);
06523       /* otherwise, turn it on */
06524       if (!p->didtdd) { /* if havent done it yet */
06525          unsigned char mybuf[41000];/*! \todo XXX This is an abuse of the stack!! */
06526          unsigned char *buf;
06527          int size, res, fd, len;
06528          struct pollfd fds[1];
06529 
06530          buf = mybuf;
06531          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
06532          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
06533          len = 40000;
06534          idx = dahdi_get_index(chan, p, 0);
06535          if (idx < 0) {
06536             ast_log(LOG_WARNING, "No index in TDD?\n");
06537             return -1;
06538          }
06539          fd = p->subs[idx].dfd;
06540          while (len) {
06541             if (ast_check_hangup(chan))
06542                return -1;
06543             size = len;
06544             if (size > READ_SIZE)
06545                size = READ_SIZE;
06546             fds[0].fd = fd;
06547             fds[0].events = POLLPRI | POLLOUT;
06548             fds[0].revents = 0;
06549             res = poll(fds, 1, -1);
06550             if (!res) {
06551                ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
06552                continue;
06553             }
06554             /* if got exception */
06555             if (fds[0].revents & POLLPRI)
06556                return -1;
06557             if (!(fds[0].revents & POLLOUT)) {
06558                ast_debug(1, "write fd not ready on channel %d\n", p->channel);
06559                continue;
06560             }
06561             res = write(fd, buf, size);
06562             if (res != size) {
06563                if (res == -1) return -1;
06564                ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
06565                break;
06566             }
06567             len -= size;
06568             buf += size;
06569          }
06570          p->didtdd = 1; /* set to have done it now */
06571       }
06572       if (*cp == 2) { /* Mate mode */
06573          if (p->tdd)
06574             tdd_free(p->tdd);
06575          p->tdd = 0;
06576          p->mate = 1;
06577          break;
06578       }
06579       if (!p->tdd) { /* if we don't have one yet */
06580          p->tdd = tdd_new(); /* allocate one */
06581       }
06582       break;
06583    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
06584       if (!p->dsp)
06585          break;
06586       cp = (char *) data;
06587       ast_debug(1, "Set option RELAX DTMF, value: %s(%d) on %s\n",
06588          *cp ? "ON" : "OFF", (int) *cp, chan->name);
06589       ast_dsp_set_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
06590       break;
06591    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
06592 #if defined(HAVE_PRI)
06593       if (dahdi_sig_pri_lib_handles(p->sig)
06594          && ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
06595          /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
06596          break;
06597       }
06598 #endif   /* defined(HAVE_PRI) */
06599 
06600       cp = (char *) data;
06601       if (!*cp) {
06602          ast_debug(1, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
06603          x = 0;
06604          dahdi_disable_ec(p);
06605       } else {
06606          ast_debug(1, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
06607          x = 1;
06608       }
06609       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x) == -1)
06610          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", p->channel, x, strerror(errno));
06611       break;
06612    case AST_OPTION_OPRMODE:  /* Operator services mode */
06613       oprmode = (struct oprmode *) data;
06614       /* We don't support operator mode across technologies */
06615       if (strcasecmp(chan->tech->type, oprmode->peer->tech->type)) {
06616          ast_log(LOG_NOTICE, "Operator mode not supported on %s to %s calls.\n",
06617                chan->tech->type, oprmode->peer->tech->type);
06618          errno = EINVAL;
06619          return -1;
06620       }
06621       pp = oprmode->peer->tech_pvt;
06622       p->oprmode = pp->oprmode = 0;
06623       /* setup peers */
06624       p->oprpeer = pp;
06625       pp->oprpeer = p;
06626       /* setup modes, if any */
06627       if (oprmode->mode)
06628       {
06629          pp->oprmode = oprmode->mode;
06630          p->oprmode = -oprmode->mode;
06631       }
06632       ast_debug(1, "Set Operator Services mode, value: %d on %s/%s\n",
06633          oprmode->mode, chan->name,oprmode->peer->name);
06634       break;
06635    case AST_OPTION_ECHOCAN:
06636       cp = (char *) data;
06637       if (*cp) {
06638          ast_debug(1, "Enabling echo cancellation on %s\n", chan->name);
06639          dahdi_enable_ec(p);
06640       } else {
06641          ast_debug(1, "Disabling echo cancellation on %s\n", chan->name);
06642          dahdi_disable_ec(p);
06643       }
06644       break;
06645    case AST_OPTION_DIGIT_DETECT:
06646       cp = (char *) data;
06647       ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
06648       if (*cp) {
06649          enable_dtmf_detect(p);
06650       } else {
06651          disable_dtmf_detect(p);
06652       }
06653       break;
06654    case AST_OPTION_FAX_DETECT:
06655       cp = (char *) data;
06656       if (p->dsp) {
06657          ast_debug(1, "%sabling fax tone detection on %s\n", *cp ? "En" : "Dis", chan->name);
06658          if (*cp) {
06659             p->dsp_features |= DSP_FEATURE_FAX_DETECT;
06660          } else {
06661             p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
06662          }
06663          ast_dsp_set_features(p->dsp, p->dsp_features);
06664       }
06665       break;
06666    default:
06667       return -1;
06668    }
06669    errno = 0;
06670 
06671    return 0;
06672 }
06673 
06674 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
06675 {
06676    struct dahdi_pvt *p = chan->tech_pvt;
06677    int res = 0;
06678 
06679    if (!strcasecmp(data, "rxgain")) {
06680       ast_mutex_lock(&p->lock);
06681       snprintf(buf, len, "%f", p->rxgain);
06682       ast_mutex_unlock(&p->lock);
06683    } else if (!strcasecmp(data, "txgain")) {
06684       ast_mutex_lock(&p->lock);
06685       snprintf(buf, len, "%f", p->txgain);
06686       ast_mutex_unlock(&p->lock);
06687 #if defined(HAVE_PRI)
06688 #if defined(HAVE_PRI_REVERSE_CHARGE)
06689    } else if (!strcasecmp(data, "reversecharge")) {
06690       ast_mutex_lock(&p->lock);
06691       switch (p->sig) {
06692       case SIG_PRI_LIB_HANDLE_CASES:
06693          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->reverse_charging_indication);
06694          break;
06695       default:
06696          *buf = '\0';
06697          res = -1;
06698          break;
06699       }
06700       ast_mutex_unlock(&p->lock);
06701 #endif
06702 #if defined(HAVE_PRI_SETUP_KEYPAD)
06703    } else if (!strcasecmp(data, "keypad_digits")) {
06704       ast_mutex_lock(&p->lock);
06705       switch (p->sig) {
06706       case SIG_PRI_LIB_HANDLE_CASES:
06707          ast_copy_string(buf, ((struct sig_pri_chan *) p->sig_pvt)->keypad_digits,
06708             len);
06709          break;
06710       default:
06711          *buf = '\0';
06712          res = -1;
06713          break;
06714       }
06715       ast_mutex_unlock(&p->lock);
06716 #endif   /* defined(HAVE_PRI_SETUP_KEYPAD) */
06717    } else if (!strcasecmp(data, "no_media_path")) {
06718       ast_mutex_lock(&p->lock);
06719       switch (p->sig) {
06720       case SIG_PRI_LIB_HANDLE_CASES:
06721          /*
06722           * TRUE if the call is on hold or is call waiting because
06723           * there is no media path available.
06724           */
06725          snprintf(buf, len, "%d", ((struct sig_pri_chan *) p->sig_pvt)->no_b_channel);
06726          break;
06727       default:
06728          *buf = '\0';
06729          res = -1;
06730          break;
06731       }
06732       ast_mutex_unlock(&p->lock);
06733 #endif   /* defined(HAVE_PRI) */
06734    } else {
06735       *buf = '\0';
06736       res = -1;
06737    }
06738 
06739    return res;
06740 }
06741 
06742 
06743 static int parse_buffers_policy(const char *parse, int *num_buffers, int *policy)
06744 {
06745    int res;
06746    char policy_str[21] = "";
06747 
06748    if ((res = sscanf(parse, "%30d,%20s", num_buffers, policy_str)) != 2) {
06749       ast_log(LOG_WARNING, "Parsing buffer string '%s' failed.\n", parse);
06750       return 1;
06751    }
06752    if (*num_buffers < 0) {
06753       ast_log(LOG_WARNING, "Invalid buffer count given '%d'.\n", *num_buffers);
06754       return -1;
06755    }
06756    if (!strcasecmp(policy_str, "full")) {
06757       *policy = DAHDI_POLICY_WHEN_FULL;
06758    } else if (!strcasecmp(policy_str, "immediate")) {
06759       *policy = DAHDI_POLICY_IMMEDIATE;
06760 #if defined(HAVE_DAHDI_HALF_FULL)
06761    } else if (!strcasecmp(policy_str, "half")) {
06762       *policy = DAHDI_POLICY_HALF_FULL;
06763 #endif
06764    } else {
06765       ast_log(LOG_WARNING, "Invalid policy name given '%s'.\n", policy_str);
06766       return -1;
06767    }
06768 
06769    return 0;
06770 }
06771 
06772 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value)
06773 {
06774    struct dahdi_pvt *p = chan->tech_pvt;
06775    int res = 0;
06776 
06777    if (!strcasecmp(data, "buffers")) {
06778       int num_bufs, policy;
06779 
06780       if (!(parse_buffers_policy(value, &num_bufs, &policy))) {
06781          struct dahdi_bufferinfo bi = {
06782             .txbufpolicy = policy,
06783             .rxbufpolicy = policy,
06784             .bufsize = p->bufsize,
06785             .numbufs = num_bufs,
06786          };
06787          int bpres;
06788 
06789          if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
06790             ast_log(LOG_WARNING, "Channel '%d' unable to override buffer policy: %s\n", p->channel, strerror(errno));
06791          } else {
06792             p->bufferoverrideinuse = 1;
06793          }
06794       } else {
06795          res = -1;
06796       }
06797    } else if (!strcasecmp(data, "echocan_mode")) {
06798       if (!strcasecmp(value, "on")) {
06799          ast_mutex_lock(&p->lock);
06800          dahdi_enable_ec(p);
06801          ast_mutex_unlock(&p->lock);
06802       } else if (!strcasecmp(value, "off")) {
06803          ast_mutex_lock(&p->lock);
06804          dahdi_disable_ec(p);
06805          ast_mutex_unlock(&p->lock);
06806 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
06807       } else if (!strcasecmp(value, "fax")) {
06808          int blah = 1;
06809 
06810          ast_mutex_lock(&p->lock);
06811          if (!p->echocanon) {
06812             dahdi_enable_ec(p);
06813          }
06814          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
06815             ast_log(LOG_WARNING, "Unable to place echocan into fax mode on channel %d: %s\n", p->channel, strerror(errno));
06816          }
06817          ast_mutex_unlock(&p->lock);
06818       } else if (!strcasecmp(value, "voice")) {
06819          int blah = 0;
06820 
06821          ast_mutex_lock(&p->lock);
06822          if (!p->echocanon) {
06823             dahdi_enable_ec(p);
06824          }
06825          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_FAX_MODE, &blah)) {
06826             ast_log(LOG_WARNING, "Unable to place echocan into voice mode on channel %d: %s\n", p->channel, strerror(errno));
06827          }
06828          ast_mutex_unlock(&p->lock);
06829 #endif
06830       } else {
06831          ast_log(LOG_WARNING, "Unsupported value '%s' provided for '%s' item.\n", value, data);
06832          res = -1;
06833       }
06834    } else {
06835       res = -1;
06836    }
06837 
06838    return res;
06839 }
06840 
06841 static void dahdi_unlink(struct dahdi_pvt *slave, struct dahdi_pvt *master, int needlock)
06842 {
06843    /* Unlink a specific slave or all slaves/masters from a given master */
06844    int x;
06845    int hasslaves;
06846    if (!master)
06847       return;
06848    if (needlock) {
06849       ast_mutex_lock(&master->lock);
06850       if (slave) {
06851          while (ast_mutex_trylock(&slave->lock)) {
06852             DEADLOCK_AVOIDANCE(&master->lock);
06853          }
06854       }
06855    }
06856    hasslaves = 0;
06857    for (x = 0; x < MAX_SLAVES; x++) {
06858       if (master->slaves[x]) {
06859          if (!slave || (master->slaves[x] == slave)) {
06860             /* Take slave out of the conference */
06861             ast_debug(1, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
06862             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
06863             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
06864             master->slaves[x]->master = NULL;
06865             master->slaves[x] = NULL;
06866          } else
06867             hasslaves = 1;
06868       }
06869       if (!hasslaves)
06870          master->inconference = 0;
06871    }
06872    if (!slave) {
06873       if (master->master) {
06874          /* Take master out of the conference */
06875          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
06876          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
06877          hasslaves = 0;
06878          for (x = 0; x < MAX_SLAVES; x++) {
06879             if (master->master->slaves[x] == master)
06880                master->master->slaves[x] = NULL;
06881             else if (master->master->slaves[x])
06882                hasslaves = 1;
06883          }
06884          if (!hasslaves)
06885             master->master->inconference = 0;
06886       }
06887       master->master = NULL;
06888    }
06889    update_conf(master);
06890    if (needlock) {
06891       if (slave)
06892          ast_mutex_unlock(&slave->lock);
06893       ast_mutex_unlock(&master->lock);
06894    }
06895 }
06896 
06897 static void dahdi_link(struct dahdi_pvt *slave, struct dahdi_pvt *master) {
06898    int x;
06899    if (!slave || !master) {
06900       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
06901       return;
06902    }
06903    for (x = 0; x < MAX_SLAVES; x++) {
06904       if (!master->slaves[x]) {
06905          master->slaves[x] = slave;
06906          break;
06907       }
06908    }
06909    if (x >= MAX_SLAVES) {
06910       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
06911       master->slaves[MAX_SLAVES - 1] = slave;
06912    }
06913    if (slave->master)
06914       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
06915    slave->master = master;
06916 
06917    ast_debug(1, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
06918 }
06919 
06920 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)
06921 {
06922    struct ast_channel *who;
06923    struct dahdi_pvt *p0, *p1, *op0, *op1;
06924    struct dahdi_pvt *master = NULL, *slave = NULL;
06925    struct ast_frame *f;
06926    int inconf = 0;
06927    int nothingok = 1;
06928    int ofd0, ofd1;
06929    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
06930    int os0 = -1, os1 = -1;
06931    int priority = 0;
06932    struct ast_channel *oc0, *oc1;
06933    enum ast_bridge_result res;
06934 #ifdef PRI_2BCT
06935    int triedtopribridge = 0;
06936    q931_call *q931c0;
06937    q931_call *q931c1;
06938 #endif
06939 
06940    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
06941       There is code below to handle it properly until DTMF is actually seen,
06942       but due to currently unresolved issues it's ignored...
06943    */
06944 
06945    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
06946       return AST_BRIDGE_FAILED_NOWARN;
06947 
06948    ast_channel_lock(c0);
06949    while (ast_channel_trylock(c1)) {
06950       CHANNEL_DEADLOCK_AVOIDANCE(c0);
06951    }
06952 
06953    p0 = c0->tech_pvt;
06954    p1 = c1->tech_pvt;
06955    /* cant do pseudo-channels here */
06956    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
06957       ast_channel_unlock(c0);
06958       ast_channel_unlock(c1);
06959       return AST_BRIDGE_FAILED_NOWARN;
06960    }
06961 
06962    oi0 = dahdi_get_index(c0, p0, 0);
06963    oi1 = dahdi_get_index(c1, p1, 0);
06964    if ((oi0 < 0) || (oi1 < 0)) {
06965       ast_channel_unlock(c0);
06966       ast_channel_unlock(c1);
06967       return AST_BRIDGE_FAILED;
06968    }
06969 
06970    op0 = p0 = c0->tech_pvt;
06971    op1 = p1 = c1->tech_pvt;
06972    ofd0 = c0->fds[0];
06973    ofd1 = c1->fds[0];
06974    oc0 = p0->owner;
06975    oc1 = p1->owner;
06976 
06977    if (ast_mutex_trylock(&p0->lock)) {
06978       /* Don't block, due to potential for deadlock */
06979       ast_channel_unlock(c0);
06980       ast_channel_unlock(c1);
06981       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
06982       return AST_BRIDGE_RETRY;
06983    }
06984    if (ast_mutex_trylock(&p1->lock)) {
06985       /* Don't block, due to potential for deadlock */
06986       ast_mutex_unlock(&p0->lock);
06987       ast_channel_unlock(c0);
06988       ast_channel_unlock(c1);
06989       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
06990       return AST_BRIDGE_RETRY;
06991    }
06992 
06993 #if defined(HAVE_PRI)
06994    if ((dahdi_sig_pri_lib_handles(p0->sig)
06995          && ((struct sig_pri_chan *) p0->sig_pvt)->no_b_channel)
06996       || (dahdi_sig_pri_lib_handles(p1->sig)
06997          && ((struct sig_pri_chan *) p1->sig_pvt)->no_b_channel)) {
06998       /*
06999        * PRI nobch channels (hold and call waiting) are equivalent to
07000        * pseudo channels and cannot be done here.
07001        */
07002       ast_mutex_unlock(&p0->lock);
07003       ast_mutex_unlock(&p1->lock);
07004       ast_channel_unlock(c0);
07005       ast_channel_unlock(c1);
07006       return AST_BRIDGE_FAILED_NOWARN;
07007    }
07008 #endif   /* defined(HAVE_PRI) */
07009 
07010    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07011       if (p0->owner && p1->owner) {
07012          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
07013          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
07014             master = p0;
07015             slave = p1;
07016             inconf = 1;
07017          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
07018             master = p1;
07019             slave = p0;
07020             inconf = 1;
07021          } else {
07022             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
07023             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
07024                p0->channel,
07025                oi0, (p0->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07026                p0->subs[SUB_REAL].inthreeway, p0->channel,
07027                oi0, (p1->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
07028                p1->subs[SUB_REAL].inthreeway);
07029          }
07030          nothingok = 0;
07031       }
07032    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
07033       if (p1->subs[SUB_THREEWAY].inthreeway) {
07034          master = p1;
07035          slave = p0;
07036          nothingok = 0;
07037       }
07038    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
07039       if (p0->subs[SUB_THREEWAY].inthreeway) {
07040          master = p0;
07041          slave = p1;
07042          nothingok = 0;
07043       }
07044    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
07045       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise,
07046          don't put us in anything */
07047       if (p1->subs[SUB_CALLWAIT].inthreeway) {
07048          master = p1;
07049          slave = p0;
07050          nothingok = 0;
07051       }
07052    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
07053       /* Same as previous */
07054       if (p0->subs[SUB_CALLWAIT].inthreeway) {
07055          master = p0;
07056          slave = p1;
07057          nothingok = 0;
07058       }
07059    }
07060    ast_debug(1, "master: %d, slave: %d, nothingok: %d\n",
07061       master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
07062    if (master && slave) {
07063       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
07064          in an active threeway call with a channel that is ringing, we should
07065          indicate ringing. */
07066       if ((oi1 == SUB_THREEWAY) &&
07067          p1->subs[SUB_THREEWAY].inthreeway &&
07068          p1->subs[SUB_REAL].owner &&
07069          p1->subs[SUB_REAL].inthreeway &&
07070          (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07071          ast_debug(1, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
07072          tone_zone_play_tone(p0->subs[oi0].dfd, DAHDI_TONE_RINGTONE);
07073          os1 = p1->subs[SUB_REAL].owner->_state;
07074       } else {
07075          ast_debug(1, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
07076          tone_zone_play_tone(p0->subs[oi0].dfd, -1);
07077       }
07078       if ((oi0 == SUB_THREEWAY) &&
07079          p0->subs[SUB_THREEWAY].inthreeway &&
07080          p0->subs[SUB_REAL].owner &&
07081          p0->subs[SUB_REAL].inthreeway &&
07082          (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
07083          ast_debug(1, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
07084          tone_zone_play_tone(p1->subs[oi1].dfd, DAHDI_TONE_RINGTONE);
07085          os0 = p0->subs[SUB_REAL].owner->_state;
07086       } else {
07087          ast_debug(1, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
07088          tone_zone_play_tone(p1->subs[oi0].dfd, -1);
07089       }
07090       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
07091          if (!p0->echocanbridged || !p1->echocanbridged) {
07092             /* Disable echo cancellation if appropriate */
07093             dahdi_disable_ec(p0);
07094             dahdi_disable_ec(p1);
07095          }
07096       }
07097       dahdi_link(slave, master);
07098       master->inconference = inconf;
07099    } else if (!nothingok)
07100       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
07101 
07102    update_conf(p0);
07103    update_conf(p1);
07104    t0 = p0->subs[SUB_REAL].inthreeway;
07105    t1 = p1->subs[SUB_REAL].inthreeway;
07106 
07107    ast_mutex_unlock(&p0->lock);
07108    ast_mutex_unlock(&p1->lock);
07109 
07110    ast_channel_unlock(c0);
07111    ast_channel_unlock(c1);
07112 
07113    /* Native bridge failed */
07114    if ((!master || !slave) && !nothingok) {
07115       dahdi_enable_ec(p0);
07116       dahdi_enable_ec(p1);
07117       return AST_BRIDGE_FAILED;
07118    }
07119 
07120    ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
07121 
07122    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07123       disable_dtmf_detect(op0);
07124 
07125    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07126       disable_dtmf_detect(op1);
07127 
07128    for (;;) {
07129       struct ast_channel *c0_priority[2] = {c0, c1};
07130       struct ast_channel *c1_priority[2] = {c1, c0};
07131 
07132       /* Here's our main loop...  Start by locking things, looking for private parts,
07133          and then balking if anything is wrong */
07134 
07135       ast_channel_lock(c0);
07136       while (ast_channel_trylock(c1)) {
07137          CHANNEL_DEADLOCK_AVOIDANCE(c0);
07138       }
07139 
07140       p0 = c0->tech_pvt;
07141       p1 = c1->tech_pvt;
07142 
07143       if (op0 == p0)
07144          i0 = dahdi_get_index(c0, p0, 1);
07145       if (op1 == p1)
07146          i1 = dahdi_get_index(c1, p1, 1);
07147 
07148       ast_channel_unlock(c0);
07149       ast_channel_unlock(c1);
07150 
07151       if (!timeoutms ||
07152          (op0 != p0) ||
07153          (op1 != p1) ||
07154          (ofd0 != c0->fds[0]) ||
07155          (ofd1 != c1->fds[0]) ||
07156          (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
07157          (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
07158          (oc0 != p0->owner) ||
07159          (oc1 != p1->owner) ||
07160          (t0 != p0->subs[SUB_REAL].inthreeway) ||
07161          (t1 != p1->subs[SUB_REAL].inthreeway) ||
07162          (oi0 != i0) ||
07163          (oi1 != i1)) {
07164          ast_debug(1, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
07165             op0->channel, oi0, op1->channel, oi1);
07166          res = AST_BRIDGE_RETRY;
07167          goto return_from_bridge;
07168       }
07169 
07170 #ifdef PRI_2BCT
07171       if (!triedtopribridge) {
07172          triedtopribridge = 1;
07173          if (p0->pri && p0->pri == p1->pri && p0->pri->transfer) {
07174             ast_mutex_lock(&p0->pri->lock);
07175             switch (p0->sig) {
07176             case SIG_PRI_LIB_HANDLE_CASES:
07177                q931c0 = ((struct sig_pri_chan *) (p0->sig_pvt))->call;
07178                break;
07179             default:
07180                q931c0 = NULL;
07181                break;
07182             }
07183             switch (p1->sig) {
07184             case SIG_PRI_LIB_HANDLE_CASES:
07185                q931c1 = ((struct sig_pri_chan *) (p1->sig_pvt))->call;
07186                break;
07187             default:
07188                q931c1 = NULL;
07189                break;
07190             }
07191             if (q931c0 && q931c1) {
07192                pri_channel_bridge(q931c0, q931c1);
07193             }
07194             ast_mutex_unlock(&p0->pri->lock);
07195          }
07196       }
07197 #endif
07198 
07199       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
07200       if (!who) {
07201          ast_debug(1, "Ooh, empty read...\n");
07202          continue;
07203       }
07204       f = ast_read(who);
07205       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
07206          *fo = f;
07207          *rc = who;
07208          res = AST_BRIDGE_COMPLETE;
07209          goto return_from_bridge;
07210       }
07211       if (f->frametype == AST_FRAME_DTMF) {
07212          if ((who == c0) && p0->pulsedial) {
07213             ast_write(c1, f);
07214          } else if ((who == c1) && p1->pulsedial) {
07215             ast_write(c0, f);
07216          } else {
07217             *fo = f;
07218             *rc = who;
07219             res = AST_BRIDGE_COMPLETE;
07220             goto return_from_bridge;
07221          }
07222       }
07223       ast_frfree(f);
07224 
07225       /* Swap who gets priority */
07226       priority = !priority;
07227    }
07228 
07229 return_from_bridge:
07230    if (op0 == p0)
07231       dahdi_enable_ec(p0);
07232 
07233    if (op1 == p1)
07234       dahdi_enable_ec(p1);
07235 
07236    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
07237       enable_dtmf_detect(op0);
07238 
07239    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
07240       enable_dtmf_detect(op1);
07241 
07242    dahdi_unlink(slave, master, 1);
07243 
07244    return res;
07245 }
07246 
07247 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07248 {
07249    struct dahdi_pvt *p = newchan->tech_pvt;
07250    int x;
07251 
07252    ast_mutex_lock(&p->lock);
07253 
07254    ast_debug(1, "New owner for channel %d is %s\n", p->channel, newchan->name);
07255    if (p->owner == oldchan) {
07256       p->owner = newchan;
07257    }
07258    for (x = 0; x < 3; x++) {
07259       if (p->subs[x].owner == oldchan) {
07260          if (!x) {
07261             dahdi_unlink(NULL, p, 0);
07262          }
07263          p->subs[x].owner = newchan;
07264       }
07265    }
07266    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
07267       analog_fixup(oldchan, newchan, p->sig_pvt);
07268 #if defined(HAVE_PRI)
07269    } else if (dahdi_sig_pri_lib_handles(p->sig)) {
07270       sig_pri_fixup(oldchan, newchan, p->sig_pvt);
07271 #endif   /* defined(HAVE_PRI) */
07272 #if defined(HAVE_SS7)
07273    } else if (p->sig == SIG_SS7) {
07274       sig_ss7_fixup(oldchan, newchan, p->sig_pvt);
07275 #endif   /* defined(HAVE_SS7) */
07276    }
07277    update_conf(p);
07278 
07279    ast_mutex_unlock(&p->lock);
07280 
07281    if (newchan->_state == AST_STATE_RINGING) {
07282       dahdi_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
07283    }
07284    return 0;
07285 }
07286 
07287 static int dahdi_ring_phone(struct dahdi_pvt *p)
07288 {
07289    int x;
07290    int res;
07291    /* Make sure our transmit state is on hook */
07292    x = 0;
07293    x = DAHDI_ONHOOK;
07294    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07295    do {
07296       x = DAHDI_RING;
07297       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07298       if (res) {
07299          switch (errno) {
07300          case EBUSY:
07301          case EINTR:
07302             /* Wait just in case */
07303             usleep(10000);
07304             continue;
07305          case EINPROGRESS:
07306             res = 0;
07307             break;
07308          default:
07309             ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
07310             res = 0;
07311          }
07312       }
07313    } while (res);
07314    return res;
07315 }
07316 
07317 static void *analog_ss_thread(void *data);
07318 
07319 static int attempt_transfer(struct dahdi_pvt *p)
07320 {
07321    /* In order to transfer, we need at least one of the channels to
07322       actually be in a call bridge.  We can't conference two applications
07323       together (but then, why would we want to?) */
07324    if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
07325       /* The three-way person we're about to transfer to could still be in MOH, so
07326          stop if now if appropriate */
07327       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
07328          ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
07329       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
07330          ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
07331       }
07332       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
07333          tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, DAHDI_TONE_RINGTONE);
07334       }
07335        if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
07336          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07337                ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
07338          return -1;
07339       }
07340       /* Orphan the channel after releasing the lock */
07341       ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07342       unalloc_sub(p, SUB_THREEWAY);
07343    } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
07344       ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
07345       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
07346          ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
07347       }
07348       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
07349          tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
07350       }
07351       if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
07352          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
07353                ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
07354          return -1;
07355       }
07356       /* Three-way is now the REAL */
07357       swap_subs(p, SUB_THREEWAY, SUB_REAL);
07358       ast_channel_unlock(p->subs[SUB_REAL].owner);
07359       unalloc_sub(p, SUB_THREEWAY);
07360       /* Tell the caller not to hangup */
07361       return 1;
07362    } else {
07363       ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
07364          p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
07365       p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07366       return -1;
07367    }
07368    return 0;
07369 }
07370 
07371 static int check_for_conference(struct dahdi_pvt *p)
07372 {
07373    struct dahdi_confinfo ci;
07374    /* Fine if we already have a master, etc */
07375    if (p->master || (p->confno > -1))
07376       return 0;
07377    memset(&ci, 0, sizeof(ci));
07378    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
07379       ast_log(LOG_WARNING, "Failed to get conference info on channel %d: %s\n", p->channel, strerror(errno));
07380       return 0;
07381    }
07382    /* If we have no master and don't have a confno, then
07383       if we're in a conference, it's probably a MeetMe room or
07384       some such, so don't let us 3-way out! */
07385    if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
07386       ast_verb(3, "Avoiding 3-way call when in an external conference\n");
07387       return 1;
07388    }
07389    return 0;
07390 }
07391 
07392 /*! Checks channel for alarms
07393  * \param p a channel to check for alarms.
07394  * \returns the alarms on the span to which the channel belongs, or alarms on
07395  *          the channel if no span alarms.
07396  */
07397 static int get_alarms(struct dahdi_pvt *p)
07398 {
07399    int res;
07400    struct dahdi_spaninfo zi;
07401    struct dahdi_params params;
07402 
07403    memset(&zi, 0, sizeof(zi));
07404    zi.spanno = p->span;
07405 
07406    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SPANSTAT, &zi)) >= 0) {
07407       if (zi.alarms != DAHDI_ALARM_NONE)
07408          return zi.alarms;
07409    } else {
07410       ast_log(LOG_WARNING, "Unable to determine alarm on channel %d: %s\n", p->channel, strerror(errno));
07411       return 0;
07412    }
07413 
07414    /* No alarms on the span. Check for channel alarms. */
07415    memset(&params, 0, sizeof(params));
07416    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &params)) >= 0)
07417       return params.chan_alarms;
07418 
07419    ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
07420 
07421    return DAHDI_ALARM_NONE;
07422 }
07423 
07424 static void dahdi_handle_dtmfup(struct ast_channel *ast, int idx, struct ast_frame **dest)
07425 {
07426    struct dahdi_pvt *p = ast->tech_pvt;
07427    struct ast_frame *f = *dest;
07428 
07429    ast_debug(1, "DTMF digit: %c on %s\n", (int) f->subclass.integer, ast->name);
07430 
07431    if (p->confirmanswer) {
07432       ast_debug(1, "Confirm answer on %s!\n", ast->name);
07433       /* Upon receiving a DTMF digit, consider this an answer confirmation instead
07434          of a DTMF digit */
07435       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07436       p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07437       *dest = &p->subs[idx].f;
07438       /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
07439       p->confirmanswer = 0;
07440    } else if (p->callwaitcas) {
07441       if ((f->subclass.integer == 'A') || (f->subclass.integer == 'D')) {
07442          ast_debug(1, "Got some DTMF, but it's for the CAS\n");
07443          if (p->cidspill)
07444             ast_free(p->cidspill);
07445          send_cwcidspill(p);
07446       }
07447       p->callwaitcas = 0;
07448       p->subs[idx].f.frametype = AST_FRAME_NULL;
07449       p->subs[idx].f.subclass.integer = 0;
07450       *dest = &p->subs[idx].f;
07451    } else if (f->subclass.integer == 'f') {
07452       /* Fax tone -- Handle and return NULL */
07453       if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
07454          /* If faxbuffers are configured, use them for the fax transmission */
07455          if (p->usefaxbuffers && !p->bufferoverrideinuse) {
07456             struct dahdi_bufferinfo bi = {
07457                .txbufpolicy = p->faxbuf_policy,
07458                .bufsize = p->bufsize,
07459                .numbufs = p->faxbuf_no
07460             };
07461             int res;
07462 
07463             if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
07464                ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast->name, strerror(errno));
07465             } else {
07466                p->bufferoverrideinuse = 1;
07467             }
07468          }
07469          p->faxhandled = 1;
07470          if (p->dsp) {
07471             p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
07472             ast_dsp_set_features(p->dsp, p->dsp_features);
07473             ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast->name);
07474          }
07475          if (strcmp(ast->exten, "fax")) {
07476             const char *target_context = S_OR(ast->macrocontext, ast->context);
07477 
07478             /* We need to unlock 'ast' here because ast_exists_extension has the
07479              * potential to start autoservice on the channel. Such action is prone
07480              * to deadlock.
07481              */
07482             ast_mutex_unlock(&p->lock);
07483             ast_channel_unlock(ast);
07484             if (ast_exists_extension(ast, target_context, "fax", 1,
07485                S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07486                ast_channel_lock(ast);
07487                ast_mutex_lock(&p->lock);
07488                ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
07489                /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
07490                pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07491                if (ast_async_goto(ast, target_context, "fax", 1))
07492                   ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07493             } else {
07494                ast_channel_lock(ast);
07495                ast_mutex_lock(&p->lock);
07496                ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
07497             }
07498          } else {
07499             ast_debug(1, "Already in a fax extension, not redirecting\n");
07500          }
07501       } else {
07502          ast_debug(1, "Fax already handled\n");
07503       }
07504       dahdi_confmute(p, 0);
07505       p->subs[idx].f.frametype = AST_FRAME_NULL;
07506       p->subs[idx].f.subclass.integer = 0;
07507       *dest = &p->subs[idx].f;
07508    }
07509 }
07510 
07511 static void handle_alarms(struct dahdi_pvt *p, int alms)
07512 {
07513    const char *alarm_str = alarm2str(alms);
07514 
07515    if (report_alarms & REPORT_CHANNEL_ALARMS) {
07516       ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm_str);
07517       manager_event(EVENT_FLAG_SYSTEM, "Alarm",
07518                  "Alarm: %s\r\n"
07519                  "Channel: %d\r\n",
07520                  alarm_str, p->channel);
07521    }
07522 
07523    if (report_alarms & REPORT_SPAN_ALARMS && p->manages_span_alarms) {
07524       ast_log(LOG_WARNING, "Detected alarm on span %d: %s\n", p->span, alarm_str);
07525       manager_event(EVENT_FLAG_SYSTEM, "SpanAlarm",
07526                  "Alarm: %s\r\n"
07527                  "Span: %d\r\n",
07528                  alarm_str, p->span);
07529    }
07530 }
07531 
07532 static struct ast_frame *dahdi_handle_event(struct ast_channel *ast)
07533 {
07534    int res, x;
07535    int idx, mysig;
07536    char *c;
07537    struct dahdi_pvt *p = ast->tech_pvt;
07538    pthread_t threadid;
07539    struct ast_channel *chan;
07540    struct ast_frame *f;
07541 
07542    idx = dahdi_get_index(ast, p, 0);
07543    mysig = p->sig;
07544    if (p->outsigmod > -1)
07545       mysig = p->outsigmod;
07546    p->subs[idx].f.frametype = AST_FRAME_NULL;
07547    p->subs[idx].f.subclass.integer = 0;
07548    p->subs[idx].f.datalen = 0;
07549    p->subs[idx].f.samples = 0;
07550    p->subs[idx].f.mallocd = 0;
07551    p->subs[idx].f.offset = 0;
07552    p->subs[idx].f.src = "dahdi_handle_event";
07553    p->subs[idx].f.data.ptr = NULL;
07554    f = &p->subs[idx].f;
07555 
07556    if (idx < 0)
07557       return &p->subs[idx].f;
07558    if (p->fake_event) {
07559       res = p->fake_event;
07560       p->fake_event = 0;
07561    } else
07562       res = dahdi_get_event(p->subs[idx].dfd);
07563 
07564    ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, idx);
07565 
07566    if (res & (DAHDI_EVENT_PULSEDIGIT | DAHDI_EVENT_DTMFUP)) {
07567       p->pulsedial = (res & DAHDI_EVENT_PULSEDIGIT) ? 1 : 0;
07568       ast_debug(1, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
07569 #if defined(HAVE_PRI)
07570       if (dahdi_sig_pri_lib_handles(p->sig)
07571          && !((struct sig_pri_chan *) p->sig_pvt)->proceeding
07572          && p->pri
07573          && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
07574          /* absorb event */
07575       } else
07576 #endif   /* defined(HAVE_PRI) */
07577       {
07578          dahdi_confmute(p, 0);
07579          p->subs[idx].f.frametype = AST_FRAME_DTMF_END;
07580          p->subs[idx].f.subclass.integer = res & 0xff;
07581       }
07582       dahdi_handle_dtmfup(ast, idx, &f);
07583       return f;
07584    }
07585 
07586    if (res & DAHDI_EVENT_DTMFDOWN) {
07587       ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
07588       /* Mute conference */
07589       dahdi_confmute(p, 1);
07590       p->subs[idx].f.frametype = AST_FRAME_DTMF_BEGIN;
07591       p->subs[idx].f.subclass.integer = res & 0xff;
07592       return &p->subs[idx].f;
07593    }
07594 
07595    switch (res) {
07596    case DAHDI_EVENT_EC_DISABLED:
07597       ast_verb(3, "Channel %d echo canceler disabled.\n", p->channel);
07598       p->echocanon = 0;
07599       break;
07600 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
07601    case DAHDI_EVENT_TX_CED_DETECTED:
07602       ast_verb(3, "Channel %d detected a CED tone towards the network.\n", p->channel);
07603       break;
07604    case DAHDI_EVENT_RX_CED_DETECTED:
07605       ast_verb(3, "Channel %d detected a CED tone from the network.\n", p->channel);
07606       break;
07607    case DAHDI_EVENT_EC_NLP_DISABLED:
07608       ast_verb(3, "Channel %d echo canceler disabled its NLP.\n", p->channel);
07609       break;
07610    case DAHDI_EVENT_EC_NLP_ENABLED:
07611       ast_verb(3, "Channel %d echo canceler enabled its NLP.\n", p->channel);
07612       break;
07613 #endif
07614    case DAHDI_EVENT_BITSCHANGED:
07615 #ifdef HAVE_OPENR2
07616       if (p->sig != SIG_MFCR2) {
07617          ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07618       } else {
07619          ast_log(LOG_DEBUG, "bits changed in chan %d\n", p->channel);
07620          openr2_chan_handle_cas(p->r2chan);
07621       }
07622 #else
07623       ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
07624 #endif
07625    case DAHDI_EVENT_PULSE_START:
07626       /* Stop tone if there's a pulse start and the PBX isn't started */
07627       if (!ast->pbx)
07628          tone_zone_play_tone(p->subs[idx].dfd, -1);
07629       break;
07630    case DAHDI_EVENT_DIALCOMPLETE:
07631 #ifdef HAVE_OPENR2
07632       if ((p->sig & SIG_MFCR2) && p->r2chan && ast->_state != AST_STATE_UP) {
07633          /* we don't need to do anything for this event for R2 signaling
07634             if the call is being setup */
07635          break;
07636       }
07637 #endif
07638       if (p->inalarm) break;
07639       if ((p->radio || (p->oprmode < 0))) break;
07640       if (ioctl(p->subs[idx].dfd,DAHDI_DIALING,&x) == -1) {
07641          ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n",ast->name, strerror(errno));
07642          return NULL;
07643       }
07644       if (!x) { /* if not still dialing in driver */
07645          dahdi_enable_ec(p);
07646          if (p->echobreak) {
07647             dahdi_train_ec(p);
07648             ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
07649             p->dop.op = DAHDI_DIAL_OP_REPLACE;
07650             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
07651             p->echobreak = 0;
07652          } else {
07653             p->dialing = 0;
07654             if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
07655                /* if thru with dialing after offhook */
07656                if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
07657                   ast_setstate(ast, AST_STATE_UP);
07658                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07659                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07660                   break;
07661                } else { /* if to state wait for offhook to dial rest */
07662                   /* we now wait for off hook */
07663                   ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
07664                }
07665             }
07666             if (ast->_state == AST_STATE_DIALING) {
07667                if ((p->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
07668                   ast_debug(1, "Done dialing, but waiting for progress detection before doing more...\n");
07669                } else if (p->confirmanswer || (!p->dialednone
07670                   && ((mysig == SIG_EM) || (mysig == SIG_EM_E1)
07671                      || (mysig == SIG_EMWINK) || (mysig == SIG_FEATD)
07672                      || (mysig == SIG_FEATDMF_TA) || (mysig == SIG_FEATDMF)
07673                      || (mysig == SIG_E911) || (mysig == SIG_FGC_CAMA)
07674                      || (mysig == SIG_FGC_CAMAMF) || (mysig == SIG_FEATB)
07675                      || (mysig == SIG_SF) || (mysig == SIG_SFWINK)
07676                      || (mysig == SIG_SF_FEATD) || (mysig == SIG_SF_FEATDMF)
07677                      || (mysig == SIG_SF_FEATB)))) {
07678                   ast_setstate(ast, AST_STATE_RINGING);
07679                } else if (!p->answeronpolarityswitch) {
07680                   ast_setstate(ast, AST_STATE_UP);
07681                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07682                   p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07683                   /* If aops=0 and hops=1, this is necessary */
07684                   p->polarity = POLARITY_REV;
07685                } else {
07686                   /* Start clean, so we can catch the change to REV polarity when party answers */
07687                   p->polarity = POLARITY_IDLE;
07688                }
07689             }
07690          }
07691       }
07692       break;
07693    case DAHDI_EVENT_ALARM:
07694       switch (p->sig) {
07695 #if defined(HAVE_PRI)
07696       case SIG_PRI_LIB_HANDLE_CASES:
07697          sig_pri_chan_alarm_notify(p->sig_pvt, 0);
07698          break;
07699 #endif   /* defined(HAVE_PRI) */
07700 #if defined(HAVE_SS7)
07701       case SIG_SS7:
07702          sig_ss7_set_alarm(p->sig_pvt, 1);
07703          break;
07704 #endif   /* defined(HAVE_SS7) */
07705       default:
07706          p->inalarm = 1;
07707          break;
07708       }
07709       res = get_alarms(p);
07710       handle_alarms(p, res);
07711 #ifdef HAVE_PRI
07712       if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
07713          /* fall through intentionally */
07714       } else {
07715          break;
07716       }
07717 #endif
07718 #if defined(HAVE_SS7)
07719       if (p->sig == SIG_SS7)
07720          break;
07721 #endif   /* defined(HAVE_SS7) */
07722 #ifdef HAVE_OPENR2
07723       if (p->sig == SIG_MFCR2)
07724          break;
07725 #endif
07726    case DAHDI_EVENT_ONHOOK:
07727       if (p->radio) {
07728          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07729          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
07730          break;
07731       }
07732       if (p->oprmode < 0)
07733       {
07734          if (p->oprmode != -1) break;
07735          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
07736          {
07737             /* Make sure it starts ringing */
07738             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
07739             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RING);
07740             save_conference(p->oprpeer);
07741             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
07742          }
07743          break;
07744       }
07745       switch (p->sig) {
07746       case SIG_FXOLS:
07747       case SIG_FXOGS:
07748       case SIG_FXOKS:
07749          /* Check for some special conditions regarding call waiting */
07750          if (idx == SUB_REAL) {
07751             /* The normal line was hung up */
07752             if (p->subs[SUB_CALLWAIT].owner) {
07753                /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
07754                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
07755                ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
07756                unalloc_sub(p, SUB_CALLWAIT);
07757 #if 0
07758                p->subs[idx].needanswer = 0;
07759                p->subs[idx].needringing = 0;
07760 #endif
07761                p->callwaitingrepeat = 0;
07762                p->cidcwexpire = 0;
07763                p->owner = NULL;
07764                /* Don't start streaming audio yet if the incoming call isn't up yet */
07765                if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
07766                   p->dialing = 1;
07767                dahdi_ring_phone(p);
07768             } else if (p->subs[SUB_THREEWAY].owner) {
07769                unsigned int mssinceflash;
07770                /* Here we have to retain the lock on both the main channel, the 3-way channel, and
07771                   the private structure -- not especially easy or clean */
07772                while (p->subs[SUB_THREEWAY].owner && ast_channel_trylock(p->subs[SUB_THREEWAY].owner)) {
07773                   /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
07774                   DLA_UNLOCK(&p->lock);
07775                   CHANNEL_DEADLOCK_AVOIDANCE(ast);
07776                   /* We can grab ast and p in that order, without worry.  We should make sure
07777                      nothing seriously bad has happened though like some sort of bizarre double
07778                      masquerade! */
07779                   DLA_LOCK(&p->lock);
07780                   if (p->owner != ast) {
07781                      ast_log(LOG_WARNING, "This isn't good...\n");
07782                      return NULL;
07783                   }
07784                }
07785                if (!p->subs[SUB_THREEWAY].owner) {
07786                   ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
07787                   return NULL;
07788                }
07789                mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
07790                ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
07791                if (mssinceflash < MIN_MS_SINCE_FLASH) {
07792                   /* It hasn't been long enough since the last flashook.  This is probably a bounce on
07793                      hanging up.  Hangup both channels now */
07794                   if (p->subs[SUB_THREEWAY].owner)
07795                      ast_queue_hangup_with_cause(p->subs[SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
07796                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07797                   ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
07798                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07799                } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
07800                   if (p->transfer) {
07801                      /* In any case this isn't a threeway call anymore */
07802                      p->subs[SUB_REAL].inthreeway = 0;
07803                      p->subs[SUB_THREEWAY].inthreeway = 0;
07804                      /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
07805                      if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
07806                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07807                         /* Swap subs and dis-own channel */
07808                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
07809                         p->owner = NULL;
07810                         /* Ring the phone */
07811                         dahdi_ring_phone(p);
07812                      } else {
07813                         if ((res = attempt_transfer(p)) < 0) {
07814                            p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07815                            if (p->subs[SUB_THREEWAY].owner)
07816                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07817                         } else if (res) {
07818                            /* Don't actually hang up at this point */
07819                            if (p->subs[SUB_THREEWAY].owner)
07820                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07821                            break;
07822                         }
07823                      }
07824                   } else {
07825                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
07826                      if (p->subs[SUB_THREEWAY].owner)
07827                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07828                   }
07829                } else {
07830                   ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
07831                   /* Swap subs and dis-own channel */
07832                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
07833                   p->owner = NULL;
07834                   /* Ring the phone */
07835                   dahdi_ring_phone(p);
07836                }
07837             }
07838          } else {
07839             ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", idx);
07840          }
07841          /* Fall through */
07842       default:
07843          dahdi_disable_ec(p);
07844          return NULL;
07845       }
07846       break;
07847    case DAHDI_EVENT_RINGOFFHOOK:
07848       if (p->inalarm) break;
07849       if (p->oprmode < 0)
07850       {
07851          if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
07852          {
07853             /* Make sure it stops ringing */
07854             dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
07855             tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, -1);
07856             restore_conference(p->oprpeer);
07857          }
07858          break;
07859       }
07860       if (p->radio)
07861       {
07862          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07863          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
07864          break;
07865       }
07866       /* for E911, its supposed to wait for offhook then dial
07867          the second half of the dial string */
07868       if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
07869          c = strchr(p->dialdest, '/');
07870          if (c)
07871             c++;
07872          else
07873             c = p->dialdest;
07874          if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
07875          else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
07876          if (strlen(p->dop.dialstr) > 4) {
07877             memset(p->echorest, 'w', sizeof(p->echorest) - 1);
07878             strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
07879             p->echorest[sizeof(p->echorest) - 1] = '\0';
07880             p->echobreak = 1;
07881             p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
07882          } else
07883             p->echobreak = 0;
07884          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
07885             int saveerr = errno;
07886 
07887             x = DAHDI_ONHOOK;
07888             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
07889             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
07890             return NULL;
07891             }
07892          p->dialing = 1;
07893          return &p->subs[idx].f;
07894       }
07895       switch (p->sig) {
07896       case SIG_FXOLS:
07897       case SIG_FXOGS:
07898       case SIG_FXOKS:
07899          switch (ast->_state) {
07900          case AST_STATE_RINGING:
07901             dahdi_enable_ec(p);
07902             dahdi_train_ec(p);
07903             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07904             p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
07905             /* Make sure it stops ringing */
07906             p->subs[SUB_REAL].needringing = 0;
07907             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
07908             ast_debug(1, "channel %d answered\n", p->channel);
07909             if (p->cidspill) {
07910                /* Cancel any running CallerID spill */
07911                ast_free(p->cidspill);
07912                p->cidspill = NULL;
07913             }
07914             p->dialing = 0;
07915             p->callwaitcas = 0;
07916             if (p->confirmanswer) {
07917                /* Ignore answer if "confirm answer" is enabled */
07918                p->subs[idx].f.frametype = AST_FRAME_NULL;
07919                p->subs[idx].f.subclass.integer = 0;
07920             } else if (!ast_strlen_zero(p->dop.dialstr)) {
07921                /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
07922                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
07923                if (res < 0) {
07924                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
07925                   p->dop.dialstr[0] = '\0';
07926                   return NULL;
07927                } else {
07928                   ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
07929                   p->subs[idx].f.frametype = AST_FRAME_NULL;
07930                   p->subs[idx].f.subclass.integer = 0;
07931                   p->dialing = 1;
07932                }
07933                p->dop.dialstr[0] = '\0';
07934                ast_setstate(ast, AST_STATE_DIALING);
07935             } else
07936                ast_setstate(ast, AST_STATE_UP);
07937             return &p->subs[idx].f;
07938          case AST_STATE_DOWN:
07939             ast_setstate(ast, AST_STATE_RING);
07940             ast->rings = 1;
07941             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07942             p->subs[idx].f.subclass.integer = AST_CONTROL_OFFHOOK;
07943             ast_debug(1, "channel %d picked up\n", p->channel);
07944             return &p->subs[idx].f;
07945          case AST_STATE_UP:
07946             /* Make sure it stops ringing */
07947             dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
07948             /* Okay -- probably call waiting*/
07949             if (ast_bridged_channel(p->owner))
07950                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
07951             p->subs[idx].needunhold = 1;
07952             break;
07953          case AST_STATE_RESERVED:
07954             /* Start up dialtone */
07955             if (has_voicemail(p))
07956                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
07957             else
07958                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
07959             break;
07960          default:
07961             ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
07962          }
07963          break;
07964       case SIG_FXSLS:
07965       case SIG_FXSGS:
07966       case SIG_FXSKS:
07967          if (ast->_state == AST_STATE_RING) {
07968             p->ringt = p->ringt_base;
07969          }
07970 
07971          /* If we get a ring then we cannot be in
07972           * reversed polarity. So we reset to idle */
07973          ast_debug(1, "Setting IDLE polarity due "
07974             "to ring. Old polarity was %d\n",
07975             p->polarity);
07976          p->polarity = POLARITY_IDLE;
07977 
07978          /* Fall through */
07979       case SIG_EM:
07980       case SIG_EM_E1:
07981       case SIG_EMWINK:
07982       case SIG_FEATD:
07983       case SIG_FEATDMF:
07984       case SIG_FEATDMF_TA:
07985       case SIG_E911:
07986       case SIG_FGC_CAMA:
07987       case SIG_FGC_CAMAMF:
07988       case SIG_FEATB:
07989       case SIG_SF:
07990       case SIG_SFWINK:
07991       case SIG_SF_FEATD:
07992       case SIG_SF_FEATDMF:
07993       case SIG_SF_FEATB:
07994          if (ast->_state == AST_STATE_PRERING)
07995             ast_setstate(ast, AST_STATE_RING);
07996          if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
07997             ast_debug(1, "Ring detected\n");
07998             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07999             p->subs[idx].f.subclass.integer = AST_CONTROL_RING;
08000          } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
08001             ast_debug(1, "Line answered\n");
08002             if (p->confirmanswer) {
08003                p->subs[idx].f.frametype = AST_FRAME_NULL;
08004                p->subs[idx].f.subclass.integer = 0;
08005             } else {
08006                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08007                p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08008                ast_setstate(ast, AST_STATE_UP);
08009             }
08010          } else if (ast->_state != AST_STATE_RING)
08011             ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
08012          break;
08013       default:
08014          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08015       }
08016       break;
08017    case DAHDI_EVENT_RINGBEGIN:
08018       switch (p->sig) {
08019       case SIG_FXSLS:
08020       case SIG_FXSGS:
08021       case SIG_FXSKS:
08022          if (ast->_state == AST_STATE_RING) {
08023             p->ringt = p->ringt_base;
08024          }
08025          break;
08026       }
08027       break;
08028    case DAHDI_EVENT_RINGERON:
08029       break;
08030    case DAHDI_EVENT_NOALARM:
08031       switch (p->sig) {
08032 #if defined(HAVE_PRI)
08033       case SIG_PRI_LIB_HANDLE_CASES:
08034          sig_pri_chan_alarm_notify(p->sig_pvt, 1);
08035          break;
08036 #endif   /* defined(HAVE_PRI) */
08037 #if defined(HAVE_SS7)
08038       case SIG_SS7:
08039          sig_ss7_set_alarm(p->sig_pvt, 0);
08040          break;
08041 #endif   /* defined(HAVE_SS7) */
08042       default:
08043          p->inalarm = 0;
08044          break;
08045       }
08046       handle_clear_alarms(p);
08047       break;
08048    case DAHDI_EVENT_WINKFLASH:
08049       if (p->inalarm) break;
08050       if (p->radio) break;
08051       if (p->oprmode < 0) break;
08052       if (p->oprmode > 1)
08053       {
08054          struct dahdi_params par;
08055 
08056          memset(&par, 0, sizeof(par));
08057          if (ioctl(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par) != -1)
08058          {
08059             if (!par.rxisoffhook)
08060             {
08061                /* Make sure it stops ringing */
08062                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
08063                dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RING);
08064                save_conference(p);
08065                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08066             }
08067          }
08068          break;
08069       }
08070       /* Remember last time we got a flash-hook */
08071       p->flashtime = ast_tvnow();
08072       switch (mysig) {
08073       case SIG_FXOLS:
08074       case SIG_FXOGS:
08075       case SIG_FXOKS:
08076          ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
08077             idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
08078          p->callwaitcas = 0;
08079 
08080          if (idx != SUB_REAL) {
08081             ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", idx, p->channel);
08082             goto winkflashdone;
08083          }
08084 
08085          if (p->subs[SUB_CALLWAIT].owner) {
08086             /* Swap to call-wait */
08087             swap_subs(p, SUB_REAL, SUB_CALLWAIT);
08088             tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
08089             p->owner = p->subs[SUB_REAL].owner;
08090             ast_debug(1, "Making %s the new owner\n", p->owner->name);
08091             if (p->owner->_state == AST_STATE_RINGING) {
08092                ast_setstate(p->owner, AST_STATE_UP);
08093                p->subs[SUB_REAL].needanswer = 1;
08094             }
08095             p->callwaitingrepeat = 0;
08096             p->cidcwexpire = 0;
08097             /* Start music on hold if appropriate */
08098             if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
08099                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
08100                   S_OR(p->mohsuggest, NULL),
08101                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08102             }
08103             p->subs[SUB_CALLWAIT].needhold = 1;
08104             if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
08105                ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
08106                   S_OR(p->mohsuggest, NULL),
08107                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08108             }
08109             p->subs[SUB_REAL].needunhold = 1;
08110          } else if (!p->subs[SUB_THREEWAY].owner) {
08111             if (!p->threewaycalling) {
08112                /* Just send a flash if no 3-way calling */
08113                p->subs[SUB_REAL].needflash = 1;
08114                goto winkflashdone;
08115             } else if (!check_for_conference(p)) {
08116                char cid_num[256];
08117                char cid_name[256];
08118 
08119                cid_num[0] = 0;
08120                cid_name[0] = 0;
08121                if (p->dahditrcallerid && p->owner) {
08122                   if (p->owner->caller.id.number.valid
08123                      && p->owner->caller.id.number.str) {
08124                      ast_copy_string(cid_num, p->owner->caller.id.number.str,
08125                         sizeof(cid_num));
08126                   }
08127                   if (p->owner->caller.id.name.valid
08128                      && p->owner->caller.id.name.str) {
08129                      ast_copy_string(cid_name, p->owner->caller.id.name.str,
08130                         sizeof(cid_name));
08131                   }
08132                }
08133                /* XXX This section needs much more error checking!!! XXX */
08134                /* Start a 3-way call if feasible */
08135                if (!((ast->pbx) ||
08136                   (ast->_state == AST_STATE_UP) ||
08137                   (ast->_state == AST_STATE_RING))) {
08138                   ast_debug(1, "Flash when call not up or ringing\n");
08139                   goto winkflashdone;
08140                }
08141                if (alloc_sub(p, SUB_THREEWAY)) {
08142                   ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
08143                   goto winkflashdone;
08144                }
08145                /* Make new channel */
08146                chan = dahdi_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, NULL);
08147                if (p->dahditrcallerid) {
08148                   if (!p->origcid_num)
08149                      p->origcid_num = ast_strdup(p->cid_num);
08150                   if (!p->origcid_name)
08151                      p->origcid_name = ast_strdup(p->cid_name);
08152                   ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
08153                   ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
08154                }
08155                /* Swap things around between the three-way and real call */
08156                swap_subs(p, SUB_THREEWAY, SUB_REAL);
08157                /* Disable echo canceller for better dialing */
08158                dahdi_disable_ec(p);
08159                res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALRECALL);
08160                if (res)
08161                   ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
08162                p->owner = chan;
08163                if (!chan) {
08164                   ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
08165                } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
08166                   ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
08167                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
08168                   dahdi_enable_ec(p);
08169                   ast_hangup(chan);
08170                } else {
08171                   struct ast_channel *other = ast_bridged_channel(p->subs[SUB_THREEWAY].owner);
08172                   int way3bridge = 0, cdr3way = 0;
08173 
08174                      if (!other) {
08175                      other = ast_bridged_channel(p->subs[SUB_REAL].owner);
08176                   } else
08177                      way3bridge = 1;
08178 
08179                      if (p->subs[SUB_THREEWAY].owner->cdr)
08180                      cdr3way = 1;
08181 
08182                   ast_verb(3, "Started three way call on channel %d\n", p->channel);
08183 
08184                   /* Start music on hold if appropriate */
08185                   if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
08186                      ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
08187                         S_OR(p->mohsuggest, NULL),
08188                         !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
08189                   }
08190                   p->subs[SUB_THREEWAY].needhold = 1;
08191                }
08192             }
08193          } else {
08194             /* Already have a 3 way call */
08195             if (p->subs[SUB_THREEWAY].inthreeway) {
08196                /* Call is already up, drop the last person */
08197                ast_debug(1, "Got flash with three way call up, dropping last call on %d\n", p->channel);
08198                /* If the primary call isn't answered yet, use it */
08199                if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
08200                   /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
08201                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08202                   p->owner = p->subs[SUB_REAL].owner;
08203                }
08204                /* Drop the last call and stop the conference */
08205                ast_verb(3, "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
08206                p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08207                p->subs[SUB_REAL].inthreeway = 0;
08208                p->subs[SUB_THREEWAY].inthreeway = 0;
08209             } else {
08210                /* Lets see what we're up to */
08211                if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
08212                   (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
08213                   int otherindex = SUB_THREEWAY;
08214                   struct ast_channel *other = ast_bridged_channel(p->subs[SUB_THREEWAY].owner);
08215                   int way3bridge = 0, cdr3way = 0;
08216 
08217                   if (!other) {
08218                      other = ast_bridged_channel(p->subs[SUB_REAL].owner);
08219                   } else
08220                      way3bridge = 1;
08221 
08222                   if (p->subs[SUB_THREEWAY].owner->cdr)
08223                      cdr3way = 1;
08224 
08225                   ast_verb(3, "Building conference on call on %s and %s\n", p->subs[SUB_THREEWAY].owner->name, p->subs[SUB_REAL].owner->name);
08226                   /* Put them in the threeway, and flip */
08227                   p->subs[SUB_THREEWAY].inthreeway = 1;
08228                   p->subs[SUB_REAL].inthreeway = 1;
08229                   if (ast->_state == AST_STATE_UP) {
08230                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
08231                      otherindex = SUB_REAL;
08232                   }
08233                   if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
08234                      ast_queue_control(p->subs[otherindex].owner, AST_CONTROL_UNHOLD);
08235                   p->subs[otherindex].needunhold = 1;
08236                   p->owner = p->subs[SUB_REAL].owner;
08237                   if (ast->_state == AST_STATE_RINGING) {
08238                      ast_debug(1, "Enabling ringtone on real and threeway\n");
08239                      res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
08240                      res = tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, DAHDI_TONE_RINGTONE);
08241                   }
08242                } else {
08243                   ast_verb(3, "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
08244                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
08245                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
08246                   p->owner = p->subs[SUB_REAL].owner;
08247                   if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
08248                      ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
08249                   p->subs[SUB_REAL].needunhold = 1;
08250                   dahdi_enable_ec(p);
08251                }
08252             }
08253          }
08254 winkflashdone:
08255          update_conf(p);
08256          break;
08257       case SIG_EM:
08258       case SIG_EM_E1:
08259       case SIG_FEATD:
08260       case SIG_SF:
08261       case SIG_SFWINK:
08262       case SIG_SF_FEATD:
08263       case SIG_FXSLS:
08264       case SIG_FXSGS:
08265          if (p->dialing)
08266             ast_debug(1, "Ignoring wink on channel %d\n", p->channel);
08267          else
08268             ast_debug(1, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
08269          break;
08270       case SIG_FEATDMF_TA:
08271          switch (p->whichwink) {
08272          case 0:
08273             ast_debug(1, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->caller.ani2,
08274                S_COR(p->owner->caller.ani.number.valid,
08275                   p->owner->caller.ani.number.str, ""));
08276             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#",
08277                p->owner->caller.ani2,
08278                S_COR(p->owner->caller.ani.number.valid,
08279                   p->owner->caller.ani.number.str, ""));
08280             break;
08281          case 1:
08282             ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
08283             break;
08284          case 2:
08285             ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
08286             return NULL;
08287          }
08288          p->whichwink++;
08289          /* Fall through */
08290       case SIG_FEATDMF:
08291       case SIG_E911:
08292       case SIG_FGC_CAMAMF:
08293       case SIG_FGC_CAMA:
08294       case SIG_FEATB:
08295       case SIG_SF_FEATDMF:
08296       case SIG_SF_FEATB:
08297       case SIG_EMWINK:
08298          /* FGD MF and EMWINK *Must* wait for wink */
08299          if (!ast_strlen_zero(p->dop.dialstr)) {
08300             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08301             if (res < 0) {
08302                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08303                p->dop.dialstr[0] = '\0';
08304                return NULL;
08305             } else
08306                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08307          }
08308          p->dop.dialstr[0] = '\0';
08309          break;
08310       default:
08311          ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
08312       }
08313       break;
08314    case DAHDI_EVENT_HOOKCOMPLETE:
08315       if (p->inalarm) break;
08316       if ((p->radio || (p->oprmode < 0))) break;
08317       if (p->waitingfordt.tv_sec) break;
08318       switch (mysig) {
08319       case SIG_FXSLS:  /* only interesting for FXS */
08320       case SIG_FXSGS:
08321       case SIG_FXSKS:
08322       case SIG_EM:
08323       case SIG_EM_E1:
08324       case SIG_EMWINK:
08325       case SIG_FEATD:
08326       case SIG_SF:
08327       case SIG_SFWINK:
08328       case SIG_SF_FEATD:
08329          if (!ast_strlen_zero(p->dop.dialstr)) {
08330             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08331             if (res < 0) {
08332                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
08333                p->dop.dialstr[0] = '\0';
08334                return NULL;
08335             } else
08336                ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
08337          }
08338          p->dop.dialstr[0] = '\0';
08339          p->dop.op = DAHDI_DIAL_OP_REPLACE;
08340          break;
08341       case SIG_FEATDMF:
08342       case SIG_FEATDMF_TA:
08343       case SIG_E911:
08344       case SIG_FGC_CAMA:
08345       case SIG_FGC_CAMAMF:
08346       case SIG_FEATB:
08347       case SIG_SF_FEATDMF:
08348       case SIG_SF_FEATB:
08349          ast_debug(1, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
08350          break;
08351       default:
08352          break;
08353       }
08354       break;
08355    case DAHDI_EVENT_POLARITY:
08356       /*
08357        * If we get a Polarity Switch event, check to see
08358        * if we should change the polarity state and
08359        * mark the channel as UP or if this is an indication
08360        * of remote end disconnect.
08361        */
08362       if (p->polarity == POLARITY_IDLE) {
08363          p->polarity = POLARITY_REV;
08364          if (p->answeronpolarityswitch &&
08365             ((ast->_state == AST_STATE_DIALING) ||
08366             (ast->_state == AST_STATE_RINGING))) {
08367             ast_debug(1, "Answering on polarity switch!\n");
08368             ast_setstate(p->owner, AST_STATE_UP);
08369             if (p->hanguponpolarityswitch) {
08370                p->polaritydelaytv = ast_tvnow();
08371             }
08372          } else
08373             ast_debug(1, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
08374       }
08375       /* Removed else statement from here as it was preventing hangups from ever happening*/
08376       /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
08377       if (p->hanguponpolarityswitch &&
08378          (p->polarityonanswerdelay > 0) &&
08379          (p->polarity == POLARITY_REV) &&
08380          ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
08381          /* Added log_debug information below to provide a better indication of what is going on */
08382          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) );
08383 
08384          if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
08385             ast_debug(1, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
08386             ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
08387             p->polarity = POLARITY_IDLE;
08388          } else
08389             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);
08390 
08391       } else {
08392          p->polarity = POLARITY_IDLE;
08393          ast_debug(1, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
08394       }
08395       /* Added more log_debug information below to provide a better indication of what is going on */
08396       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) );
08397       break;
08398    default:
08399       ast_debug(1, "Dunno what to do with event %d on channel %d\n", res, p->channel);
08400    }
08401    return &p->subs[idx].f;
08402 }
08403 
08404 static struct ast_frame *__dahdi_exception(struct ast_channel *ast)
08405 {
08406    int res;
08407    int idx;
08408    struct ast_frame *f;
08409    int usedindex = -1;
08410    struct dahdi_pvt *p = ast->tech_pvt;
08411 
08412    idx = dahdi_get_index(ast, p, 1);
08413 
08414    p->subs[idx].f.frametype = AST_FRAME_NULL;
08415    p->subs[idx].f.datalen = 0;
08416    p->subs[idx].f.samples = 0;
08417    p->subs[idx].f.mallocd = 0;
08418    p->subs[idx].f.offset = 0;
08419    p->subs[idx].f.subclass.integer = 0;
08420    p->subs[idx].f.delivery = ast_tv(0,0);
08421    p->subs[idx].f.src = "dahdi_exception";
08422    p->subs[idx].f.data.ptr = NULL;
08423 
08424 
08425    if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
08426       /* If nobody owns us, absorb the event appropriately, otherwise
08427          we loop indefinitely.  This occurs when, during call waiting, the
08428          other end hangs up our channel so that it no longer exists, but we
08429          have neither FLASH'd nor ONHOOK'd to signify our desire to
08430          change to the other channel. */
08431       if (p->fake_event) {
08432          res = p->fake_event;
08433          p->fake_event = 0;
08434       } else
08435          res = dahdi_get_event(p->subs[SUB_REAL].dfd);
08436       /* Switch to real if there is one and this isn't something really silly... */
08437       if ((res != DAHDI_EVENT_RINGEROFF) && (res != DAHDI_EVENT_RINGERON) &&
08438          (res != DAHDI_EVENT_HOOKCOMPLETE)) {
08439          ast_debug(1, "Restoring owner of channel %d on event %d\n", p->channel, res);
08440          p->owner = p->subs[SUB_REAL].owner;
08441          if (p->owner && ast_bridged_channel(p->owner))
08442             ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08443          p->subs[SUB_REAL].needunhold = 1;
08444       }
08445       switch (res) {
08446       case DAHDI_EVENT_ONHOOK:
08447          dahdi_disable_ec(p);
08448          if (p->owner) {
08449             ast_verb(3, "Channel %s still has call, ringing phone\n", p->owner->name);
08450             dahdi_ring_phone(p);
08451             p->callwaitingrepeat = 0;
08452             p->cidcwexpire = 0;
08453          } else
08454             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08455          update_conf(p);
08456          break;
08457       case DAHDI_EVENT_RINGOFFHOOK:
08458          dahdi_enable_ec(p);
08459          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08460          if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
08461             p->subs[SUB_REAL].needanswer = 1;
08462             p->dialing = 0;
08463          }
08464          break;
08465       case DAHDI_EVENT_HOOKCOMPLETE:
08466       case DAHDI_EVENT_RINGERON:
08467       case DAHDI_EVENT_RINGEROFF:
08468          /* Do nothing */
08469          break;
08470       case DAHDI_EVENT_WINKFLASH:
08471          p->flashtime = ast_tvnow();
08472          if (p->owner) {
08473             ast_verb(3, "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
08474             if (p->owner->_state != AST_STATE_UP) {
08475                /* Answer if necessary */
08476                usedindex = dahdi_get_index(p->owner, p, 0);
08477                if (usedindex > -1) {
08478                   p->subs[usedindex].needanswer = 1;
08479                }
08480                ast_setstate(p->owner, AST_STATE_UP);
08481             }
08482             p->callwaitingrepeat = 0;
08483             p->cidcwexpire = 0;
08484             if (ast_bridged_channel(p->owner))
08485                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
08486             p->subs[SUB_REAL].needunhold = 1;
08487          } else
08488             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
08489          update_conf(p);
08490          break;
08491       default:
08492          ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
08493       }
08494       f = &p->subs[idx].f;
08495       return f;
08496    }
08497    if (!(p->radio || (p->oprmode < 0)))
08498       ast_debug(1, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
08499    /* If it's not us, return NULL immediately */
08500    if (ast != p->owner) {
08501       ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
08502       f = &p->subs[idx].f;
08503       return f;
08504    }
08505    f = dahdi_handle_event(ast);
08506 
08507    /* tell the cdr this zap device hung up */
08508    if (f == NULL) {
08509       ast_set_hangupsource(ast, ast->name, 0);
08510    }
08511 
08512    return f;
08513 }
08514 
08515 static struct ast_frame *dahdi_exception(struct ast_channel *ast)
08516 {
08517    struct dahdi_pvt *p = ast->tech_pvt;
08518    struct ast_frame *f;
08519    ast_mutex_lock(&p->lock);
08520    if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08521       struct analog_pvt *analog_p = p->sig_pvt;
08522       f = analog_exception(analog_p, ast);
08523    } else {
08524       f = __dahdi_exception(ast);
08525    }
08526    ast_mutex_unlock(&p->lock);
08527    return f;
08528 }
08529 
08530 static struct ast_frame *dahdi_read(struct ast_channel *ast)
08531 {
08532    struct dahdi_pvt *p = ast->tech_pvt;
08533    int res;
08534    int idx;
08535    void *readbuf;
08536    struct ast_frame *f;
08537 
08538    while (ast_mutex_trylock(&p->lock)) {
08539       CHANNEL_DEADLOCK_AVOIDANCE(ast);
08540    }
08541 
08542    idx = dahdi_get_index(ast, p, 0);
08543 
08544    /* Hang up if we don't really exist */
08545    if (idx < 0)   {
08546       ast_log(LOG_WARNING, "We don't exist?\n");
08547       ast_mutex_unlock(&p->lock);
08548       return NULL;
08549    }
08550 
08551    if ((p->radio || (p->oprmode < 0)) && p->inalarm) {
08552       ast_mutex_unlock(&p->lock);
08553       return NULL;
08554    }
08555 
08556    p->subs[idx].f.frametype = AST_FRAME_NULL;
08557    p->subs[idx].f.datalen = 0;
08558    p->subs[idx].f.samples = 0;
08559    p->subs[idx].f.mallocd = 0;
08560    p->subs[idx].f.offset = 0;
08561    p->subs[idx].f.subclass.integer = 0;
08562    p->subs[idx].f.delivery = ast_tv(0,0);
08563    p->subs[idx].f.src = "dahdi_read";
08564    p->subs[idx].f.data.ptr = NULL;
08565 
08566    /* make sure it sends initial key state as first frame */
08567    if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
08568    {
08569       struct dahdi_params ps;
08570 
08571       memset(&ps, 0, sizeof(ps));
08572       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
08573          ast_mutex_unlock(&p->lock);
08574          return NULL;
08575       }
08576       p->firstradio = 1;
08577       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08578       if (ps.rxisoffhook)
08579       {
08580          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_KEY;
08581       }
08582       else
08583       {
08584          p->subs[idx].f.subclass.integer = AST_CONTROL_RADIO_UNKEY;
08585       }
08586       ast_mutex_unlock(&p->lock);
08587       return &p->subs[idx].f;
08588    }
08589    if (p->ringt > 0) {
08590       if (!(--p->ringt)) {
08591          ast_mutex_unlock(&p->lock);
08592          return NULL;
08593       }
08594    }
08595 
08596 #ifdef HAVE_OPENR2
08597    if (p->mfcr2) {
08598       openr2_chan_process_event(p->r2chan);
08599    }
08600 #endif
08601 
08602    if (p->subs[idx].needringing) {
08603       /* Send ringing frame if requested */
08604       p->subs[idx].needringing = 0;
08605       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08606       p->subs[idx].f.subclass.integer = AST_CONTROL_RINGING;
08607       ast_setstate(ast, AST_STATE_RINGING);
08608       ast_mutex_unlock(&p->lock);
08609       return &p->subs[idx].f;
08610    }
08611 
08612    if (p->subs[idx].needbusy) {
08613       /* Send busy frame if requested */
08614       p->subs[idx].needbusy = 0;
08615       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08616       p->subs[idx].f.subclass.integer = AST_CONTROL_BUSY;
08617       ast_mutex_unlock(&p->lock);
08618       return &p->subs[idx].f;
08619    }
08620 
08621    if (p->subs[idx].needcongestion) {
08622       /* Send congestion frame if requested */
08623       p->subs[idx].needcongestion = 0;
08624       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08625       p->subs[idx].f.subclass.integer = AST_CONTROL_CONGESTION;
08626       ast_mutex_unlock(&p->lock);
08627       return &p->subs[idx].f;
08628    }
08629 
08630    if (p->subs[idx].needanswer) {
08631       /* Send answer frame if requested */
08632       p->subs[idx].needanswer = 0;
08633       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08634       p->subs[idx].f.subclass.integer = AST_CONTROL_ANSWER;
08635       ast_mutex_unlock(&p->lock);
08636       return &p->subs[idx].f;
08637    }
08638 #ifdef HAVE_OPENR2
08639    if (p->mfcr2 && openr2_chan_get_read_enabled(p->r2chan)) {
08640       /* openr2 took care of reading and handling any event
08641         (needanswer, needbusy etc), if we continue we will read()
08642         twice, lets just return a null frame. This should only
08643         happen when openr2 is dialing out */
08644       ast_mutex_unlock(&p->lock);
08645       return &ast_null_frame;
08646    }
08647 #endif
08648 
08649    if (p->subs[idx].needflash) {
08650       /* Send answer frame if requested */
08651       p->subs[idx].needflash = 0;
08652       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08653       p->subs[idx].f.subclass.integer = AST_CONTROL_FLASH;
08654       ast_mutex_unlock(&p->lock);
08655       return &p->subs[idx].f;
08656    }
08657 
08658    if (p->subs[idx].needhold) {
08659       /* Send answer frame if requested */
08660       p->subs[idx].needhold = 0;
08661       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08662       p->subs[idx].f.subclass.integer = AST_CONTROL_HOLD;
08663       ast_mutex_unlock(&p->lock);
08664       ast_debug(1, "Sending hold on '%s'\n", ast->name);
08665       return &p->subs[idx].f;
08666    }
08667 
08668    if (p->subs[idx].needunhold) {
08669       /* Send answer frame if requested */
08670       p->subs[idx].needunhold = 0;
08671       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
08672       p->subs[idx].f.subclass.integer = AST_CONTROL_UNHOLD;
08673       ast_mutex_unlock(&p->lock);
08674       ast_debug(1, "Sending unhold on '%s'\n", ast->name);
08675       return &p->subs[idx].f;
08676    }
08677 
08678    if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
08679       if (!p->subs[idx].linear) {
08680          p->subs[idx].linear = 1;
08681          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08682          if (res)
08683             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, idx);
08684       }
08685    } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
08686       (ast->rawreadformat == AST_FORMAT_ALAW)) {
08687       if (p->subs[idx].linear) {
08688          p->subs[idx].linear = 0;
08689          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08690          if (res)
08691             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, idx);
08692       }
08693    } else {
08694       ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
08695       ast_mutex_unlock(&p->lock);
08696       return NULL;
08697    }
08698    readbuf = ((unsigned char *)p->subs[idx].buffer) + AST_FRIENDLY_OFFSET;
08699    CHECK_BLOCKING(ast);
08700    res = read(p->subs[idx].dfd, readbuf, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
08701    ast_clear_flag(ast, AST_FLAG_BLOCKING);
08702    /* Check for hangup */
08703    if (res < 0) {
08704       f = NULL;
08705       if (res == -1) {
08706          if (errno == EAGAIN) {
08707             /* Return "NULL" frame if there is nobody there */
08708             ast_mutex_unlock(&p->lock);
08709             return &p->subs[idx].f;
08710          } else if (errno == ELAST) {
08711             if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08712                struct analog_pvt *analog_p = p->sig_pvt;
08713                f = analog_exception(analog_p, ast);
08714             } else {
08715                f = __dahdi_exception(ast);
08716             }
08717          } else
08718             ast_log(LOG_WARNING, "dahdi_rec: %s\n", strerror(errno));
08719       }
08720       ast_mutex_unlock(&p->lock);
08721       return f;
08722    }
08723    if (res != (p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE)) {
08724       ast_debug(1, "Short read (%d/%d), must be an event...\n", res, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
08725       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08726          struct analog_pvt *analog_p = p->sig_pvt;
08727          f = analog_exception(analog_p, ast);
08728       } else {
08729          f = __dahdi_exception(ast);
08730       }
08731       ast_mutex_unlock(&p->lock);
08732       return f;
08733    }
08734    if (p->tdd) { /* if in TDD mode, see if we receive that */
08735       int c;
08736 
08737       c = tdd_feed(p->tdd,readbuf,READ_SIZE);
08738       if (c < 0) {
08739          ast_debug(1,"tdd_feed failed\n");
08740          ast_mutex_unlock(&p->lock);
08741          return NULL;
08742       }
08743       if (c) { /* if a char to return */
08744          p->subs[idx].f.subclass.integer = 0;
08745          p->subs[idx].f.frametype = AST_FRAME_TEXT;
08746          p->subs[idx].f.mallocd = 0;
08747          p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
08748          p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET;
08749          p->subs[idx].f.datalen = 1;
08750          *((char *) p->subs[idx].f.data.ptr) = c;
08751          ast_mutex_unlock(&p->lock);
08752          return &p->subs[idx].f;
08753       }
08754    }
08755    /* Ensure the CW timer decrements only on a single subchannel */
08756    if (p->callwaitingrepeat && dahdi_get_index(ast, p, 1) == SUB_REAL) {
08757       p->callwaitingrepeat--;
08758    }
08759    if (p->cidcwexpire)
08760       p->cidcwexpire--;
08761    /* Repeat callwaiting */
08762    if (p->callwaitingrepeat == 1) {
08763       p->callwaitrings++;
08764       dahdi_callwait(ast);
08765    }
08766    /* Expire CID/CW */
08767    if (p->cidcwexpire == 1) {
08768       ast_verb(3, "CPE does not support Call Waiting Caller*ID.\n");
08769       restore_conference(p);
08770    }
08771    if (p->subs[idx].linear) {
08772       p->subs[idx].f.datalen = READ_SIZE * 2;
08773    } else
08774       p->subs[idx].f.datalen = READ_SIZE;
08775 
08776    /* Handle CallerID Transmission */
08777    if ((p->owner == ast) && p->cidspill) {
08778       send_callerid(p);
08779    }
08780 
08781    p->subs[idx].f.frametype = AST_FRAME_VOICE;
08782    p->subs[idx].f.subclass.codec = ast->rawreadformat;
08783    p->subs[idx].f.samples = READ_SIZE;
08784    p->subs[idx].f.mallocd = 0;
08785    p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
08786    p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[idx].buffer[0]);
08787 #if 0
08788    ast_debug(1, "Read %d of voice on %s\n", p->subs[idx].f.datalen, ast->name);
08789 #endif
08790    if (p->dialing ||  p->radio || /* Transmitting something */
08791       (idx && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
08792       ((idx == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
08793       ) {
08794       /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
08795          don't send anything */
08796       p->subs[idx].f.frametype = AST_FRAME_NULL;
08797       p->subs[idx].f.subclass.integer = 0;
08798       p->subs[idx].f.samples = 0;
08799       p->subs[idx].f.mallocd = 0;
08800       p->subs[idx].f.offset = 0;
08801       p->subs[idx].f.data.ptr = NULL;
08802       p->subs[idx].f.datalen= 0;
08803    }
08804    if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress || p->waitingfordt.tv_sec) && !idx) {
08805       /* Perform busy detection etc on the dahdi line */
08806       int mute;
08807 
08808       f = ast_dsp_process(ast, p->dsp, &p->subs[idx].f);
08809 
08810       /* Check if DSP code thinks we should be muting this frame and mute the conference if so */
08811       mute = ast_dsp_was_muted(p->dsp);
08812       if (p->muting != mute) {
08813          p->muting = mute;
08814          dahdi_confmute(p, mute);
08815       }
08816 
08817       if (f) {
08818          if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass.integer == AST_CONTROL_BUSY)) {
08819             if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
08820                /* Treat this as a "hangup" instead of a "busy" on the assumption that
08821                   a busy */
08822                f = NULL;
08823             }
08824          } else if (f->frametype == AST_FRAME_DTMF) {
08825 #ifdef HAVE_PRI
08826             if (dahdi_sig_pri_lib_handles(p->sig)
08827                && !((struct sig_pri_chan *) p->sig_pvt)->proceeding
08828                && p->pri
08829                && ((!p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING))
08830                   || (p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)))) {
08831                /* Don't accept in-band DTMF when in overlap dial mode */
08832                f->frametype = AST_FRAME_NULL;
08833                f->subclass.integer = 0;
08834             }
08835 #endif
08836             /* DSP clears us of being pulse */
08837             p->pulsedial = 0;
08838          } else if (p->waitingfordt.tv_sec) {
08839             if (ast_tvdiff_ms(ast_tvnow(), p->waitingfordt) >= p->waitfordialtone ) {
08840                p->waitingfordt.tv_sec = 0;
08841                ast_log(LOG_WARNING, "Never saw dialtone on channel %d\n", p->channel);
08842                f=NULL;
08843             } else if (f->frametype == AST_FRAME_VOICE) {
08844                f->frametype = AST_FRAME_NULL;
08845                f->subclass.integer = 0;
08846                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) {
08847                   p->waitingfordt.tv_sec = 0;
08848                   p->dsp_features &= ~DSP_FEATURE_WAITDIALTONE;
08849                   ast_dsp_set_features(p->dsp, p->dsp_features);
08850                   ast_log(LOG_DEBUG, "Got 10 samples of dialtone!\n");
08851                   if (!ast_strlen_zero(p->dop.dialstr)) { /* Dial deferred digits */
08852                      res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
08853                      if (res < 0) {
08854                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
08855                         p->dop.dialstr[0] = '\0';
08856                         ast_mutex_unlock(&p->lock);
08857                         return NULL;
08858                      } else {
08859                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
08860                         p->dialing = 1;
08861                         p->dop.dialstr[0] = '\0';
08862                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
08863                         ast_setstate(ast, AST_STATE_DIALING);
08864                      }
08865                   }
08866                }
08867             }
08868          }
08869       }
08870    } else
08871       f = &p->subs[idx].f;
08872 
08873    if (f && (f->frametype == AST_FRAME_DTMF)) {
08874       if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
08875          analog_handle_dtmfup(p->sig_pvt, ast, idx, &f);
08876       } else
08877          dahdi_handle_dtmfup(ast, idx, &f);
08878    }
08879 
08880    /* If we have a fake_event, trigger exception to handle it */
08881    if (p->fake_event)
08882       ast_set_flag(ast, AST_FLAG_EXCEPTION);
08883 
08884    ast_mutex_unlock(&p->lock);
08885    return f;
08886 }
08887 
08888 static int my_dahdi_write(struct dahdi_pvt *p, unsigned char *buf, int len, int idx, int linear)
08889 {
08890    int sent=0;
08891    int size;
08892    int res;
08893    int fd;
08894    fd = p->subs[idx].dfd;
08895    while (len) {
08896       size = len;
08897       if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
08898          size = (linear ? READ_SIZE * 2 : READ_SIZE);
08899       res = write(fd, buf, size);
08900       if (res != size) {
08901          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
08902          return sent;
08903       }
08904       len -= size;
08905       buf += size;
08906    }
08907    return sent;
08908 }
08909 
08910 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame)
08911 {
08912    struct dahdi_pvt *p = ast->tech_pvt;
08913    int res;
08914    int idx;
08915    idx = dahdi_get_index(ast, p, 0);
08916    if (idx < 0) {
08917       ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
08918       return -1;
08919    }
08920 
08921    /* Write a frame of (presumably voice) data */
08922    if (frame->frametype != AST_FRAME_VOICE) {
08923       if (frame->frametype != AST_FRAME_IMAGE)
08924          ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
08925       return 0;
08926    }
08927    if ((frame->subclass.codec != AST_FORMAT_SLINEAR) &&
08928       (frame->subclass.codec != AST_FORMAT_ULAW) &&
08929       (frame->subclass.codec != AST_FORMAT_ALAW)) {
08930       ast_log(LOG_WARNING, "Cannot handle frames in %s format\n", ast_getformatname(frame->subclass.codec));
08931       return -1;
08932    }
08933    if (p->dialing) {
08934       ast_debug(1, "Dropping frame since I'm still dialing on %s...\n",ast->name);
08935       return 0;
08936    }
08937    if (!p->owner) {
08938       ast_debug(1, "Dropping frame since there is no active owner on %s...\n",ast->name);
08939       return 0;
08940    }
08941    if (p->cidspill) {
08942       ast_debug(1, "Dropping frame since I've still got a callerid spill\n");
08943       return 0;
08944    }
08945    /* Return if it's not valid data */
08946    if (!frame->data.ptr || !frame->datalen)
08947       return 0;
08948 
08949    if (frame->subclass.codec == AST_FORMAT_SLINEAR) {
08950       if (!p->subs[idx].linear) {
08951          p->subs[idx].linear = 1;
08952          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08953          if (res)
08954             ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
08955       }
08956       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 1);
08957    } else {
08958       /* x-law already */
08959       if (p->subs[idx].linear) {
08960          p->subs[idx].linear = 0;
08961          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08962          if (res)
08963             ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
08964       }
08965       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 0);
08966    }
08967    if (res < 0) {
08968       ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
08969       return -1;
08970    }
08971    return 0;
08972 }
08973 
08974 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
08975 {
08976    struct dahdi_pvt *p = chan->tech_pvt;
08977    int res=-1;
08978    int idx;
08979    int func = DAHDI_FLASH;
08980 
08981    ast_mutex_lock(&p->lock);
08982    ast_debug(1, "Requested indication %d on channel %s\n", condition, chan->name);
08983    switch (p->sig) {
08984 #if defined(HAVE_PRI)
08985    case SIG_PRI_LIB_HANDLE_CASES:
08986       res = sig_pri_indicate(p->sig_pvt, chan, condition, data, datalen);
08987       ast_mutex_unlock(&p->lock);
08988       return res;
08989 #endif   /* defined(HAVE_PRI) */
08990 #if defined(HAVE_SS7)
08991    case SIG_SS7:
08992       res = sig_ss7_indicate(p->sig_pvt, chan, condition, data, datalen);
08993       ast_mutex_unlock(&p->lock);
08994       return res;
08995 #endif   /* defined(HAVE_SS7) */
08996    default:
08997       break;
08998    }
08999 #ifdef HAVE_OPENR2
09000    if (p->mfcr2 && !p->mfcr2_call_accepted) {
09001       ast_mutex_unlock(&p->lock);
09002       /* if this is an R2 call and the call is not yet accepted, we don't want the
09003          tone indications to mess up with the MF tones */
09004       return 0;
09005    }
09006 #endif
09007    idx = dahdi_get_index(chan, p, 0);
09008    if (idx == SUB_REAL) {
09009       switch (condition) {
09010       case AST_CONTROL_BUSY:
09011          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_BUSY);
09012          break;
09013       case AST_CONTROL_RINGING:
09014          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_RINGTONE);
09015 
09016          if (chan->_state != AST_STATE_UP) {
09017             if ((chan->_state != AST_STATE_RING) ||
09018                ((p->sig != SIG_FXSKS) &&
09019              (p->sig != SIG_FXSLS) &&
09020              (p->sig != SIG_FXSGS)))
09021             ast_setstate(chan, AST_STATE_RINGING);
09022          }
09023          break;
09024       case AST_CONTROL_PROCEEDING:
09025          ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
09026          /* don't continue in ast_indicate */
09027          res = 0;
09028          break;
09029       case AST_CONTROL_PROGRESS:
09030          ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
09031          /* don't continue in ast_indicate */
09032          res = 0;
09033          break;
09034       case AST_CONTROL_CONGESTION:
09035          chan->hangupcause = AST_CAUSE_CONGESTION;
09036          break;
09037       case AST_CONTROL_HOLD:
09038          ast_moh_start(chan, data, p->mohinterpret);
09039          break;
09040       case AST_CONTROL_UNHOLD:
09041          ast_moh_stop(chan);
09042          break;
09043       case AST_CONTROL_RADIO_KEY:
09044          if (p->radio)
09045             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
09046          res = 0;
09047          break;
09048       case AST_CONTROL_RADIO_UNKEY:
09049          if (p->radio)
09050             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_RINGOFF);
09051          res = 0;
09052          break;
09053       case AST_CONTROL_FLASH:
09054          /* flash hookswitch */
09055          if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
09056             /* Clear out the dial buffer */
09057             p->dop.dialstr[0] = '\0';
09058             if ((ioctl(p->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
09059                ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
09060                   chan->name, strerror(errno));
09061             } else
09062                res = 0;
09063          } else
09064             res = 0;
09065          break;
09066       case AST_CONTROL_SRCUPDATE:
09067          res = 0;
09068          break;
09069       case -1:
09070          res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09071          break;
09072       }
09073    } else {
09074       res = 0;
09075    }
09076    ast_mutex_unlock(&p->lock);
09077    return res;
09078 }
09079 
09080 #if defined(HAVE_PRI)
09081 static struct ast_str *create_channel_name(struct dahdi_pvt *i, int is_outgoing, char *address)
09082 #else
09083 static struct ast_str *create_channel_name(struct dahdi_pvt *i)
09084 #endif   /* defined(HAVE_PRI) */
09085 {
09086    struct ast_str *chan_name;
09087    int x, y;
09088 
09089    /* Create the new channel name tail. */
09090    if (!(chan_name = ast_str_create(32))) {
09091       return NULL;
09092    }
09093    if (i->channel == CHAN_PSEUDO) {
09094       ast_str_set(&chan_name, 0, "pseudo-%ld", ast_random());
09095 #if defined(HAVE_PRI)
09096    } else if (i->pri) {
09097       ast_mutex_lock(&i->pri->lock);
09098       y = ++i->pri->new_chan_seq;
09099       if (is_outgoing) {
09100          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, address, y);
09101          address[0] = '\0';
09102       } else if (ast_strlen_zero(i->cid_subaddr)) {
09103          /* Put in caller-id number only since there is no subaddress. */
09104          ast_str_set(&chan_name, 0, "i%d/%s-%x", i->pri->span, i->cid_num, y);
09105       } else {
09106          /* Put in caller-id number and subaddress. */
09107          ast_str_set(&chan_name, 0, "i%d/%s:%s-%x", i->pri->span, i->cid_num,
09108             i->cid_subaddr, y);
09109       }
09110       ast_mutex_unlock(&i->pri->lock);
09111 #endif   /* defined(HAVE_PRI) */
09112    } else {
09113       y = 1;
09114       do {
09115          ast_str_set(&chan_name, 0, "%d-%d", i->channel, y);
09116          for (x = 0; x < 3; ++x) {
09117             if (i->subs[x].owner && !strcasecmp(ast_str_buffer(chan_name),
09118                i->subs[x].owner->name + 6)) {
09119                break;
09120             }
09121          }
09122          ++y;
09123       } while (x < 3);
09124    }
09125    return chan_name;
09126 }
09127 
09128 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid)
09129 {
09130    struct ast_channel *tmp;
09131    format_t deflaw;
09132    int x;
09133    int features;
09134    struct ast_str *chan_name;
09135    struct ast_variable *v;
09136 
09137    if (i->subs[idx].owner) {
09138       ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[idx]);
09139       return NULL;
09140    }
09141 
09142 #if defined(HAVE_PRI)
09143    /*
09144     * The dnid has been stuffed with the called-number[:subaddress]
09145     * by dahdi_request() for outgoing calls.
09146     */
09147    chan_name = create_channel_name(i, i->outgoing, i->dnid);
09148 #else
09149    chan_name = create_channel_name(i);
09150 #endif   /* defined(HAVE_PRI) */
09151    if (!chan_name) {
09152       return NULL;
09153    }
09154 
09155    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));
09156    ast_free(chan_name);
09157    if (!tmp)
09158       return NULL;
09159    tmp->tech = &dahdi_tech;
09160 #if defined(HAVE_PRI)
09161    if (i->pri) {
09162       ast_cc_copy_config_params(i->cc_params, i->pri->cc_params);
09163    }
09164 #endif   /* defined(HAVE_PRI) */
09165    ast_channel_cc_params_init(tmp, i->cc_params);
09166    if (law) {
09167       i->law = law;
09168       if (law == DAHDI_LAW_ALAW) {
09169          deflaw = AST_FORMAT_ALAW;
09170       } else {
09171          deflaw = AST_FORMAT_ULAW;
09172       }
09173    } else {
09174       switch (i->sig) {
09175       case SIG_PRI_LIB_HANDLE_CASES:
09176          /* Make sure companding law is known. */
09177          i->law = (i->law_default == DAHDI_LAW_ALAW)
09178             ? DAHDI_LAW_ALAW : DAHDI_LAW_MULAW;
09179          break;
09180       default:
09181          i->law = i->law_default;
09182          break;
09183       }
09184       if (i->law_default == DAHDI_LAW_ALAW) {
09185          deflaw = AST_FORMAT_ALAW;
09186       } else {
09187          deflaw = AST_FORMAT_ULAW;
09188       }
09189    }
09190    ast_channel_set_fd(tmp, 0, i->subs[idx].dfd);
09191    tmp->nativeformats = deflaw;
09192    /* Start out assuming ulaw since it's smaller :) */
09193    tmp->rawreadformat = deflaw;
09194    tmp->readformat = deflaw;
09195    tmp->rawwriteformat = deflaw;
09196    tmp->writeformat = deflaw;
09197    i->subs[idx].linear = 0;
09198    dahdi_setlinear(i->subs[idx].dfd, i->subs[idx].linear);
09199    features = 0;
09200    if (idx == SUB_REAL) {
09201       if (i->busydetect && CANBUSYDETECT(i))
09202          features |= DSP_FEATURE_BUSY_DETECT;
09203       if ((i->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(i))
09204          features |= DSP_FEATURE_CALL_PROGRESS;
09205       if ((i->waitfordialtone) && CANPROGRESSDETECT(i))
09206          features |= DSP_FEATURE_WAITDIALTONE;
09207       if ((!i->outgoing && (i->callprogress & CALLPROGRESS_FAX_INCOMING)) ||
09208          (i->outgoing && (i->callprogress & CALLPROGRESS_FAX_OUTGOING))) {
09209          features |= DSP_FEATURE_FAX_DETECT;
09210       }
09211       x = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
09212       if (ioctl(i->subs[idx].dfd, DAHDI_TONEDETECT, &x)) {
09213          i->hardwaredtmf = 0;
09214          features |= DSP_FEATURE_DIGIT_DETECT;
09215       } else if (NEED_MFDETECT(i)) {
09216          i->hardwaredtmf = 1;
09217          features |= DSP_FEATURE_DIGIT_DETECT;
09218       }
09219    }
09220    if (features) {
09221       if (i->dsp) {
09222          ast_debug(1, "Already have a dsp on %s?\n", tmp->name);
09223       } else {
09224          if (i->channel != CHAN_PSEUDO)
09225             i->dsp = ast_dsp_new();
09226          else
09227             i->dsp = NULL;
09228          if (i->dsp) {
09229             i->dsp_features = features;
09230 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09231             /* We cannot do progress detection until receive PROGRESS message */
09232             if (i->outgoing && (dahdi_sig_pri_lib_handles(i->sig) || (i->sig == SIG_SS7))) {
09233                /* Remember requested DSP features, don't treat
09234                   talking as ANSWER */
09235                i->dsp_features = features & ~DSP_PROGRESS_TALK;
09236                features = 0;
09237             }
09238 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09239             ast_dsp_set_features(i->dsp, features);
09240             ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
09241             if (!ast_strlen_zero(progzone))
09242                ast_dsp_set_call_progress_zone(i->dsp, progzone);
09243             if (i->busydetect && CANBUSYDETECT(i)) {
09244                ast_dsp_set_busy_count(i->dsp, i->busycount);
09245                ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
09246             }
09247          }
09248       }
09249    }
09250 
09251    if (state == AST_STATE_RING)
09252       tmp->rings = 1;
09253    tmp->tech_pvt = i;
09254    if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
09255       /* Only FXO signalled stuff can be picked up */
09256       tmp->callgroup = i->callgroup;
09257       tmp->pickupgroup = i->pickupgroup;
09258    }
09259    if (!ast_strlen_zero(i->parkinglot))
09260       ast_string_field_set(tmp, parkinglot, i->parkinglot);
09261    if (!ast_strlen_zero(i->language))
09262       ast_string_field_set(tmp, language, i->language);
09263    if (!i->owner)
09264       i->owner = tmp;
09265    if (!ast_strlen_zero(i->accountcode))
09266       ast_string_field_set(tmp, accountcode, i->accountcode);
09267    if (i->amaflags)
09268       tmp->amaflags = i->amaflags;
09269    i->subs[idx].owner = tmp;
09270    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
09271    if (!analog_lib_handles(i->sig, i->radio, i->oprmode)) {
09272       ast_string_field_set(tmp, call_forward, i->call_forward);
09273    }
09274    /* If we've been told "no ADSI" then enforce it */
09275    if (!i->adsi)
09276       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
09277    if (!ast_strlen_zero(i->exten))
09278       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
09279    if (!ast_strlen_zero(i->rdnis)) {
09280       tmp->redirecting.from.number.valid = 1;
09281       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
09282    }
09283    if (!ast_strlen_zero(i->dnid)) {
09284       tmp->dialed.number.str = ast_strdup(i->dnid);
09285    }
09286 
09287    /* Don't use ast_set_callerid() here because it will
09288     * generate a needless NewCallerID event */
09289 #if defined(HAVE_PRI) || defined(HAVE_SS7)
09290    if (!ast_strlen_zero(i->cid_ani)) {
09291       tmp->caller.ani.number.valid = 1;
09292       tmp->caller.ani.number.str = ast_strdup(i->cid_ani);
09293    } else if (!ast_strlen_zero(i->cid_num)) {
09294       tmp->caller.ani.number.valid = 1;
09295       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09296    }
09297 #else
09298    if (!ast_strlen_zero(i->cid_num)) {
09299       tmp->caller.ani.number.valid = 1;
09300       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
09301    }
09302 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
09303    tmp->caller.id.name.presentation = i->callingpres;
09304    tmp->caller.id.number.presentation = i->callingpres;
09305    tmp->caller.id.number.plan = i->cid_ton;
09306    tmp->caller.ani2 = i->cid_ani2;
09307    tmp->caller.id.tag = ast_strdup(i->cid_tag);
09308    /* clear the fake event in case we posted one before we had ast_channel */
09309    i->fake_event = 0;
09310    /* Assure there is no confmute on this channel */
09311    dahdi_confmute(i, 0);
09312    i->muting = 0;
09313    /* Configure the new channel jb */
09314    ast_jb_configure(tmp, &global_jbconf);
09315 
09316    ast_devstate_changed_literal(ast_state_chan2dev(state), tmp->name);
09317 
09318    for (v = i->vars ; v ; v = v->next)
09319       pbx_builtin_setvar_helper(tmp, v->name, v->value);
09320 
09321    ast_module_ref(ast_module_info->self);
09322 
09323    if (startpbx) {
09324 #ifdef HAVE_OPENR2
09325       if (i->mfcr2call) {
09326          pbx_builtin_setvar_helper(tmp, "MFCR2_CATEGORY", openr2_proto_get_category_string(i->mfcr2_recvd_category));
09327       }
09328 #endif
09329       if (ast_pbx_start(tmp)) {
09330          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
09331          ast_hangup(tmp);
09332          return NULL;
09333       }
09334    }
09335    return tmp;
09336 }
09337 
09338 
09339 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
09340 {
09341    char c;
09342 
09343    *str = 0; /* start with empty output buffer */
09344    for (;;)
09345    {
09346       /* Wait for the first digit (up to specified ms). */
09347       c = ast_waitfordigit(chan, ms);
09348       /* if timeout, hangup or error, return as such */
09349       if (c < 1)
09350          return c;
09351       *str++ = c;
09352       *str = 0;
09353       if (strchr(term, c))
09354          return 1;
09355    }
09356 }
09357 
09358 static int dahdi_wink(struct dahdi_pvt *p, int idx)
09359 {
09360    int j;
09361    dahdi_set_hook(p->subs[idx].dfd, DAHDI_WINK);
09362    for (;;)
09363    {
09364       /* set bits of interest */
09365       j = DAHDI_IOMUX_SIGEVENT;
09366       /* wait for some happening */
09367       if (ioctl(p->subs[idx].dfd,DAHDI_IOMUX,&j) == -1) return(-1);
09368       /* exit loop if we have it */
09369       if (j & DAHDI_IOMUX_SIGEVENT) break;
09370    }
09371    /* get the event info */
09372    if (ioctl(p->subs[idx].dfd,DAHDI_GETEVENT,&j) == -1) return(-1);
09373    return 0;
09374 }
09375 
09376 /*! \brief enable or disable the chan_dahdi Do-Not-Disturb mode for a DAHDI channel
09377  * \param dahdichan "Physical" DAHDI channel (e.g: DAHDI/5)
09378  * \param flag on 1 to enable, 0 to disable, -1 return dnd value
09379  *
09380  * chan_dahdi has a DND (Do Not Disturb) mode for each dahdichan (physical
09381  * DAHDI channel). Use this to enable or disable it.
09382  *
09383  * \bug the use of the word "channel" for those dahdichans is really confusing.
09384  */
09385 static int dahdi_dnd(struct dahdi_pvt *dahdichan, int flag)
09386 {
09387    if (analog_lib_handles(dahdichan->sig, dahdichan->radio, dahdichan->oprmode)) {
09388       return analog_dnd(dahdichan->sig_pvt, flag);
09389    }
09390 
09391    if (flag == -1) {
09392       return dahdichan->dnd;
09393    }
09394 
09395    /* Do not disturb */
09396    dahdichan->dnd = flag;
09397    ast_verb(3, "%s DND on channel %d\n",
09398          flag? "Enabled" : "Disabled",
09399          dahdichan->channel);
09400    manager_event(EVENT_FLAG_SYSTEM, "DNDState",
09401          "Channel: DAHDI/%d\r\n"
09402          "Status: %s\r\n", dahdichan->channel,
09403          flag? "enabled" : "disabled");
09404 
09405    return 0;
09406 }
09407 
09408 static void *analog_ss_thread(void *data)
09409 {
09410    struct ast_channel *chan = data;
09411    struct dahdi_pvt *p = chan->tech_pvt;
09412    char exten[AST_MAX_EXTENSION] = "";
09413    char exten2[AST_MAX_EXTENSION] = "";
09414    unsigned char buf[256];
09415    char dtmfcid[300];
09416    char dtmfbuf[300];
09417    struct callerid_state *cs = NULL;
09418    char *name = NULL, *number = NULL;
09419    int distMatches;
09420    int curRingData[3];
09421    int receivedRingT;
09422    int counter1;
09423    int counter;
09424    int samples = 0;
09425    struct ast_smdi_md_message *smdi_msg = NULL;
09426    int flags = 0;
09427    int i;
09428    int timeout;
09429    int getforward = 0;
09430    char *s1, *s2;
09431    int len = 0;
09432    int res;
09433    int idx;
09434 
09435    ast_mutex_lock(&ss_thread_lock);
09436    ss_thread_count++;
09437    ast_mutex_unlock(&ss_thread_lock);
09438    /* in the bizarre case where the channel has become a zombie before we
09439       even get started here, abort safely
09440    */
09441    if (!p) {
09442       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
09443       ast_hangup(chan);
09444       goto quit;
09445    }
09446    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
09447    idx = dahdi_get_index(chan, p, 1);
09448    if (idx < 0) {
09449       ast_log(LOG_WARNING, "Huh?\n");
09450       ast_hangup(chan);
09451       goto quit;
09452    }
09453    if (p->dsp)
09454       ast_dsp_digitreset(p->dsp);
09455    switch (p->sig) {
09456    case SIG_FEATD:
09457    case SIG_FEATDMF:
09458    case SIG_FEATDMF_TA:
09459    case SIG_E911:
09460    case SIG_FGC_CAMAMF:
09461    case SIG_FEATB:
09462    case SIG_EMWINK:
09463    case SIG_SF_FEATD:
09464    case SIG_SF_FEATDMF:
09465    case SIG_SF_FEATB:
09466    case SIG_SFWINK:
09467       if (dahdi_wink(p, idx))
09468          goto quit;
09469       /* Fall through */
09470    case SIG_EM:
09471    case SIG_EM_E1:
09472    case SIG_SF:
09473    case SIG_FGC_CAMA:
09474       res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09475       if (p->dsp)
09476          ast_dsp_digitreset(p->dsp);
09477       /* set digit mode appropriately */
09478       if (p->dsp) {
09479          if (NEED_MFDETECT(p))
09480             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
09481          else
09482             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
09483       }
09484       memset(dtmfbuf, 0, sizeof(dtmfbuf));
09485       /* Wait for the first digit only if immediate=no */
09486       if (!p->immediate)
09487          /* Wait for the first digit (up to 5 seconds). */
09488          res = ast_waitfordigit(chan, 5000);
09489       else
09490          res = 0;
09491       if (res > 0) {
09492          /* save first char */
09493          dtmfbuf[0] = res;
09494          switch (p->sig) {
09495          case SIG_FEATD:
09496          case SIG_SF_FEATD:
09497             res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
09498             if (res > 0)
09499                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
09500             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09501             break;
09502          case SIG_FEATDMF_TA:
09503             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09504             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09505             if (dahdi_wink(p, idx)) goto quit;
09506             dtmfbuf[0] = 0;
09507             /* Wait for the first digit (up to 5 seconds). */
09508             res = ast_waitfordigit(chan, 5000);
09509             if (res <= 0) break;
09510             dtmfbuf[0] = res;
09511             /* fall through intentionally */
09512          case SIG_FEATDMF:
09513          case SIG_E911:
09514          case SIG_FGC_CAMAMF:
09515          case SIG_SF_FEATDMF:
09516             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09517             /* if international caca, do it again to get real ANO */
09518             if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
09519             {
09520                if (dahdi_wink(p, idx)) goto quit;
09521                dtmfbuf[0] = 0;
09522                /* Wait for the first digit (up to 5 seconds). */
09523                res = ast_waitfordigit(chan, 5000);
09524                if (res <= 0) break;
09525                dtmfbuf[0] = res;
09526                res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09527             }
09528             if (res > 0) {
09529                /* if E911, take off hook */
09530                if (p->sig == SIG_E911)
09531                   dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
09532                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
09533             }
09534             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09535             break;
09536          case SIG_FEATB:
09537          case SIG_SF_FEATB:
09538             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
09539             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09540             break;
09541          case SIG_EMWINK:
09542             /* if we received a '*', we are actually receiving Feature Group D
09543                dial syntax, so use that mode; otherwise, fall through to normal
09544                mode
09545             */
09546             if (res == '*') {
09547                res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
09548                if (res > 0)
09549                   res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
09550                if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
09551                break;
09552             }
09553          default:
09554             /* If we got the first digit, get the rest */
09555             len = 1;
09556             dtmfbuf[len] = '\0';
09557             while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
09558                if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
09559                   timeout = matchdigittimeout;
09560                } else {
09561                   timeout = gendigittimeout;
09562                }
09563                res = ast_waitfordigit(chan, timeout);
09564                if (res < 0) {
09565                   ast_debug(1, "waitfordigit returned < 0...\n");
09566                   ast_hangup(chan);
09567                   goto quit;
09568                } else if (res) {
09569                   dtmfbuf[len++] = res;
09570                   dtmfbuf[len] = '\0';
09571                } else {
09572                   break;
09573                }
09574             }
09575             break;
09576          }
09577       }
09578       if (res == -1) {
09579          ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
09580          ast_hangup(chan);
09581          goto quit;
09582       } else if (res < 0) {
09583          ast_debug(1, "Got hung up before digits finished\n");
09584          ast_hangup(chan);
09585          goto quit;
09586       }
09587 
09588       if (p->sig == SIG_FGC_CAMA) {
09589          char anibuf[100];
09590 
09591          if (ast_safe_sleep(chan,1000) == -1) {
09592             ast_hangup(chan);
09593             goto quit;
09594          }
09595          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
09596          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
09597          res = my_getsigstr(chan, anibuf, "#", 10000);
09598          if ((res > 0) && (strlen(anibuf) > 2)) {
09599             if (anibuf[strlen(anibuf) - 1] == '#')
09600                anibuf[strlen(anibuf) - 1] = 0;
09601             ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
09602          }
09603          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
09604       }
09605 
09606       ast_copy_string(exten, dtmfbuf, sizeof(exten));
09607       if (ast_strlen_zero(exten))
09608          ast_copy_string(exten, "s", sizeof(exten));
09609       if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
09610          /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
09611          if (exten[0] == '*') {
09612             char *stringp=NULL;
09613             ast_copy_string(exten2, exten, sizeof(exten2));
09614             /* Parse out extension and callerid */
09615             stringp=exten2 +1;
09616             s1 = strsep(&stringp, "*");
09617             s2 = strsep(&stringp, "*");
09618             if (s2) {
09619                if (!ast_strlen_zero(p->cid_num))
09620                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
09621                else
09622                   ast_set_callerid(chan, s1, NULL, s1);
09623                ast_copy_string(exten, s2, sizeof(exten));
09624             } else
09625                ast_copy_string(exten, s1, sizeof(exten));
09626          } else if (p->sig == SIG_FEATD)
09627             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
09628       }
09629       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
09630          if (exten[0] == '*') {
09631             char *stringp=NULL;
09632             ast_copy_string(exten2, exten, sizeof(exten2));
09633             /* Parse out extension and callerid */
09634             stringp=exten2 +1;
09635             s1 = strsep(&stringp, "#");
09636             s2 = strsep(&stringp, "#");
09637             if (s2) {
09638                if (!ast_strlen_zero(p->cid_num))
09639                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
09640                else
09641                   if (*(s1 + 2))
09642                      ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
09643                ast_copy_string(exten, s2 + 1, sizeof(exten));
09644             } else
09645                ast_copy_string(exten, s1 + 2, sizeof(exten));
09646          } else
09647             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
09648       }
09649       if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
09650          if (exten[0] == '*') {
09651             char *stringp=NULL;
09652             ast_copy_string(exten2, exten, sizeof(exten2));
09653             /* Parse out extension and callerid */
09654             stringp=exten2 +1;
09655             s1 = strsep(&stringp, "#");
09656             s2 = strsep(&stringp, "#");
09657             if (s2 && (*(s2 + 1) == '0')) {
09658                if (*(s2 + 2))
09659                   ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
09660             }
09661             if (s1)  ast_copy_string(exten, s1, sizeof(exten));
09662             else ast_copy_string(exten, "911", sizeof(exten));
09663          } else
09664             ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
09665       }
09666       if (p->sig == SIG_FEATB) {
09667          if (exten[0] == '*') {
09668             char *stringp=NULL;
09669             ast_copy_string(exten2, exten, sizeof(exten2));
09670             /* Parse out extension and callerid */
09671             stringp=exten2 +1;
09672             s1 = strsep(&stringp, "#");
09673             ast_copy_string(exten, exten2 + 1, sizeof(exten));
09674          } else
09675             ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
09676       }
09677       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
09678          dahdi_wink(p, idx);
09679          /* some switches require a minimum guard time between
09680             the last FGD wink and something that answers
09681             immediately. This ensures it */
09682          if (ast_safe_sleep(chan,100)) goto quit;
09683       }
09684       dahdi_enable_ec(p);
09685       if (NEED_MFDETECT(p)) {
09686          if (p->dsp) {
09687             if (!p->hardwaredtmf)
09688                ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
09689             else {
09690                ast_dsp_free(p->dsp);
09691                p->dsp = NULL;
09692             }
09693          }
09694       }
09695 
09696       if (ast_exists_extension(chan, chan->context, exten, 1,
09697          S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))) {
09698          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
09699          if (p->dsp) ast_dsp_digitreset(p->dsp);
09700          res = ast_pbx_run(chan);
09701          if (res) {
09702             ast_log(LOG_WARNING, "PBX exited non-zero\n");
09703             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09704          }
09705          goto quit;
09706       } else {
09707          ast_verb(2, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
09708          sleep(2);
09709          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_INFO);
09710          if (res < 0)
09711             ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
09712          else
09713             sleep(1);
09714          res = ast_streamfile(chan, "ss-noservice", chan->language);
09715          if (res >= 0)
09716             ast_waitstream(chan, "");
09717          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09718          ast_hangup(chan);
09719          goto quit;
09720       }
09721       break;
09722    case SIG_FXOLS:
09723    case SIG_FXOGS:
09724    case SIG_FXOKS:
09725       /* Read the first digit */
09726       timeout = firstdigittimeout;
09727       /* If starting a threeway call, never timeout on the first digit so someone
09728          can use flash-hook as a "hold" feature */
09729       if (p->subs[SUB_THREEWAY].owner)
09730          timeout = 999999;
09731       while (len < AST_MAX_EXTENSION-1) {
09732          /* Read digit unless it's supposed to be immediate, in which case the
09733             only answer is 's' */
09734          if (p->immediate)
09735             res = 's';
09736          else
09737             res = ast_waitfordigit(chan, timeout);
09738          timeout = 0;
09739          if (res < 0) {
09740             ast_debug(1, "waitfordigit returned < 0...\n");
09741             res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09742             ast_hangup(chan);
09743             goto quit;
09744          } else if (res) {
09745             ast_debug(1,"waitfordigit returned '%c' (%d), timeout = %d\n", res, res, timeout);
09746             exten[len++]=res;
09747             exten[len] = '\0';
09748          }
09749          if (!ast_ignore_pattern(chan->context, exten))
09750             tone_zone_play_tone(p->subs[idx].dfd, -1);
09751          else
09752             tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
09753          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && !ast_parking_ext_valid(exten, chan, chan->context)) {
09754             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
09755                if (getforward) {
09756                   /* Record this as the forwarding extension */
09757                   ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
09758                   ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
09759                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09760                   if (res)
09761                      break;
09762                   usleep(500000);
09763                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09764                   sleep(1);
09765                   memset(exten, 0, sizeof(exten));
09766                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
09767                   len = 0;
09768                   getforward = 0;
09769                } else {
09770                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
09771                   ast_copy_string(chan->exten, exten, sizeof(chan->exten));
09772                   if (!ast_strlen_zero(p->cid_num)) {
09773                      if (!p->hidecallerid)
09774                         ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
09775                      else
09776                         ast_set_callerid(chan, NULL, NULL, p->cid_num);
09777                   }
09778                   if (!ast_strlen_zero(p->cid_name)) {
09779                      if (!p->hidecallerid)
09780                         ast_set_callerid(chan, NULL, p->cid_name, NULL);
09781                   }
09782                   ast_setstate(chan, AST_STATE_RING);
09783                   dahdi_enable_ec(p);
09784                   res = ast_pbx_run(chan);
09785                   if (res) {
09786                      ast_log(LOG_WARNING, "PBX exited non-zero\n");
09787                      res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09788                   }
09789                   goto quit;
09790                }
09791             } else {
09792                /* It's a match, but they just typed a digit, and there is an ambiguous match,
09793                   so just set the timeout to matchdigittimeout and wait some more */
09794                timeout = matchdigittimeout;
09795             }
09796          } else if (res == 0) {
09797             ast_debug(1, "not enough digits (and no ambiguous match)...\n");
09798             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09799             dahdi_wait_event(p->subs[idx].dfd);
09800             ast_hangup(chan);
09801             goto quit;
09802          } else if (p->callwaiting && !strcmp(exten, "*70")) {
09803             ast_verb(3, "Disabling call waiting on %s\n", chan->name);
09804             /* Disable call waiting if enabled */
09805             p->callwaiting = 0;
09806             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09807             if (res) {
09808                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
09809                   chan->name, strerror(errno));
09810             }
09811             len = 0;
09812             ioctl(p->subs[idx].dfd,DAHDI_CONFDIAG,&len);
09813             memset(exten, 0, sizeof(exten));
09814             timeout = firstdigittimeout;
09815 
09816          } else if (!strcmp(exten,ast_pickup_ext())) {
09817             /* Scan all channels and see if there are any
09818              * ringing channels that have call groups
09819              * that equal this channels pickup group
09820              */
09821             if (idx == SUB_REAL) {
09822                /* Switch us from Third call to Call Wait */
09823                if (p->subs[SUB_THREEWAY].owner) {
09824                   /* If you make a threeway call and the *8# a call, it should actually
09825                      look like a callwait */
09826                   alloc_sub(p, SUB_CALLWAIT);
09827                   swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
09828                   unalloc_sub(p, SUB_THREEWAY);
09829                }
09830                dahdi_enable_ec(p);
09831                if (ast_pickup_call(chan)) {
09832                   ast_debug(1, "No call pickup possible...\n");
09833                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09834                   dahdi_wait_event(p->subs[idx].dfd);
09835                }
09836                ast_hangup(chan);
09837                goto quit;
09838             } else {
09839                ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
09840                ast_hangup(chan);
09841                goto quit;
09842             }
09843 
09844          } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
09845             ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
09846             /* Disable Caller*ID if enabled */
09847             p->hidecallerid = 1;
09848             ast_party_number_free(&chan->caller.id.number);
09849             ast_party_number_init(&chan->caller.id.number);
09850             ast_party_name_free(&chan->caller.id.name);
09851             ast_party_name_init(&chan->caller.id.name);
09852             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09853             if (res) {
09854                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
09855                   chan->name, strerror(errno));
09856             }
09857             len = 0;
09858             memset(exten, 0, sizeof(exten));
09859             timeout = firstdigittimeout;
09860          } else if (p->callreturn && !strcmp(exten, "*69")) {
09861             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09862             break;
09863          } else if (!strcmp(exten, "*78")) {
09864             dahdi_dnd(p, 1);
09865             /* Do not disturb */
09866             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09867             getforward = 0;
09868             memset(exten, 0, sizeof(exten));
09869             len = 0;
09870          } else if (!strcmp(exten, "*79")) {
09871             dahdi_dnd(p, 0);
09872             /* Do not disturb */
09873             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09874             getforward = 0;
09875             memset(exten, 0, sizeof(exten));
09876             len = 0;
09877          } else if (p->cancallforward && !strcmp(exten, "*72")) {
09878             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09879             getforward = 1;
09880             memset(exten, 0, sizeof(exten));
09881             len = 0;
09882          } else if (p->cancallforward && !strcmp(exten, "*73")) {
09883             ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
09884             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09885             memset(p->call_forward, 0, sizeof(p->call_forward));
09886             getforward = 0;
09887             memset(exten, 0, sizeof(exten));
09888             len = 0;
09889          } else if ((p->transfer || p->canpark) && ast_parking_ext_valid(exten, chan, chan->context) &&
09890                   p->subs[SUB_THREEWAY].owner &&
09891                   ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
09892             /* This is a three way call, the main call being a real channel,
09893                and we're parking the first call. */
09894             ast_masq_park_call(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), chan, 0, NULL);
09895             ast_verb(3, "Parking call to '%s'\n", chan->name);
09896             break;
09897          } else if (p->hidecallerid && !strcmp(exten, "*82")) {
09898             ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
09899             /* Enable Caller*ID if enabled */
09900             p->hidecallerid = 0;
09901             ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
09902             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
09903             if (res) {
09904                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
09905                   chan->name, strerror(errno));
09906             }
09907             len = 0;
09908             memset(exten, 0, sizeof(exten));
09909             timeout = firstdigittimeout;
09910          } else if (!strcmp(exten, "*0")) {
09911             struct ast_channel *nbridge =
09912                p->subs[SUB_THREEWAY].owner;
09913             struct dahdi_pvt *pbridge = NULL;
09914             /* set up the private struct of the bridged one, if any */
09915             if (nbridge && ast_bridged_channel(nbridge))
09916                pbridge = ast_bridged_channel(nbridge)->tech_pvt;
09917             if (nbridge && pbridge &&
09918                (nbridge->tech == &dahdi_tech) &&
09919                (ast_bridged_channel(nbridge)->tech == &dahdi_tech) &&
09920                ISTRUNK(pbridge)) {
09921                int func = DAHDI_FLASH;
09922                /* Clear out the dial buffer */
09923                p->dop.dialstr[0] = '\0';
09924                /* flash hookswitch */
09925                if ((ioctl(pbridge->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
09926                   ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
09927                      nbridge->name, strerror(errno));
09928                }
09929                swap_subs(p, SUB_REAL, SUB_THREEWAY);
09930                unalloc_sub(p, SUB_THREEWAY);
09931                p->owner = p->subs[SUB_REAL].owner;
09932                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
09933                   ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
09934                ast_hangup(chan);
09935                goto quit;
09936             } else {
09937                tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09938                dahdi_wait_event(p->subs[idx].dfd);
09939                tone_zone_play_tone(p->subs[idx].dfd, -1);
09940                swap_subs(p, SUB_REAL, SUB_THREEWAY);
09941                unalloc_sub(p, SUB_THREEWAY);
09942                p->owner = p->subs[SUB_REAL].owner;
09943                ast_hangup(chan);
09944                goto quit;
09945             }
09946          } else if (!ast_canmatch_extension(chan, chan->context, exten, 1,
09947             S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, NULL))
09948             && ((exten[0] != '*') || (strlen(exten) > 2))) {
09949             ast_debug(1, "Can't match %s from '%s' in context %s\n", exten,
09950                S_COR(chan->caller.id.number.valid, chan->caller.id.number.str, "<Unknown Caller>"),
09951                chan->context);
09952             break;
09953          }
09954          if (!timeout)
09955             timeout = gendigittimeout;
09956          if (len && !ast_ignore_pattern(chan->context, exten))
09957             tone_zone_play_tone(p->subs[idx].dfd, -1);
09958       }
09959       break;
09960    case SIG_FXSLS:
09961    case SIG_FXSGS:
09962    case SIG_FXSKS:
09963       /* check for SMDI messages */
09964       if (p->use_smdi && p->smdi_iface) {
09965          smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
09966 
09967          if (smdi_msg != NULL) {
09968             ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
09969 
09970             if (smdi_msg->type == 'B')
09971                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
09972             else if (smdi_msg->type == 'N')
09973                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
09974 
09975             ast_debug(1, "Received SMDI message on %s\n", chan->name);
09976          } else {
09977             ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
09978          }
09979       }
09980 
09981       if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
09982          number = smdi_msg->calling_st;
09983 
09984       /* If we want caller id, we're in a prering state due to a polarity reversal
09985        * and we're set to use a polarity reversal to trigger the start of caller id,
09986        * grab the caller id and wait for ringing to start... */
09987       } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING &&
09988                    (p->cid_start == CID_START_POLARITY || p->cid_start == CID_START_POLARITY_IN || p->cid_start == CID_START_DTMF_NOALERT))) {
09989          /* If set to use DTMF CID signalling, listen for DTMF */
09990          if (p->cid_signalling == CID_SIG_DTMF) {
09991             int k = 0;
09992             cs = NULL;
09993             ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
09994             dahdi_setlinear(p->subs[idx].dfd, 0);
09995             /*
09996              * We are the only party interested in the Rx stream since
09997              * we have not answered yet.  We don't need or even want DTMF
09998              * emulation.  The DTMF digits can come so fast that emulation
09999              * can drop some of them.
10000              */
10001             ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
10002             res = 4000;/* This is a typical OFF time between rings. */
10003             for (;;) {
10004                struct ast_frame *f;
10005                res = ast_waitfor(chan, res);
10006                if (res <= 0) {
10007                   /*
10008                    * We do not need to restore the dahdi_setlinear()
10009                    * or AST_FLAG_END_DTMF_ONLY flag settings since we
10010                    * are hanging up the channel.
10011                    */
10012                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10013                      "Exiting simple switch\n");
10014                   ast_hangup(chan);
10015                   goto quit;
10016                }
10017                f = ast_read(chan);
10018                if (!f)
10019                   break;
10020                if (f->frametype == AST_FRAME_DTMF) {
10021                   if (k < ARRAY_LEN(dtmfbuf) - 1) {
10022                      dtmfbuf[k++] = f->subclass.integer;
10023                   }
10024                   ast_debug(1, "CID got digit '%c'\n", f->subclass.integer);
10025                   res = 4000;/* This is a typical OFF time between rings. */
10026                }
10027                ast_frfree(f);
10028                if (chan->_state == AST_STATE_RING ||
10029                   chan->_state == AST_STATE_RINGING)
10030                   break; /* Got ring */
10031             }
10032             ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
10033             dtmfbuf[k] = '\0';
10034             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10035             /* Got cid and ring. */
10036             ast_debug(1, "CID got string '%s'\n", dtmfbuf);
10037             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10038             ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
10039             /* If first byte is NULL, we have no cid */
10040             if (!ast_strlen_zero(dtmfcid))
10041                number = dtmfcid;
10042             else
10043                number = NULL;
10044          /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10045          } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
10046             cs = callerid_new(p->cid_signalling);
10047             if (cs) {
10048                samples = 0;
10049 #if 1
10050                bump_gains(p);
10051 #endif
10052                /* Take out of linear mode for Caller*ID processing */
10053                dahdi_setlinear(p->subs[idx].dfd, 0);
10054 
10055                /* First we wait and listen for the Caller*ID */
10056                for (;;) {
10057                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10058                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10059                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10060                      callerid_free(cs);
10061                      ast_hangup(chan);
10062                      goto quit;
10063                   }
10064                   if (i & DAHDI_IOMUX_SIGEVENT) {
10065                      res = dahdi_get_event(p->subs[idx].dfd);
10066                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10067                      if (res == DAHDI_EVENT_NOALARM) {
10068                         p->inalarm = 0;
10069                      }
10070 
10071                      if (p->cid_signalling == CID_SIG_V23_JP) {
10072                         if (res == DAHDI_EVENT_RINGBEGIN) {
10073                            res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10074                            usleep(1);
10075                         }
10076                      } else {
10077                         res = 0;
10078                         break;
10079                      }
10080                   } else if (i & DAHDI_IOMUX_READ) {
10081                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10082                      if (res < 0) {
10083                         if (errno != ELAST) {
10084                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10085                            callerid_free(cs);
10086                            ast_hangup(chan);
10087                            goto quit;
10088                         }
10089                         break;
10090                      }
10091                      samples += res;
10092 
10093                      if (p->cid_signalling == CID_SIG_V23_JP) {
10094                         res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
10095                      } else {
10096                         res = callerid_feed(cs, buf, res, AST_LAW(p));
10097                      }
10098                      if (res < 0) {
10099                         /*
10100                          * The previous diagnostic message output likely
10101                          * explains why it failed.
10102                          */
10103                         ast_log(LOG_WARNING,
10104                            "Failed to decode CallerID on channel '%s'\n",
10105                            chan->name);
10106                         break;
10107                      } else if (res)
10108                         break;
10109                      else if (samples > (8000 * 10))
10110                         break;
10111                   }
10112                }
10113                if (res == 1) {
10114                   callerid_get(cs, &name, &number, &flags);
10115                   ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10116                }
10117 
10118                if (p->cid_signalling == CID_SIG_V23_JP) {
10119                   res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
10120                   usleep(1);
10121                }
10122 
10123                /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
10124                res = 4000;/* This is a typical OFF time between rings. */
10125                for (;;) {
10126                   struct ast_frame *f;
10127                   res = ast_waitfor(chan, res);
10128                   if (res <= 0) {
10129                      ast_log(LOG_WARNING, "CID timed out waiting for ring. "
10130                         "Exiting simple switch\n");
10131                      ast_hangup(chan);
10132                      goto quit;
10133                   }
10134                   if (!(f = ast_read(chan))) {
10135                      ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
10136                      ast_hangup(chan);
10137                      goto quit;
10138                   }
10139                   ast_frfree(f);
10140                   if (chan->_state == AST_STATE_RING ||
10141                      chan->_state == AST_STATE_RINGING)
10142                      break; /* Got ring */
10143                }
10144 
10145                /* We must have a ring by now, so, if configured, lets try to listen for
10146                 * distinctive ringing */
10147                if (p->usedistinctiveringdetection) {
10148                   len = 0;
10149                   distMatches = 0;
10150                   /* Clear the current ring data array so we don't have old data in it. */
10151                   for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10152                      curRingData[receivedRingT] = 0;
10153                   receivedRingT = 0;
10154                   counter = 0;
10155                   counter1 = 0;
10156                   /* Check to see if context is what it should be, if not set to be. */
10157                   if (strcmp(p->context,p->defcontext) != 0) {
10158                      ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10159                      ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10160                   }
10161 
10162                   for (;;) {
10163                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10164                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10165                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10166                         callerid_free(cs);
10167                         ast_hangup(chan);
10168                         goto quit;
10169                      }
10170                      if (i & DAHDI_IOMUX_SIGEVENT) {
10171                         res = dahdi_get_event(p->subs[idx].dfd);
10172                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10173                         if (res == DAHDI_EVENT_NOALARM) {
10174                            p->inalarm = 0;
10175                         }
10176                         res = 0;
10177                         /* Let us detect distinctive ring */
10178 
10179                         curRingData[receivedRingT] = p->ringt;
10180 
10181                         if (p->ringt < p->ringt_base/2)
10182                            break;
10183                         /* Increment the ringT counter so we can match it against
10184                            values in chan_dahdi.conf for distinctive ring */
10185                         if (++receivedRingT == ARRAY_LEN(curRingData))
10186                            break;
10187                      } else if (i & DAHDI_IOMUX_READ) {
10188                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10189                         if (res < 0) {
10190                            if (errno != ELAST) {
10191                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10192                               callerid_free(cs);
10193                               ast_hangup(chan);
10194                               goto quit;
10195                            }
10196                            break;
10197                         }
10198                         if (p->ringt > 0) {
10199                            if (!(--p->ringt)) {
10200                               res = -1;
10201                               break;
10202                            }
10203                         }
10204                      }
10205                   }
10206                      /* this only shows up if you have n of the dring patterns filled in */
10207                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10208                   for (counter = 0; counter < 3; counter++) {
10209                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10210                      channel */
10211                      distMatches = 0;
10212                      for (counter1 = 0; counter1 < 3; counter1++) {
10213                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10214                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10215                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10216                            curRingData[counter1]);
10217                            distMatches++;
10218                         } else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10219                               curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10220                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10221                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10222                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10223                            distMatches++;
10224                         }
10225                      }
10226 
10227                      if (distMatches == 3) {
10228                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10229                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10230                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10231                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10232                         break;
10233                      }
10234                   }
10235                }
10236                /* Restore linear mode (if appropriate) for Caller*ID processing */
10237                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10238 #if 1
10239                restore_gains(p);
10240 #endif
10241             } else
10242                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10243          } else {
10244             ast_log(LOG_WARNING, "Channel %s in prering "
10245                "state, but I have nothing to do. "
10246                "Terminating simple switch, should be "
10247                "restarted by the actual ring.\n",
10248                chan->name);
10249             ast_hangup(chan);
10250             goto quit;
10251          }
10252       } else if (p->use_callerid && p->cid_start == CID_START_RING) {
10253          if (p->cid_signalling == CID_SIG_DTMF) {
10254             int k = 0;
10255             cs = NULL;
10256             dahdi_setlinear(p->subs[idx].dfd, 0);
10257             res = 2000;
10258             for (;;) {
10259                struct ast_frame *f;
10260                res = ast_waitfor(chan, res);
10261                if (res <= 0) {
10262                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
10263                      "Exiting simple switch\n");
10264                   ast_hangup(chan);
10265                   return NULL;
10266                }
10267                f = ast_read(chan);
10268                if (f->frametype == AST_FRAME_DTMF) {
10269                   dtmfbuf[k++] = f->subclass.integer;
10270                   ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass.integer);
10271                   res = 2000;
10272                }
10273                ast_frfree(f);
10274 
10275                if (p->ringt_base == p->ringt)
10276                   break;
10277             }
10278             dtmfbuf[k] = '\0';
10279             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10280             /* Got cid and ring. */
10281             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
10282             ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
10283                dtmfcid, flags);
10284             /* If first byte is NULL, we have no cid */
10285             if (!ast_strlen_zero(dtmfcid))
10286                number = dtmfcid;
10287             else
10288                number = NULL;
10289             /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
10290          } else {
10291             /* FSK Bell202 callerID */
10292             cs = callerid_new(p->cid_signalling);
10293             if (cs) {
10294 #if 1
10295                bump_gains(p);
10296 #endif
10297                samples = 0;
10298                len = 0;
10299                distMatches = 0;
10300                /* Clear the current ring data array so we don't have old data in it. */
10301                for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
10302                   curRingData[receivedRingT] = 0;
10303                receivedRingT = 0;
10304                counter = 0;
10305                counter1 = 0;
10306                /* Check to see if context is what it should be, if not set to be. */
10307                if (strcmp(p->context,p->defcontext) != 0) {
10308                   ast_copy_string(p->context, p->defcontext, sizeof(p->context));
10309                   ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
10310                }
10311 
10312                /* Take out of linear mode for Caller*ID processing */
10313                dahdi_setlinear(p->subs[idx].dfd, 0);
10314                for (;;) {
10315                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10316                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10317                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10318                      callerid_free(cs);
10319                      ast_hangup(chan);
10320                      goto quit;
10321                   }
10322                   if (i & DAHDI_IOMUX_SIGEVENT) {
10323                      res = dahdi_get_event(p->subs[idx].dfd);
10324                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10325                      if (res == DAHDI_EVENT_NOALARM) {
10326                         p->inalarm = 0;
10327                      }
10328                      /* If we get a PR event, they hung up while processing calerid */
10329                      if ( res == DAHDI_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
10330                         ast_log(LOG_DEBUG, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
10331                         p->polarity = POLARITY_IDLE;
10332                         callerid_free(cs);
10333                         ast_hangup(chan);
10334                         goto quit;
10335                      }
10336                      res = 0;
10337                      /* Let us detect callerid when the telco uses distinctive ring */
10338 
10339                      curRingData[receivedRingT] = p->ringt;
10340 
10341                      if (p->ringt < p->ringt_base/2)
10342                         break;
10343                      /* Increment the ringT counter so we can match it against
10344                         values in chan_dahdi.conf for distinctive ring */
10345                      if (++receivedRingT == ARRAY_LEN(curRingData))
10346                         break;
10347                   } else if (i & DAHDI_IOMUX_READ) {
10348                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
10349                      if (res < 0) {
10350                         if (errno != ELAST) {
10351                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10352                            callerid_free(cs);
10353                            ast_hangup(chan);
10354                            goto quit;
10355                         }
10356                         break;
10357                      }
10358                      if (p->ringt > 0) {
10359                         if (!(--p->ringt)) {
10360                            res = -1;
10361                            break;
10362                         }
10363                      }
10364                      samples += res;
10365                      res = callerid_feed(cs, buf, res, AST_LAW(p));
10366                      if (res < 0) {
10367                         /*
10368                          * The previous diagnostic message output likely
10369                          * explains why it failed.
10370                          */
10371                         ast_log(LOG_WARNING,
10372                            "Failed to decode CallerID on channel '%s'\n",
10373                            chan->name);
10374                         break;
10375                      } else if (res)
10376                         break;
10377                      else if (samples > (8000 * 10))
10378                         break;
10379                   }
10380                }
10381                if (res == 1) {
10382                   callerid_get(cs, &name, &number, &flags);
10383                   ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
10384                }
10385                if (distinctiveringaftercid == 1) {
10386                   /* Clear the current ring data array so we don't have old data in it. */
10387                   for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
10388                      curRingData[receivedRingT] = 0;
10389                   }
10390                   receivedRingT = 0;
10391                   ast_verb(3, "Detecting post-CID distinctive ring\n");
10392                   for (;;) {
10393                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10394                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
10395                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10396                         callerid_free(cs);
10397                         ast_hangup(chan);
10398                         goto quit;
10399                      }
10400                      if (i & DAHDI_IOMUX_SIGEVENT) {
10401                         res = dahdi_get_event(p->subs[idx].dfd);
10402                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
10403                         if (res == DAHDI_EVENT_NOALARM) {
10404                            p->inalarm = 0;
10405                         }
10406                         res = 0;
10407                         /* Let us detect callerid when the telco uses distinctive ring */
10408 
10409                         curRingData[receivedRingT] = p->ringt;
10410 
10411                         if (p->ringt < p->ringt_base/2)
10412                            break;
10413                         /* Increment the ringT counter so we can match it against
10414                            values in chan_dahdi.conf for distinctive ring */
10415                         if (++receivedRingT == ARRAY_LEN(curRingData))
10416                            break;
10417                      } else if (i & DAHDI_IOMUX_READ) {
10418                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
10419                         if (res < 0) {
10420                            if (errno != ELAST) {
10421                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10422                               callerid_free(cs);
10423                               ast_hangup(chan);
10424                               goto quit;
10425                            }
10426                            break;
10427                         }
10428                         if (p->ringt > 0) {
10429                            if (!(--p->ringt)) {
10430                               res = -1;
10431                               break;
10432                            }
10433                         }
10434                      }
10435                   }
10436                }
10437                if (p->usedistinctiveringdetection) {
10438                   /* this only shows up if you have n of the dring patterns filled in */
10439                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
10440 
10441                   for (counter = 0; counter < 3; counter++) {
10442                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
10443                      channel */
10444                      /* this only shows up if you have n of the dring patterns filled in */
10445                      ast_verb(3, "Checking %d,%d,%d\n",
10446                            p->drings.ringnum[counter].ring[0],
10447                            p->drings.ringnum[counter].ring[1],
10448                            p->drings.ringnum[counter].ring[2]);
10449                      distMatches = 0;
10450                      for (counter1 = 0; counter1 < 3; counter1++) {
10451                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
10452                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
10453                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
10454                            curRingData[counter1]);
10455                            distMatches++;
10456                         }
10457                         else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
10458                            curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
10459                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
10460                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
10461                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
10462                            distMatches++;
10463                         }
10464                      }
10465                      if (distMatches == 3) {
10466                         /* The ring matches, set the context to whatever is for distinctive ring.. */
10467                         ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
10468                         ast_copy_string(chan->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(chan->context));
10469                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
10470                         break;
10471                      }
10472                   }
10473                }
10474                /* Restore linear mode (if appropriate) for Caller*ID processing */
10475                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
10476 #if 1
10477                restore_gains(p);
10478 #endif
10479                if (res < 0) {
10480                   ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
10481                }
10482             } else
10483                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
10484          }
10485       } else
10486          cs = NULL;
10487 
10488       if (number)
10489          ast_shrink_phone_number(number);
10490       ast_set_callerid(chan, number, name, number);
10491 
10492       if (smdi_msg)
10493          ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
10494 
10495       if (cs)
10496          callerid_free(cs);
10497 
10498       my_handle_notify_message(chan, p, flags, -1);
10499 
10500       ast_setstate(chan, AST_STATE_RING);
10501       chan->rings = 1;
10502       p->ringt = p->ringt_base;
10503       res = ast_pbx_run(chan);
10504       if (res) {
10505          ast_hangup(chan);
10506          ast_log(LOG_WARNING, "PBX exited non-zero\n");
10507       }
10508       goto quit;
10509    default:
10510       ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
10511       res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10512       if (res < 0)
10513             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
10514    }
10515    res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
10516    if (res < 0)
10517          ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
10518    ast_hangup(chan);
10519 quit:
10520    ast_mutex_lock(&ss_thread_lock);
10521    ss_thread_count--;
10522    ast_cond_signal(&ss_thread_complete);
10523    ast_mutex_unlock(&ss_thread_lock);
10524    return NULL;
10525 }
10526 
10527 struct mwi_thread_data {
10528    struct dahdi_pvt *pvt;
10529    unsigned char buf[READ_SIZE];
10530    size_t len;
10531 };
10532 
10533 static int calc_energy(const unsigned char *buf, int len, format_t law)
10534 {
10535    int x;
10536    int sum = 0;
10537 
10538    if (!len)
10539       return 0;
10540 
10541    for (x = 0; x < len; x++)
10542       sum += abs(law == AST_FORMAT_ULAW ? AST_MULAW(buf[x]) : AST_ALAW(buf[x]));
10543 
10544    return sum / len;
10545 }
10546 
10547 static void *mwi_thread(void *data)
10548 {
10549    struct mwi_thread_data *mtd = data;
10550    struct callerid_state *cs;
10551    pthread_t threadid;
10552    int samples = 0;
10553    char *name, *number;
10554    int flags;
10555    int i, res;
10556    unsigned int spill_done = 0;
10557    int spill_result = -1;
10558 
10559    if (!(cs = callerid_new(mtd->pvt->cid_signalling))) {
10560       mtd->pvt->mwimonitoractive = 0;
10561 
10562       return NULL;
10563    }
10564 
10565    callerid_feed(cs, mtd->buf, mtd->len, AST_LAW(mtd->pvt));
10566 
10567    bump_gains(mtd->pvt);
10568 
10569    for (;;) {
10570       i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
10571       if ((res = ioctl(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_IOMUX, &i))) {
10572          ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
10573          goto quit;
10574       }
10575 
10576       if (i & DAHDI_IOMUX_SIGEVENT) {
10577          struct ast_channel *chan;
10578 
10579          /* If we get an event, screen out events that we do not act on.
10580           * Otherwise, cancel and go to the simple switch to let it deal with it.
10581           */
10582          res = dahdi_get_event(mtd->pvt->subs[SUB_REAL].dfd);
10583 
10584          switch (res) {
10585          case DAHDI_EVENT_NEONMWI_ACTIVE:
10586          case DAHDI_EVENT_NEONMWI_INACTIVE:
10587          case DAHDI_EVENT_NONE:
10588          case DAHDI_EVENT_BITSCHANGED:
10589             break;
10590          case DAHDI_EVENT_NOALARM:
10591             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
10592                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
10593 
10594                analog_p->inalarm = 0;
10595             }
10596             mtd->pvt->inalarm = 0;
10597             handle_clear_alarms(mtd->pvt);
10598             break;
10599          case DAHDI_EVENT_ALARM:
10600             if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
10601                struct analog_pvt *analog_p = mtd->pvt->sig_pvt;
10602 
10603                analog_p->inalarm = 1;
10604             }
10605             mtd->pvt->inalarm = 1;
10606             res = get_alarms(mtd->pvt);
10607             handle_alarms(mtd->pvt, res);
10608             break; /* What to do on channel alarm ???? -- fall thru intentionally?? */
10609          default:
10610             ast_log(LOG_NOTICE, "Got event %d (%s)...  Passing along to analog_ss_thread\n", res, event2str(res));
10611             callerid_free(cs);
10612 
10613             restore_gains(mtd->pvt);
10614             mtd->pvt->ringt = mtd->pvt->ringt_base;
10615 
10616             if ((chan = dahdi_new(mtd->pvt, AST_STATE_RING, 0, SUB_REAL, 0, NULL))) {
10617                int result;
10618                if (analog_lib_handles(mtd->pvt->sig, mtd->pvt->radio, mtd->pvt->oprmode)) {
10619                   result = analog_ss_thread_start(mtd->pvt->sig_pvt, chan);
10620                } else {
10621                   result = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
10622                }
10623                if (result) {
10624                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", mtd->pvt->channel);
10625                   res = tone_zone_play_tone(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
10626                   if (res < 0)
10627                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", mtd->pvt->channel);
10628                   ast_hangup(chan);
10629                   goto quit;
10630                }
10631                goto quit_no_clean;
10632 
10633             } else {
10634                ast_log(LOG_WARNING, "Could not create channel to handle call\n");
10635             }
10636          }
10637       } else if (i & DAHDI_IOMUX_READ) {
10638          if ((res = read(mtd->pvt->subs[SUB_REAL].dfd, mtd->buf, sizeof(mtd->buf))) < 0) {
10639             if (errno != ELAST) {
10640                ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
10641                goto quit;
10642             }
10643             break;
10644          }
10645          samples += res;
10646          if (!spill_done) {
10647             if ((spill_result = callerid_feed(cs, mtd->buf, res, AST_LAW(mtd->pvt))) < 0) {
10648                /*
10649                 * The previous diagnostic message output likely
10650                 * explains why it failed.
10651                 */
10652                ast_log(LOG_WARNING, "Failed to decode CallerID\n");
10653                break;
10654             } else if (spill_result) {
10655                spill_done = 1;
10656             }
10657          } else {
10658             /* keep reading data until the energy level drops below the threshold
10659                so we don't get another 'trigger' on the remaining carrier signal
10660             */
10661             if (calc_energy(mtd->buf, res, AST_LAW(mtd->pvt)) <= mwilevel)
10662                break;
10663          }
10664          if (samples > (8000 * 4)) /*Termination case - time to give up*/
10665             break;
10666       }
10667    }
10668 
10669    if (spill_result == 1) {
10670       callerid_get(cs, &name, &number, &flags);
10671       if (flags & CID_MSGWAITING) {
10672          ast_log(LOG_NOTICE, "mwi: Have Messages on channel %d\n", mtd->pvt->channel);
10673          notify_message(mtd->pvt->mailbox, 1);
10674       } else if (flags & CID_NOMSGWAITING) {
10675          ast_log(LOG_NOTICE, "mwi: No Messages on channel %d\n", mtd->pvt->channel);
10676          notify_message(mtd->pvt->mailbox, 0);
10677       } else {
10678          ast_log(LOG_NOTICE, "mwi: Status unknown on channel %d\n", mtd->pvt->channel);
10679       }
10680    }
10681 
10682 
10683 quit:
10684    callerid_free(cs);
10685 
10686    restore_gains(mtd->pvt);
10687 
10688 quit_no_clean:
10689    mtd->pvt->mwimonitoractive = 0;
10690 
10691    ast_free(mtd);
10692 
10693    return NULL;
10694 }
10695 
10696 /*
10697 * The following three functions (mwi_send_init, mwi_send_process_buffer,
10698 * mwi_send_process_event) work with the do_monitor thread to generate mwi spills
10699 * that are sent out via FXS port on voicemail state change.  The execution of
10700 * the mwi send is state driven and can either generate a ring pulse prior to
10701 * sending the fsk spill or simply send an fsk spill.
10702 */
10703 static int mwi_send_init(struct dahdi_pvt * pvt)
10704 {
10705    int x, res;
10706 
10707 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10708    /* Determine how this spill is to be sent */
10709    if (pvt->mwisend_rpas) {
10710       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
10711       pvt->mwisendactive = 1;
10712    } else if (pvt->mwisend_fsk) {
10713       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
10714       pvt->mwisendactive = 1;
10715    } else {
10716       pvt->mwisendactive = 0;
10717       return 0;
10718    }
10719 #else
10720    if (mwisend_rpas) {
10721       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
10722    } else {
10723       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
10724    }
10725    pvt->mwisendactive = 1;
10726 #endif
10727 
10728    if (pvt->cidspill) {
10729       ast_log(LOG_WARNING, "cidspill already exists when trying to send FSK MWI\n");
10730       ast_free(pvt->cidspill);
10731       pvt->cidspill = NULL;
10732       pvt->cidpos = 0;
10733       pvt->cidlen = 0;
10734    }
10735    pvt->cidspill = ast_calloc(1, MAX_CALLERID_SIZE);
10736    if (!pvt->cidspill) {
10737       pvt->mwisendactive = 0;
10738       return -1;
10739    }
10740    x = DAHDI_FLUSH_BOTH;
10741    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
10742    x = 3000;
10743    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_ONHOOKTRANSFER, &x);
10744 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10745    if (pvt->mwisend_fsk) {
10746 #endif
10747       pvt->cidlen = ast_callerid_vmwi_generate(pvt->cidspill, has_voicemail(pvt), CID_MWI_TYPE_MDMF_FULL,
10748                       AST_LAW(pvt), pvt->cid_name, pvt->cid_num, 0);
10749       pvt->cidpos = 0;
10750 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10751    }
10752 #endif
10753    return 0;
10754 }
10755 
10756 static int mwi_send_process_buffer(struct dahdi_pvt * pvt, int num_read)
10757 {
10758    struct timeval    now;
10759    int         res;
10760 
10761    /* sanity check to catch if this had been interrupted previously
10762    *  i.e. state says there is more to do but there is no spill allocated
10763    */
10764    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current && !pvt->cidspill) {
10765       pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
10766    } else if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
10767       /* Normal processing -- Perform mwi send action */
10768       switch ( pvt->mwisend_data.mwisend_current) {
10769       case MWI_SEND_SA:
10770          /* Send the Ring Pulse Signal Alert */
10771          res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &AS_RP_cadence);
10772          if (res) {
10773             ast_log(LOG_WARNING, "Unable to set RP-AS ring cadence: %s\n", strerror(errno));
10774             goto quit;
10775          }
10776          res = dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RING);
10777          pvt->mwisend_data.mwisend_current = MWI_SEND_SA_WAIT;
10778          break;
10779       case MWI_SEND_SA_WAIT:  /* do nothing until I get RINGEROFF event */
10780          break;
10781       case MWI_SEND_PAUSE:  /* Wait between alert and spill - min of 500 mS*/
10782 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10783          if (pvt->mwisend_fsk) {
10784 #endif
10785             gettimeofday(&now, NULL);
10786             if ((int)(now.tv_sec - pvt->mwisend_data.pause.tv_sec) * 1000000 + (int)now.tv_usec - (int)pvt->mwisend_data.pause.tv_usec > 500000) {
10787                pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
10788             }
10789 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10790          } else { /* support for mwisendtype=nofsk */
10791             pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
10792          }
10793 #endif
10794          break;
10795       case MWI_SEND_SPILL:
10796          /* We read some number of bytes.  Write an equal amount of data */
10797          if(0 < num_read) {
10798             if (num_read > pvt->cidlen - pvt->cidpos)
10799                num_read = pvt->cidlen - pvt->cidpos;
10800             res = write(pvt->subs[SUB_REAL].dfd, pvt->cidspill + pvt->cidpos, num_read);
10801             if (res > 0) {
10802                pvt->cidpos += res;
10803                if (pvt->cidpos >= pvt->cidlen) {
10804                   pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
10805                }
10806             } else {
10807                ast_log(LOG_WARNING, "MWI FSK Send Write failed: %s\n", strerror(errno));
10808                goto quit;
10809             }
10810          }
10811          break;
10812       case MWI_SEND_CLEANUP:
10813          /* For now, do nothing */
10814          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
10815          break;
10816       default:
10817          /* Should not get here, punt*/
10818          goto quit;
10819       }
10820    }
10821 
10822    if (MWI_SEND_DONE == pvt->mwisend_data.mwisend_current) {
10823       if (pvt->cidspill) {
10824          ast_free(pvt->cidspill);
10825          pvt->cidspill = NULL;
10826          pvt->cidpos = 0;
10827          pvt->cidlen = 0;
10828       }
10829       pvt->mwisendactive = 0;
10830    }
10831    return 0;
10832 quit:
10833    if (pvt->cidspill) {
10834       ast_free(pvt->cidspill);
10835       pvt->cidspill = NULL;
10836       pvt->cidpos = 0;
10837       pvt->cidlen = 0;
10838    }
10839    pvt->mwisendactive = 0;
10840    return -1;
10841 }
10842 
10843 static int mwi_send_process_event(struct dahdi_pvt * pvt, int event)
10844 {
10845    int handled = 0;
10846 
10847    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
10848       switch (event) {
10849       case DAHDI_EVENT_RINGEROFF:
10850          if(pvt->mwisend_data.mwisend_current == MWI_SEND_SA_WAIT) {
10851             handled = 1;
10852 
10853             if (dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RINGOFF) ) {
10854                ast_log(LOG_WARNING, "Unable to finsh RP-AS: %s mwi send aborted\n", strerror(errno));
10855                if(pvt->cidspill) {
10856                   ast_free(pvt->cidspill);
10857                   pvt->cidspill = NULL;
10858                }
10859                pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
10860                pvt->mwisendactive = 0;
10861             } else {
10862                pvt->mwisend_data.mwisend_current = MWI_SEND_PAUSE;
10863                gettimeofday(&pvt->mwisend_data.pause, NULL);
10864             }
10865          }
10866          break;
10867       /* Going off hook, I need to punt this spill */
10868       case DAHDI_EVENT_RINGOFFHOOK:
10869          if (pvt->cidspill) {
10870             ast_free(pvt->cidspill);
10871             pvt->cidspill = NULL;
10872             pvt->cidpos = 0;
10873             pvt->cidlen = 0;
10874          }
10875          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
10876          pvt->mwisendactive = 0;
10877          break;
10878       case DAHDI_EVENT_RINGERON:
10879       case DAHDI_EVENT_HOOKCOMPLETE:
10880          break;
10881       default:
10882          break;
10883       }
10884    }
10885    return handled;
10886 }
10887 
10888 /* destroy a DAHDI channel, identified by its number */
10889 static int dahdi_destroy_channel_bynum(int channel)
10890 {
10891    struct dahdi_pvt *cur;
10892 
10893    ast_mutex_lock(&iflock);
10894    for (cur = iflist; cur; cur = cur->next) {
10895       if (cur->channel == channel) {
10896          int x = DAHDI_FLASH;
10897 
10898          /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
10899          ioctl(cur->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
10900 
10901          destroy_channel(cur, 1);
10902          ast_mutex_unlock(&iflock);
10903          ast_module_unref(ast_module_info->self);
10904          return RESULT_SUCCESS;
10905       }
10906    }
10907    ast_mutex_unlock(&iflock);
10908    return RESULT_FAILURE;
10909 }
10910 
10911 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
10912 {
10913    int res;
10914    pthread_t threadid;
10915    struct ast_channel *chan;
10916 
10917    /* Handle an event on a given channel for the monitor thread. */
10918 
10919    switch (event) {
10920    case DAHDI_EVENT_NONE:
10921    case DAHDI_EVENT_BITSCHANGED:
10922       break;
10923    case DAHDI_EVENT_WINKFLASH:
10924    case DAHDI_EVENT_RINGOFFHOOK:
10925       if (i->inalarm) break;
10926       if (i->radio) break;
10927       /* Got a ring/answer.  What kind of channel are we? */
10928       switch (i->sig) {
10929       case SIG_FXOLS:
10930       case SIG_FXOGS:
10931       case SIG_FXOKS:
10932          res = dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
10933          if (res && (errno == EBUSY))
10934             break;
10935          if (i->cidspill) {
10936             /* Cancel VMWI spill */
10937             ast_free(i->cidspill);
10938             i->cidspill = NULL;
10939          }
10940          if (i->immediate) {
10941             dahdi_enable_ec(i);
10942             /* The channel is immediately up.  Start right away */
10943             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
10944             chan = dahdi_new(i, AST_STATE_RING, 1, SUB_REAL, 0, NULL);
10945             if (!chan) {
10946                ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
10947                res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
10948                if (res < 0)
10949                   ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
10950             }
10951          } else {
10952             /* Check for callerid, digits, etc */
10953             chan = dahdi_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, NULL);
10954             if (chan) {
10955                if (has_voicemail(i))
10956                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
10957                else
10958                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
10959                if (res < 0)
10960                   ast_log(LOG_WARNING, "Unable to play dialtone on channel %d, do you have defaultzone and loadzone defined?\n", i->channel);
10961                if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
10962                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
10963                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
10964                   if (res < 0)
10965                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
10966                   ast_hangup(chan);
10967                }
10968             } else
10969                ast_log(LOG_WARNING, "Unable to create channel\n");
10970          }
10971          break;
10972       case SIG_FXSLS:
10973       case SIG_FXSGS:
10974       case SIG_FXSKS:
10975             i->ringt = i->ringt_base;
10976             /* Fall through */
10977       case SIG_EMWINK:
10978       case SIG_FEATD:
10979       case SIG_FEATDMF:
10980       case SIG_FEATDMF_TA:
10981       case SIG_E911:
10982       case SIG_FGC_CAMA:
10983       case SIG_FGC_CAMAMF:
10984       case SIG_FEATB:
10985       case SIG_EM:
10986       case SIG_EM_E1:
10987       case SIG_SFWINK:
10988       case SIG_SF_FEATD:
10989       case SIG_SF_FEATDMF:
10990       case SIG_SF_FEATB:
10991       case SIG_SF:
10992          /* Check for callerid, digits, etc */
10993          if (i->cid_start == CID_START_POLARITY_IN) {
10994             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
10995          } else {
10996             chan = dahdi_new(i, AST_STATE_RING, 0, SUB_REAL, 0, NULL);
10997          }
10998 
10999          if (!chan) {
11000             ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11001          } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11002             ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11003             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11004             if (res < 0) {
11005                ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11006             }
11007             ast_hangup(chan);
11008          }
11009          break;
11010       default:
11011          ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11012          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
11013          if (res < 0)
11014             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
11015          return NULL;
11016       }
11017       break;
11018    case DAHDI_EVENT_NOALARM:
11019       switch (i->sig) {
11020 #if defined(HAVE_PRI)
11021       case SIG_PRI_LIB_HANDLE_CASES:
11022          sig_pri_chan_alarm_notify(i->sig_pvt, 1);
11023          break;
11024 #endif   /* defined(HAVE_PRI) */
11025 #if defined(HAVE_SS7)
11026       case SIG_SS7:
11027          sig_ss7_set_alarm(i->sig_pvt, 0);
11028          break;
11029 #endif   /* defined(HAVE_SS7) */
11030       default:
11031          i->inalarm = 0;
11032          break;
11033       }
11034       handle_clear_alarms(i);
11035       break;
11036    case DAHDI_EVENT_ALARM:
11037       switch (i->sig) {
11038 #if defined(HAVE_PRI)
11039       case SIG_PRI_LIB_HANDLE_CASES:
11040          sig_pri_chan_alarm_notify(i->sig_pvt, 0);
11041          break;
11042 #endif   /* defined(HAVE_PRI) */
11043 #if defined(HAVE_SS7)
11044       case SIG_SS7:
11045          sig_ss7_set_alarm(i->sig_pvt, 1);
11046          break;
11047 #endif   /* defined(HAVE_SS7) */
11048       default:
11049          i->inalarm = 1;
11050          break;
11051       }
11052       res = get_alarms(i);
11053       handle_alarms(i, res);
11054       /* fall thru intentionally */
11055    case DAHDI_EVENT_ONHOOK:
11056       if (i->radio)
11057          break;
11058       /* Back on hook.  Hang up. */
11059       switch (i->sig) {
11060       case SIG_FXOLS:
11061       case SIG_FXOGS:
11062       case SIG_FEATD:
11063       case SIG_FEATDMF:
11064       case SIG_FEATDMF_TA:
11065       case SIG_E911:
11066       case SIG_FGC_CAMA:
11067       case SIG_FGC_CAMAMF:
11068       case SIG_FEATB:
11069       case SIG_EM:
11070       case SIG_EM_E1:
11071       case SIG_EMWINK:
11072       case SIG_SF_FEATD:
11073       case SIG_SF_FEATDMF:
11074       case SIG_SF_FEATB:
11075       case SIG_SF:
11076       case SIG_SFWINK:
11077       case SIG_FXSLS:
11078       case SIG_FXSGS:
11079       case SIG_FXSKS:
11080       case SIG_FXOKS:
11081          dahdi_disable_ec(i);
11082          /* Diddle the battery for the zhone */
11083 #ifdef ZHONE_HACK
11084          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
11085          usleep(1);
11086 #endif
11087          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11088          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
11089          break;
11090       case SIG_SS7:
11091       case SIG_PRI_LIB_HANDLE_CASES:
11092          dahdi_disable_ec(i);
11093          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11094          break;
11095       default:
11096          ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
11097          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
11098          return NULL;
11099       }
11100       break;
11101    case DAHDI_EVENT_POLARITY:
11102       switch (i->sig) {
11103       case SIG_FXSLS:
11104       case SIG_FXSKS:
11105       case SIG_FXSGS:
11106          /* We have already got a PR before the channel was
11107             created, but it wasn't handled. We need polarity
11108             to be REV for remote hangup detection to work.
11109             At least in Spain */
11110          if (i->hanguponpolarityswitch)
11111             i->polarity = POLARITY_REV;
11112          if (i->cid_start == CID_START_POLARITY || i->cid_start == CID_START_POLARITY_IN) {
11113             i->polarity = POLARITY_REV;
11114             ast_verb(2, "Starting post polarity "
11115                "CID detection on channel %d\n",
11116                i->channel);
11117             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11118             if (!chan) {
11119                ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11120             } else if (ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan)) {
11121                ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11122             }
11123          }
11124          break;
11125       default:
11126          ast_log(LOG_WARNING, "handle_init_event detected "
11127             "polarity reversal on non-FXO (SIG_FXS) "
11128             "interface %d\n", i->channel);
11129       }
11130       break;
11131    case DAHDI_EVENT_REMOVED: /* destroy channel, will actually do so in do_monitor */
11132       ast_log(LOG_NOTICE,
11133             "Got DAHDI_EVENT_REMOVED. Destroying channel %d\n",
11134             i->channel);
11135       return i;
11136    case DAHDI_EVENT_NEONMWI_ACTIVE:
11137       if (i->mwimonitor_neon) {
11138          notify_message(i->mailbox, 1);
11139          ast_log(LOG_NOTICE, "NEON MWI set for channel %d, mailbox %s \n", i->channel, i->mailbox);
11140       }
11141       break;
11142    case DAHDI_EVENT_NEONMWI_INACTIVE:
11143       if (i->mwimonitor_neon) {
11144          notify_message(i->mailbox, 0);
11145          ast_log(LOG_NOTICE, "NEON MWI cleared for channel %d, mailbox %s\n", i->channel, i->mailbox);
11146       }
11147       break;
11148    }
11149    return NULL;
11150 }
11151 
11152 static void *do_monitor(void *data)
11153 {
11154    int count, res, res2, spoint, pollres=0;
11155    struct dahdi_pvt *i;
11156    struct dahdi_pvt *last = NULL;
11157    struct dahdi_pvt *doomed;
11158    time_t thispass = 0, lastpass = 0;
11159    int found;
11160    char buf[1024];
11161    struct pollfd *pfds=NULL;
11162    int lastalloc = -1;
11163    /* This thread monitors all the frame relay interfaces which are not yet in use
11164       (and thus do not have a separate thread) indefinitely */
11165    /* From here on out, we die whenever asked */
11166 #if 0
11167    if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
11168       ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
11169       return NULL;
11170    }
11171    ast_debug(1, "Monitor starting...\n");
11172 #endif
11173    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11174 
11175    for (;;) {
11176       /* Lock the interface list */
11177       ast_mutex_lock(&iflock);
11178       if (!pfds || (lastalloc != ifcount)) {
11179          if (pfds) {
11180             ast_free(pfds);
11181             pfds = NULL;
11182          }
11183          if (ifcount) {
11184             if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
11185                ast_mutex_unlock(&iflock);
11186                return NULL;
11187             }
11188          }
11189          lastalloc = ifcount;
11190       }
11191       /* Build the stuff we're going to poll on, that is the socket of every
11192          dahdi_pvt that does not have an associated owner channel */
11193       count = 0;
11194       for (i = iflist; i; i = i->next) {
11195          ast_mutex_lock(&i->lock);
11196          if ((i->subs[SUB_REAL].dfd > -1) && i->sig && (!i->radio) && !(i->sig & SIG_MFCR2)) {
11197             if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11198                struct analog_pvt *p = i->sig_pvt;
11199 
11200                if (!p)
11201                   ast_log(LOG_ERROR, "No sig_pvt?\n");
11202 
11203                if (!p->owner && !p->subs[SUB_REAL].owner) {
11204                   /* This needs to be watched, as it lacks an owner */
11205                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11206                   pfds[count].events = POLLPRI;
11207                   pfds[count].revents = 0;
11208                   /* Message waiting or r2 channels also get watched for reading */
11209                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk || 
11210                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11211                      pfds[count].events |= POLLIN;
11212                   }
11213                   count++;
11214                }
11215             } else {
11216                if (!i->owner && !i->subs[SUB_REAL].owner && !i->mwimonitoractive ) {
11217                   /* This needs to be watched, as it lacks an owner */
11218                   pfds[count].fd = i->subs[SUB_REAL].dfd;
11219                   pfds[count].events = POLLPRI;
11220                   pfds[count].revents = 0;
11221                   /* If we are monitoring for VMWI or sending CID, we need to
11222                      read from the channel as well */
11223                   if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk ||
11224                      (i->cid_start == CID_START_DTMF_NOALERT && (i->sig == SIG_FXSLS || i->sig == SIG_FXSGS || i->sig == SIG_FXSKS))) {
11225                      pfds[count].events |= POLLIN;
11226                   }
11227                   count++;
11228                }
11229             }
11230          }
11231          ast_mutex_unlock(&i->lock);
11232       }
11233       /* Okay, now that we know what to do, release the interface lock */
11234       ast_mutex_unlock(&iflock);
11235 
11236       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
11237       pthread_testcancel();
11238       /* Wait at least a second for something to happen */
11239       res = poll(pfds, count, 1000);
11240       pthread_testcancel();
11241       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
11242 
11243       /* Okay, poll has finished.  Let's see what happened.  */
11244       if (res < 0) {
11245          if ((errno != EAGAIN) && (errno != EINTR))
11246             ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
11247          continue;
11248       }
11249       /* Alright, lock the interface list again, and let's look and see what has
11250          happened */
11251       ast_mutex_lock(&iflock);
11252       found = 0;
11253       spoint = 0;
11254       lastpass = thispass;
11255       thispass = time(NULL);
11256       doomed = NULL;
11257       for (i = iflist;; i = i->next) {
11258          if (doomed) {
11259             int res;
11260             res = dahdi_destroy_channel_bynum(doomed->channel);
11261             if (res != RESULT_SUCCESS) {
11262                ast_log(LOG_WARNING, "Couldn't find channel to destroy, hopefully another destroy operation just happened.\n");
11263             }
11264             doomed = NULL;
11265          }
11266          if (!i) {
11267             break;
11268          }
11269 
11270          if (thispass != lastpass) {
11271             if (!found && ((i == last) || ((i == iflist) && !last))) {
11272                last = i;
11273                if (last) {
11274                   struct analog_pvt *analog_p = last->sig_pvt;
11275                   /* Only allow MWI to be initiated on a quiescent fxs port */
11276                   if (analog_p
11277                      && !last->mwisendactive
11278                      && (last->sig & __DAHDI_SIG_FXO)
11279                      && !analog_p->fxsoffhookstate
11280                      && !last->owner
11281                      && !ast_strlen_zero(last->mailbox)
11282                      && (thispass - analog_p->onhooktime > 3)) {
11283                      res = has_voicemail(last);
11284                      if (analog_p->msgstate != res) {
11285                         /* Set driver resources for signalling VMWI */
11286                         res2 = ioctl(last->subs[SUB_REAL].dfd, DAHDI_VMWI, &res);
11287                         if (res2) {
11288                            /* TODO: This message will ALWAYS be generated on some cards; any way to restrict it to those cards where it is interesting? */
11289                            ast_debug(3, "Unable to control message waiting led on channel %d: %s\n", last->channel, strerror(errno));
11290                         }
11291                         /* If enabled for FSK spill then initiate it */
11292                         if (mwi_send_init(last)) {
11293                            ast_log(LOG_WARNING, "Unable to initiate mwi send sequence on channel %d\n", last->channel);
11294                         }
11295                         analog_p->msgstate = res;
11296                         found ++;
11297                      }
11298                   }
11299                   last = last->next;
11300                }
11301             }
11302          }
11303          if ((i->subs[SUB_REAL].dfd > -1) && i->sig) {
11304             if (i->radio && !i->owner)
11305             {
11306                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11307                if (res)
11308                {
11309                   ast_debug(1, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
11310                   /* Don't hold iflock while handling init events */
11311                   ast_mutex_unlock(&iflock);
11312                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11313                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11314                   else
11315                      doomed = handle_init_event(i, res);
11316                   ast_mutex_lock(&iflock);
11317                }
11318                continue;
11319             }
11320             pollres = ast_fdisset(pfds, i->subs[SUB_REAL].dfd, count, &spoint);
11321             if (pollres & POLLIN) {
11322                if (i->owner || i->subs[SUB_REAL].owner) {
11323 #ifdef HAVE_PRI
11324                   if (!i->pri)
11325 #endif
11326                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].dfd);
11327                   continue;
11328                }
11329                if (!i->mwimonitor_fsk && !i->mwisendactive  && i->cid_start != CID_START_DTMF_NOALERT) {
11330                   ast_log(LOG_WARNING, "Whoa....  I'm not looking for MWI or sending MWI but am reading (%d)...\n", i->subs[SUB_REAL].dfd);
11331                   continue;
11332                }
11333                res = read(i->subs[SUB_REAL].dfd, buf, sizeof(buf));
11334                if (res > 0) {
11335                   if (i->mwimonitor_fsk) {
11336                      if (calc_energy((unsigned char *) buf, res, AST_LAW(i)) > mwilevel) {
11337                         pthread_attr_t attr;
11338                         pthread_t threadid;
11339                         struct mwi_thread_data *mtd;
11340 
11341                         pthread_attr_init(&attr);
11342                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
11343 
11344                         ast_log(LOG_DEBUG, "Maybe some MWI on port %d!\n", i->channel);
11345                         if ((mtd = ast_calloc(1, sizeof(*mtd)))) {
11346                            mtd->pvt = i;
11347                            memcpy(mtd->buf, buf, res);
11348                            mtd->len = res;
11349                            if (ast_pthread_create_background(&threadid, &attr, mwi_thread, mtd)) {
11350                               ast_log(LOG_WARNING, "Unable to start mwi thread on channel %d\n", i->channel);
11351                               ast_free(mtd);
11352                            }
11353                            i->mwimonitoractive = 1;
11354                         }
11355                      }
11356                   /* If configured to check for a DTMF CID spill that comes without alert (e.g no polarity reversal) */
11357                   } else if (i->cid_start == CID_START_DTMF_NOALERT) {
11358                      int energy;
11359                      struct timeval now;
11360                      /* State machine dtmfcid_holdoff_state allows for the line to settle
11361                       * before checking agin for dtmf energy.  Presently waits for 500 mS before checking again 
11362                      */
11363                      if (1 == i->dtmfcid_holdoff_state) {
11364                         gettimeofday(&i->dtmfcid_delay, NULL);
11365                         i->dtmfcid_holdoff_state = 2;
11366                      } else if (2 == i->dtmfcid_holdoff_state) {
11367                         gettimeofday(&now, NULL);
11368                         if ((int)(now.tv_sec - i->dtmfcid_delay.tv_sec) * 1000000 + (int)now.tv_usec - (int)i->dtmfcid_delay.tv_usec > 500000) {
11369                            i->dtmfcid_holdoff_state = 0;
11370                         }
11371                      } else {
11372                         energy = calc_energy((unsigned char *) buf, res, AST_LAW(i));
11373                         if (!i->mwisendactive && energy > dtmfcid_level) {
11374                            pthread_t threadid;
11375                            struct ast_channel *chan;
11376                            ast_mutex_unlock(&iflock);
11377                            if (analog_lib_handles(i->sig, i->radio, i->oprmode)) {
11378                               /* just in case this event changes or somehow destroys a channel, set doomed here too */
11379                               doomed = analog_handle_init_event(i->sig_pvt, ANALOG_EVENT_DTMFCID);  
11380                               i->dtmfcid_holdoff_state = 1;
11381                            } else {
11382                               chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, NULL);
11383                               if (!chan) {
11384                                  ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
11385                               } else {
11386                                  res = ast_pthread_create_detached(&threadid, NULL, analog_ss_thread, chan);
11387                                  if (res) {
11388                                     ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
11389                                  } else {
11390                                     i->dtmfcid_holdoff_state = 1;
11391                                  }
11392                               }
11393                            }
11394                            ast_mutex_lock(&iflock);
11395                         }
11396                      }
11397                   }
11398                   if (i->mwisendactive) {
11399                      mwi_send_process_buffer(i, res);
11400                   }
11401                } else {
11402                   ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
11403                }
11404             }
11405             if (pollres & POLLPRI) {
11406                if (i->owner || i->subs[SUB_REAL].owner) {
11407 #ifdef HAVE_PRI
11408                   if (!i->pri)
11409 #endif
11410                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d)...\n", i->subs[SUB_REAL].dfd);
11411                   continue;
11412                }
11413                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
11414                ast_debug(1, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
11415                /* Don't hold iflock while handling init events */
11416                ast_mutex_unlock(&iflock);
11417                if (0 == i->mwisendactive || 0 == mwi_send_process_event(i, res)) {
11418                   if (analog_lib_handles(i->sig, i->radio, i->oprmode))
11419                      doomed = (struct dahdi_pvt *) analog_handle_init_event(i->sig_pvt, dahdievent_to_analogevent(res));
11420                   else
11421                      doomed = handle_init_event(i, res);
11422                }
11423                ast_mutex_lock(&iflock);
11424             }
11425          }
11426       }
11427       ast_mutex_unlock(&iflock);
11428    }
11429    /* Never reached */
11430    return NULL;
11431 
11432 }
11433 
11434 static int restart_monitor(void)
11435 {
11436    /* If we're supposed to be stopped -- stay stopped */
11437    if (monitor_thread == AST_PTHREADT_STOP)
11438       return 0;
11439    ast_mutex_lock(&monlock);
11440    if (monitor_thread == pthread_self()) {
11441       ast_mutex_unlock(&monlock);
11442       ast_log(LOG_WARNING, "Cannot kill myself\n");
11443       return -1;
11444    }
11445    if (monitor_thread != AST_PTHREADT_NULL) {
11446       /* Wake up the thread */
11447       pthread_kill(monitor_thread, SIGURG);
11448    } else {
11449       /* Start a new monitor */
11450       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
11451          ast_mutex_unlock(&monlock);
11452          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
11453          return -1;
11454       }
11455    }
11456    ast_mutex_unlock(&monlock);
11457    return 0;
11458 }
11459 
11460 #if defined(HAVE_PRI)
11461 static int pri_resolve_span(int *span, int channel, int offset, struct dahdi_spaninfo *si)
11462 {
11463    int x;
11464    int trunkgroup;
11465    /* Get appropriate trunk group if there is one */
11466    trunkgroup = pris[*span].mastertrunkgroup;
11467    if (trunkgroup) {
11468       /* Select a specific trunk group */
11469       for (x = 0; x < NUM_SPANS; x++) {
11470          if (pris[x].pri.trunkgroup == trunkgroup) {
11471             *span = x;
11472             return 0;
11473          }
11474       }
11475       ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
11476       *span = -1;
11477    } else {
11478       if (pris[*span].pri.trunkgroup) {
11479          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);
11480          *span = -1;
11481       } else if (pris[*span].mastertrunkgroup) {
11482          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
11483          *span = -1;
11484       } else {
11485          if (si->totalchans == 31) {
11486             /* E1 */
11487             pris[*span].dchannels[0] = 16 + offset;
11488          } else if (si->totalchans == 24) {
11489             /* T1 or J1 */
11490             pris[*span].dchannels[0] = 24 + offset;
11491          } else if (si->totalchans == 3) {
11492             /* BRI */
11493             pris[*span].dchannels[0] = 3 + offset;
11494          } else {
11495             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);
11496             *span = -1;
11497             return 0;
11498          }
11499          pris[*span].pri.span = *span + 1;
11500       }
11501    }
11502    return 0;
11503 }
11504 #endif   /* defined(HAVE_PRI) */
11505 
11506 #if defined(HAVE_PRI)
11507 static int pri_create_trunkgroup(int trunkgroup, int *channels)
11508 {
11509    struct dahdi_spaninfo si;
11510    struct dahdi_params p;
11511    int fd;
11512    int span;
11513    int ospan=0;
11514    int x,y;
11515    for (x = 0; x < NUM_SPANS; x++) {
11516       if (pris[x].pri.trunkgroup == trunkgroup) {
11517          ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
11518          return -1;
11519       }
11520    }
11521    for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
11522       if (!channels[y])
11523          break;
11524       memset(&si, 0, sizeof(si));
11525       memset(&p, 0, sizeof(p));
11526       fd = open("/dev/dahdi/channel", O_RDWR);
11527       if (fd < 0) {
11528          ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
11529          return -1;
11530       }
11531       x = channels[y];
11532       if (ioctl(fd, DAHDI_SPECIFY, &x)) {
11533          ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
11534          close(fd);
11535          return -1;
11536       }
11537       if (ioctl(fd, DAHDI_GET_PARAMS, &p)) {
11538          ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
11539          return -1;
11540       }
11541       if (ioctl(fd, DAHDI_SPANSTAT, &si)) {
11542          ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d): %s\n", channels[y], p.spanno, strerror(errno));
11543          close(fd);
11544          return -1;
11545       }
11546       span = p.spanno - 1;
11547       if (pris[span].pri.trunkgroup) {
11548          ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].pri.trunkgroup);
11549          close(fd);
11550          return -1;
11551       }
11552       if (pris[span].pri.pvts[0]) {
11553          ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
11554          close(fd);
11555          return -1;
11556       }
11557       if (!y) {
11558          pris[span].pri.trunkgroup = trunkgroup;
11559          ospan = span;
11560       }
11561       pris[ospan].dchannels[y] = channels[y];
11562       pris[span].pri.span = span + 1;
11563       close(fd);
11564    }
11565    return 0;
11566 }
11567 #endif   /* defined(HAVE_PRI) */
11568 
11569 #if defined(HAVE_PRI)
11570 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
11571 {
11572    if (pris[span].mastertrunkgroup) {
11573       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);
11574       return -1;
11575    }
11576    pris[span].mastertrunkgroup = trunkgroup;
11577    pris[span].prilogicalspan = logicalspan;
11578    return 0;
11579 }
11580 #endif   /* defined(HAVE_PRI) */
11581 
11582 #if defined(HAVE_SS7)
11583 static unsigned int parse_pointcode(const char *pcstring)
11584 {
11585    unsigned int code1, code2, code3;
11586    int numvals;
11587 
11588    numvals = sscanf(pcstring, "%30d-%30d-%30d", &code1, &code2, &code3);
11589    if (numvals == 1)
11590       return code1;
11591    if (numvals == 3)
11592       return (code1 << 16) | (code2 << 8) | code3;
11593 
11594    return 0;
11595 }
11596 #endif   /* defined(HAVE_SS7) */
11597 
11598 #if defined(HAVE_SS7)
11599 static struct dahdi_ss7 * ss7_resolve_linkset(int linkset)
11600 {
11601    if ((linkset < 0) || (linkset >= NUM_SPANS))
11602       return NULL;
11603    else
11604       return &linksets[linkset - 1];
11605 }
11606 #endif   /* defined(HAVE_SS7) */
11607 
11608 #ifdef HAVE_OPENR2
11609 static void dahdi_r2_destroy_links(void)
11610 {
11611    int i = 0;
11612    if (!r2links) {
11613       return;
11614    }
11615    for (; i < r2links_count; i++) {
11616       if (r2links[i]->r2master != AST_PTHREADT_NULL) {
11617          pthread_cancel(r2links[i]->r2master);
11618          pthread_join(r2links[i]->r2master, NULL);
11619          openr2_context_delete(r2links[i]->protocol_context);
11620       }
11621       ast_free(r2links[i]);
11622    }
11623    ast_free(r2links);
11624    r2links = NULL;
11625    r2links_count = 0;
11626 }
11627 
11628 #define R2_LINK_CAPACITY 10
11629 static struct dahdi_mfcr2 *dahdi_r2_get_link(void)
11630 {
11631    struct dahdi_mfcr2 *new_r2link = NULL;
11632    struct dahdi_mfcr2 **new_r2links = NULL;
11633    /* this function is called just when starting up and no monitor threads have been launched,
11634       no need to lock monitored_count member */
11635    if (!r2links_count || (r2links[r2links_count - 1]->monitored_count == R2_LINK_CAPACITY)) {
11636       new_r2link = ast_calloc(1, sizeof(**r2links));
11637       if (!new_r2link) {
11638          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
11639          return NULL;
11640       }
11641       new_r2links = ast_realloc(r2links, ((r2links_count + 1) * sizeof(*r2links)));
11642       if (!new_r2links) {
11643          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
11644          ast_free(new_r2link);
11645          return NULL;
11646       }
11647       r2links = new_r2links;
11648       new_r2link->r2master = AST_PTHREADT_NULL;
11649       r2links[r2links_count] = new_r2link;
11650       r2links_count++;
11651       ast_log(LOG_DEBUG, "Created new R2 link!\n");
11652    }
11653    return r2links[r2links_count - 1];
11654 }
11655 
11656 static int dahdi_r2_set_context(struct dahdi_mfcr2 *r2_link, const struct dahdi_chan_conf *conf)
11657 {
11658    char tmplogdir[] = "/tmp";
11659    char logdir[OR2_MAX_PATH];
11660    int threshold = 0;
11661    int snres = 0;
11662    r2_link->protocol_context = openr2_context_new(NULL, &dahdi_r2_event_iface,
11663          &dahdi_r2_transcode_iface, conf->mfcr2.variant, conf->mfcr2.max_ani,
11664          conf->mfcr2.max_dnis);
11665    if (!r2_link->protocol_context) {
11666       return -1;
11667    }
11668    openr2_context_set_log_level(r2_link->protocol_context, conf->mfcr2.loglevel);
11669    openr2_context_set_ani_first(r2_link->protocol_context, conf->mfcr2.get_ani_first);
11670 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
11671    openr2_context_set_skip_category_request(r2_link->protocol_context, conf->mfcr2.skip_category_request);
11672 #endif
11673    openr2_context_set_mf_threshold(r2_link->protocol_context, threshold);
11674    openr2_context_set_mf_back_timeout(r2_link->protocol_context, conf->mfcr2.mfback_timeout);
11675    openr2_context_set_metering_pulse_timeout(r2_link->protocol_context, conf->mfcr2.metering_pulse_timeout);
11676    openr2_context_set_double_answer(r2_link->protocol_context, conf->mfcr2.double_answer);
11677    openr2_context_set_immediate_accept(r2_link->protocol_context, conf->mfcr2.immediate_accept);
11678    if (ast_strlen_zero(conf->mfcr2.logdir)) {
11679       if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
11680          ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
11681       }
11682    } else {
11683       snres = snprintf(logdir, sizeof(logdir), "%s/%s/%s", ast_config_AST_LOG_DIR, "mfcr2", conf->mfcr2.logdir);
11684       if (snres >= sizeof(logdir)) {
11685          ast_log(LOG_ERROR, "MFC/R2 logging directory truncated, using %s\n", tmplogdir);
11686          if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
11687             ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
11688          }
11689       } else {
11690          if (openr2_context_set_log_directory(r2_link->protocol_context, logdir)) {
11691             ast_log(LOG_ERROR, "Failed setting MFC/R2 log directory %s\n", logdir);
11692          }
11693       }
11694    }
11695    if (!ast_strlen_zero(conf->mfcr2.r2proto_file)) {
11696       if (openr2_context_configure_from_advanced_file(r2_link->protocol_context, conf->mfcr2.r2proto_file)) {
11697          ast_log(LOG_ERROR, "Failed to configure r2context from advanced configuration file %s\n", conf->mfcr2.r2proto_file);
11698       }
11699    }
11700    r2_link->monitored_count = 0;
11701    return 0;
11702 }
11703 #endif
11704 
11705 /* converts a DAHDI sigtype to signalling as can be configured from
11706  * chan_dahdi.conf.
11707  * While both have basically the same values, this will later be the
11708  * place to add filters and sanity checks
11709  */
11710 static int sigtype_to_signalling(int sigtype)
11711 {
11712    return sigtype;
11713 }
11714 
11715 /*!
11716  * \internal
11717  * \brief Get file name and channel number from (subdir,number)
11718  *
11719  * \param subdir name of the subdirectory under /dev/dahdi/
11720  * \param channel name of device file under /dev/dahdi/<subdir>/
11721  * \param path buffer to put file name in
11722  * \param pathlen maximal length of path
11723  *
11724  * \retval minor number of dahdi channel.
11725  * \retval -errno on error.
11726  */
11727 static int device2chan(const char *subdir, int channel, char *path, int pathlen)
11728 {
11729    struct stat stbuf;
11730    int      num;
11731 
11732    snprintf(path, pathlen, "/dev/dahdi/%s/%d", subdir, channel);
11733    if (stat(path, &stbuf) < 0) {
11734       ast_log(LOG_ERROR, "stat(%s) failed: %s\n", path, strerror(errno));
11735       return -errno;
11736    }
11737    if (!S_ISCHR(stbuf.st_mode)) {
11738       ast_log(LOG_ERROR, "%s: Not a character device file\n", path);
11739       return -EINVAL;
11740    }
11741    num = minor(stbuf.st_rdev);
11742    ast_log(LOG_DEBUG, "%s -> %d\n", path, num);
11743    return num;
11744 
11745 }
11746 
11747 /*!
11748  * \internal
11749  * \brief Initialize/create a channel interface.
11750  *
11751  * \param channel Channel interface number to initialize/create.
11752  * \param conf Configuration parameters to initialize interface with.
11753  * \param reloading What we are doing now:
11754  * 0 - initial module load,
11755  * 1 - module reload,
11756  * 2 - module restart
11757  *
11758  * \retval Interface-pointer initialized/created
11759  * \retval NULL if error
11760  */
11761 static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf, int reloading)
11762 {
11763    /* Make a dahdi_pvt structure for this interface */
11764    struct dahdi_pvt *tmp;/*!< Current channel structure initializing */
11765    char fn[80];
11766    struct dahdi_bufferinfo bi;
11767 
11768    int res;
11769    int span = 0;
11770    int here = 0;/*!< TRUE if the channel interface already exists. */
11771    int x;
11772    struct analog_pvt *analog_p = NULL;
11773    struct dahdi_params p;
11774 #if defined(HAVE_PRI)
11775    struct dahdi_spaninfo si;
11776    struct sig_pri_chan *pri_chan = NULL;
11777 #endif   /* defined(HAVE_PRI) */
11778 #if defined(HAVE_SS7)
11779    struct sig_ss7_chan *ss7_chan = NULL;
11780 #endif   /* defined(HAVE_SS7) */
11781 
11782    /* Search channel interface list to see if it already exists. */
11783    for (tmp = iflist; tmp; tmp = tmp->next) {
11784       if (!tmp->destroy) {
11785          if (tmp->channel == channel) {
11786             /* The channel interface already exists. */
11787             here = 1;
11788             break;
11789          }
11790          if (tmp->channel > channel) {
11791             /* No way it can be in the sorted list. */
11792             tmp = NULL;
11793             break;
11794          }
11795       }
11796    }
11797 
11798    if (!here && reloading != 1) {
11799       tmp = ast_calloc(1, sizeof(*tmp));
11800       if (!tmp) {
11801          return NULL;
11802       }
11803       tmp->cc_params = ast_cc_config_params_init();
11804       if (!tmp->cc_params) {
11805          ast_free(tmp);
11806          return NULL;
11807       }
11808       ast_mutex_init(&tmp->lock);
11809       ifcount++;
11810       for (x = 0; x < 3; x++)
11811          tmp->subs[x].dfd = -1;
11812       tmp->channel = channel;
11813       tmp->priindication_oob = conf->chan.priindication_oob;
11814    }
11815 
11816    if (tmp) {
11817       int chan_sig = conf->chan.sig;
11818 
11819       if (!here) {
11820          /* Can only get here if this is a new channel interface being created. */
11821          if ((channel != CHAN_PSEUDO)) {
11822             int count = 0;
11823 
11824             snprintf(fn, sizeof(fn), "%d", channel);
11825             /* Open non-blocking */
11826             tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
11827             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 */
11828                usleep(1);
11829                tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
11830                count++;
11831             }
11832             /* Allocate a DAHDI structure */
11833             if (tmp->subs[SUB_REAL].dfd < 0) {
11834                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);
11835                destroy_dahdi_pvt(tmp);
11836                return NULL;
11837             }
11838             memset(&p, 0, sizeof(p));
11839             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
11840             if (res < 0) {
11841                ast_log(LOG_ERROR, "Unable to get parameters: %s\n", strerror(errno));
11842                destroy_dahdi_pvt(tmp);
11843                return NULL;
11844             }
11845             if (conf->is_sig_auto)
11846                chan_sig = sigtype_to_signalling(p.sigtype);
11847             if (p.sigtype != (chan_sig & 0x3ffff)) {
11848                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));
11849                destroy_dahdi_pvt(tmp);
11850                return NULL;
11851             }
11852             tmp->law_default = p.curlaw;
11853             tmp->law = p.curlaw;
11854             tmp->span = p.spanno;
11855             span = p.spanno - 1;
11856          } else {
11857             chan_sig = 0;
11858          }
11859          tmp->sig = chan_sig;
11860          tmp->outsigmod = conf->chan.outsigmod;
11861 
11862          if (analog_lib_handles(chan_sig, tmp->radio, tmp->oprmode)) {
11863             analog_p = analog_new(dahdisig_to_analogsig(chan_sig), &dahdi_analog_callbacks, tmp);
11864             if (!analog_p) {
11865                destroy_dahdi_pvt(tmp);
11866                return NULL;
11867             }
11868             tmp->sig_pvt = analog_p;
11869          }
11870 #if defined(HAVE_SS7)
11871          if (chan_sig == SIG_SS7) {
11872             struct dahdi_ss7 *ss7;
11873             int clear = 0;
11874 
11875             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &clear)) {
11876                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
11877                destroy_dahdi_pvt(tmp);
11878                return NULL;
11879             }
11880 
11881             ss7 = ss7_resolve_linkset(cur_linkset);
11882             if (!ss7) {
11883                ast_log(LOG_ERROR, "Unable to find linkset %d\n", cur_linkset);
11884                destroy_dahdi_pvt(tmp);
11885                return NULL;
11886             }
11887             ss7->ss7.span = cur_linkset;
11888             if (cur_cicbeginswith < 0) {
11889                ast_log(LOG_ERROR, "Need to set cicbeginswith for the channels!\n");
11890                destroy_dahdi_pvt(tmp);
11891                return NULL;
11892             }
11893             ss7_chan = sig_ss7_chan_new(tmp, &dahdi_ss7_callbacks, &ss7->ss7);
11894             if (!ss7_chan) {
11895                destroy_dahdi_pvt(tmp);
11896                return NULL;
11897             }
11898             tmp->sig_pvt = ss7_chan;
11899             tmp->ss7 = &ss7->ss7;
11900 
11901             ss7_chan->channel = tmp->channel;
11902             ss7_chan->cic = cur_cicbeginswith++;
11903 
11904             /* DB: Add CIC's DPC information */
11905             ss7_chan->dpc = cur_defaultdpc;
11906 
11907             ss7->ss7.pvts[ss7->ss7.numchans++] = ss7_chan;
11908 
11909             ast_copy_string(ss7->ss7.internationalprefix, conf->ss7.ss7.internationalprefix, sizeof(ss7->ss7.internationalprefix));
11910             ast_copy_string(ss7->ss7.nationalprefix, conf->ss7.ss7.nationalprefix, sizeof(ss7->ss7.nationalprefix));
11911             ast_copy_string(ss7->ss7.subscriberprefix, conf->ss7.ss7.subscriberprefix, sizeof(ss7->ss7.subscriberprefix));
11912             ast_copy_string(ss7->ss7.unknownprefix, conf->ss7.ss7.unknownprefix, sizeof(ss7->ss7.unknownprefix));
11913 
11914             ss7->ss7.called_nai = conf->ss7.ss7.called_nai;
11915             ss7->ss7.calling_nai = conf->ss7.ss7.calling_nai;
11916          }
11917 #endif   /* defined(HAVE_SS7) */
11918 #ifdef HAVE_OPENR2
11919          if (chan_sig == SIG_MFCR2) {
11920             struct dahdi_mfcr2 *r2_link;
11921             r2_link = dahdi_r2_get_link();
11922             if (!r2_link) {
11923                ast_log(LOG_WARNING, "Cannot get another R2 DAHDI context!\n");
11924                destroy_dahdi_pvt(tmp);
11925                return NULL;
11926             }
11927             if (!r2_link->protocol_context && dahdi_r2_set_context(r2_link, conf)) {
11928                ast_log(LOG_ERROR, "Cannot create OpenR2 protocol context.\n");
11929                destroy_dahdi_pvt(tmp);
11930                return NULL;
11931             }
11932             if (r2_link->numchans == ARRAY_LEN(r2_link->pvts)) {
11933                ast_log(LOG_ERROR, "Cannot add more channels to this link!\n");
11934                destroy_dahdi_pvt(tmp);
11935                return NULL;
11936             }
11937             r2_link->pvts[r2_link->numchans++] = tmp;
11938             tmp->r2chan = openr2_chan_new_from_fd(r2_link->protocol_context,
11939                                         tmp->subs[SUB_REAL].dfd,
11940                                         NULL, NULL);
11941             if (!tmp->r2chan) {
11942                openr2_liberr_t err = openr2_context_get_last_error(r2_link->protocol_context);
11943                ast_log(LOG_ERROR, "Cannot create OpenR2 channel: %s\n", openr2_context_error_string(err));
11944                destroy_dahdi_pvt(tmp);
11945                return NULL;
11946             }
11947             tmp->mfcr2 = r2_link;
11948             if (conf->mfcr2.call_files) {
11949                openr2_chan_enable_call_files(tmp->r2chan);
11950             }
11951             openr2_chan_set_client_data(tmp->r2chan, tmp);
11952             /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
11953             openr2_chan_set_logging_func(tmp->r2chan, (openr2_logging_func_t)dahdi_r2_on_chan_log);
11954             openr2_chan_set_log_level(tmp->r2chan, conf->mfcr2.loglevel);
11955             tmp->mfcr2_category = conf->mfcr2.category;
11956             tmp->mfcr2_charge_calls = conf->mfcr2.charge_calls;
11957             tmp->mfcr2_allow_collect_calls = conf->mfcr2.allow_collect_calls;
11958             tmp->mfcr2_forced_release = conf->mfcr2.forced_release;
11959             tmp->mfcr2_accept_on_offer = conf->mfcr2.accept_on_offer;
11960             tmp->mfcr2call = 0;
11961             tmp->mfcr2_dnis_index = 0;
11962             tmp->mfcr2_ani_index = 0;
11963             r2_link->monitored_count++;
11964          }
11965 #endif
11966 #ifdef HAVE_PRI
11967          if (dahdi_sig_pri_lib_handles(chan_sig)) {
11968             int offset;
11969             int matchesdchan;
11970             int x,y;
11971             int myswitchtype = 0;
11972 
11973             offset = 0;
11974             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &offset)) {
11975                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
11976                destroy_dahdi_pvt(tmp);
11977                return NULL;
11978             }
11979             if (span >= NUM_SPANS) {
11980                ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
11981                destroy_dahdi_pvt(tmp);
11982                return NULL;
11983             } else {
11984                si.spanno = 0;
11985                if (ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SPANSTAT,&si) == -1) {
11986                   ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
11987                   destroy_dahdi_pvt(tmp);
11988                   return NULL;
11989                }
11990                /* Store the logical span first based upon the real span */
11991                tmp->logicalspan = pris[span].prilogicalspan;
11992                pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
11993                if (span < 0) {
11994                   ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
11995                   destroy_dahdi_pvt(tmp);
11996                   return NULL;
11997                }
11998                myswitchtype = conf->pri.pri.switchtype;
11999                /* Make sure this isn't a d-channel */
12000                matchesdchan=0;
12001                for (x = 0; x < NUM_SPANS; x++) {
12002                   for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
12003                      if (pris[x].dchannels[y] == tmp->channel) {
12004                         matchesdchan = 1;
12005                         break;
12006                      }
12007                   }
12008                }
12009                if (!matchesdchan) {
12010                   if (pris[span].pri.nodetype && (pris[span].pri.nodetype != conf->pri.pri.nodetype)) {
12011                      ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].pri.nodetype));
12012                      destroy_dahdi_pvt(tmp);
12013                      return NULL;
12014                   }
12015                   if (pris[span].pri.switchtype && (pris[span].pri.switchtype != myswitchtype)) {
12016                      ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].pri.switchtype));
12017                      destroy_dahdi_pvt(tmp);
12018                      return NULL;
12019                   }
12020                   if ((pris[span].pri.dialplan) && (pris[span].pri.dialplan != conf->pri.pri.dialplan)) {
12021                      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));
12022                      destroy_dahdi_pvt(tmp);
12023                      return NULL;
12024                   }
12025                   if (!ast_strlen_zero(pris[span].pri.idledial) && strcmp(pris[span].pri.idledial, conf->pri.pri.idledial)) {
12026                      ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf->pri.pri.idledial);
12027                      destroy_dahdi_pvt(tmp);
12028                      return NULL;
12029                   }
12030                   if (!ast_strlen_zero(pris[span].pri.idleext) && strcmp(pris[span].pri.idleext, conf->pri.pri.idleext)) {
12031                      ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf->pri.pri.idleext);
12032                      destroy_dahdi_pvt(tmp);
12033                      return NULL;
12034                   }
12035                   if (pris[span].pri.minunused && (pris[span].pri.minunused != conf->pri.pri.minunused)) {
12036                      ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf->pri.pri.minunused);
12037                      destroy_dahdi_pvt(tmp);
12038                      return NULL;
12039                   }
12040                   if (pris[span].pri.minidle && (pris[span].pri.minidle != conf->pri.pri.minidle)) {
12041                      ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf->pri.pri.minidle);
12042                      destroy_dahdi_pvt(tmp);
12043                      return NULL;
12044                   }
12045                   if (pris[span].pri.numchans >= ARRAY_LEN(pris[span].pri.pvts)) {
12046                      ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
12047                         pris[span].pri.trunkgroup);
12048                      destroy_dahdi_pvt(tmp);
12049                      return NULL;
12050                   }
12051 
12052                   ast_debug(4, "Adding callbacks %p to chan %d\n", &dahdi_pri_callbacks, tmp->channel);
12053                   pri_chan = sig_pri_chan_new(tmp, &dahdi_pri_callbacks, &pris[span].pri, tmp->logicalspan, p.chanpos, pris[span].mastertrunkgroup);
12054                   if (!pri_chan) {
12055                      destroy_dahdi_pvt(tmp);
12056                      return NULL;
12057                   }
12058                   tmp->sig_pvt = pri_chan;
12059                   tmp->pri = &pris[span].pri;
12060 
12061                   tmp->priexclusive = conf->chan.priexclusive;
12062 
12063                   if (!tmp->pri->cc_params) {
12064                      tmp->pri->cc_params = ast_cc_config_params_init();
12065                      if (!tmp->pri->cc_params) {
12066                         destroy_dahdi_pvt(tmp);
12067                         return NULL;
12068                      }
12069                   }
12070                   ast_cc_copy_config_params(tmp->pri->cc_params,
12071                      conf->chan.cc_params);
12072 
12073                   pris[span].pri.sig = chan_sig;
12074                   pris[span].pri.nodetype = conf->pri.pri.nodetype;
12075                   pris[span].pri.switchtype = myswitchtype;
12076                   pris[span].pri.nsf = conf->pri.pri.nsf;
12077                   pris[span].pri.dialplan = conf->pri.pri.dialplan;
12078                   pris[span].pri.localdialplan = conf->pri.pri.localdialplan;
12079                   pris[span].pri.pvts[pris[span].pri.numchans++] = tmp->sig_pvt;
12080                   pris[span].pri.minunused = conf->pri.pri.minunused;
12081                   pris[span].pri.minidle = conf->pri.pri.minidle;
12082                   pris[span].pri.overlapdial = conf->pri.pri.overlapdial;
12083                   pris[span].pri.qsigchannelmapping = conf->pri.pri.qsigchannelmapping;
12084                   pris[span].pri.discardremoteholdretrieval = conf->pri.pri.discardremoteholdretrieval;
12085 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12086                   pris[span].pri.enable_service_message_support = conf->pri.pri.enable_service_message_support;
12087 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
12088 #ifdef HAVE_PRI_INBANDDISCONNECT
12089                   pris[span].pri.inbanddisconnect = conf->pri.pri.inbanddisconnect;
12090 #endif
12091 #if defined(HAVE_PRI_CALL_HOLD)
12092                   pris[span].pri.hold_disconnect_transfer =
12093                      conf->pri.pri.hold_disconnect_transfer;
12094 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
12095 #if defined(HAVE_PRI_CCSS)
12096                   pris[span].pri.cc_ptmp_recall_mode =
12097                      conf->pri.pri.cc_ptmp_recall_mode;
12098                   pris[span].pri.cc_qsig_signaling_link_req =
12099                      conf->pri.pri.cc_qsig_signaling_link_req;
12100                   pris[span].pri.cc_qsig_signaling_link_rsp =
12101                      conf->pri.pri.cc_qsig_signaling_link_rsp;
12102 #endif   /* defined(HAVE_PRI_CCSS) */
12103 #if defined(HAVE_PRI_CALL_WAITING)
12104                   pris[span].pri.max_call_waiting_calls =
12105                      conf->pri.pri.max_call_waiting_calls;
12106                   pris[span].pri.allow_call_waiting_calls =
12107                      conf->pri.pri.allow_call_waiting_calls;
12108 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12109                   pris[span].pri.transfer = conf->chan.transfer;
12110                   pris[span].pri.facilityenable = conf->pri.pri.facilityenable;
12111 #if defined(HAVE_PRI_AOC_EVENTS)
12112                   pris[span].pri.aoc_passthrough_flag = conf->pri.pri.aoc_passthrough_flag;
12113                   pris[span].pri.aoce_delayhangup = conf->pri.pri.aoce_delayhangup;
12114 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
12115                   pris[span].pri.append_msn_to_user_tag = conf->pri.pri.append_msn_to_user_tag;
12116                   ast_copy_string(pris[span].pri.initial_user_tag, conf->chan.cid_tag, sizeof(pris[span].pri.initial_user_tag));
12117                   ast_copy_string(pris[span].pri.msn_list, conf->pri.pri.msn_list, sizeof(pris[span].pri.msn_list));
12118 #if defined(HAVE_PRI_MWI)
12119                   ast_copy_string(pris[span].pri.mwi_mailboxes,
12120                      conf->pri.pri.mwi_mailboxes,
12121                      sizeof(pris[span].pri.mwi_mailboxes));
12122 #endif   /* defined(HAVE_PRI_MWI) */
12123                   ast_copy_string(pris[span].pri.idledial, conf->pri.pri.idledial, sizeof(pris[span].pri.idledial));
12124                   ast_copy_string(pris[span].pri.idleext, conf->pri.pri.idleext, sizeof(pris[span].pri.idleext));
12125                   ast_copy_string(pris[span].pri.internationalprefix, conf->pri.pri.internationalprefix, sizeof(pris[span].pri.internationalprefix));
12126                   ast_copy_string(pris[span].pri.nationalprefix, conf->pri.pri.nationalprefix, sizeof(pris[span].pri.nationalprefix));
12127                   ast_copy_string(pris[span].pri.localprefix, conf->pri.pri.localprefix, sizeof(pris[span].pri.localprefix));
12128                   ast_copy_string(pris[span].pri.privateprefix, conf->pri.pri.privateprefix, sizeof(pris[span].pri.privateprefix));
12129                   ast_copy_string(pris[span].pri.unknownprefix, conf->pri.pri.unknownprefix, sizeof(pris[span].pri.unknownprefix));
12130                   pris[span].pri.resetinterval = conf->pri.pri.resetinterval;
12131 
12132                   for (x = 0; x < PRI_MAX_TIMERS; x++) {
12133                      pris[span].pri.pritimers[x] = conf->pri.pri.pritimers[x];
12134                   }
12135 
12136 #if defined(HAVE_PRI_CALL_WAITING)
12137                   /* Channel initial config parameters. */
12138                   pris[span].pri.ch_cfg.stripmsd = conf->chan.stripmsd;
12139                   pris[span].pri.ch_cfg.hidecallerid = conf->chan.hidecallerid;
12140                   pris[span].pri.ch_cfg.hidecalleridname = conf->chan.hidecalleridname;
12141                   pris[span].pri.ch_cfg.immediate = conf->chan.immediate;
12142                   pris[span].pri.ch_cfg.priexclusive = conf->chan.priexclusive;
12143                   pris[span].pri.ch_cfg.priindication_oob = conf->chan.priindication_oob;
12144                   pris[span].pri.ch_cfg.use_callerid = conf->chan.use_callerid;
12145                   pris[span].pri.ch_cfg.use_callingpres = conf->chan.use_callingpres;
12146                   ast_copy_string(pris[span].pri.ch_cfg.context, conf->chan.context, sizeof(pris[span].pri.ch_cfg.context));
12147                   ast_copy_string(pris[span].pri.ch_cfg.mohinterpret, conf->chan.mohinterpret, sizeof(pris[span].pri.ch_cfg.mohinterpret));
12148 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12149                } else {
12150                   ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", p.chanpos);
12151                   destroy_dahdi_pvt(tmp);
12152                   return NULL;
12153                }
12154             }
12155          }
12156 #endif
12157       } else {
12158          /* already exists in interface list */
12159          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));
12160          chan_sig = tmp->sig;
12161          if (tmp->subs[SUB_REAL].dfd > -1) {
12162             memset(&p, 0, sizeof(p));
12163             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12164          }
12165       }
12166       /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
12167       switch (chan_sig) {
12168       case SIG_FXSKS:
12169       case SIG_FXSLS:
12170       case SIG_EM:
12171       case SIG_EM_E1:
12172       case SIG_EMWINK:
12173       case SIG_FEATD:
12174       case SIG_FEATDMF:
12175       case SIG_FEATDMF_TA:
12176       case SIG_FEATB:
12177       case SIG_E911:
12178       case SIG_SF:
12179       case SIG_SFWINK:
12180       case SIG_FGC_CAMA:
12181       case SIG_FGC_CAMAMF:
12182       case SIG_SF_FEATD:
12183       case SIG_SF_FEATDMF:
12184       case SIG_SF_FEATB:
12185          p.starttime = 250;
12186          break;
12187       }
12188 
12189       if (tmp->radio) {
12190          /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
12191          p.channo = channel;
12192          p.rxwinktime = 1;
12193          p.rxflashtime = 1;
12194          p.starttime = 1;
12195          p.debouncetime = 5;
12196       } else {
12197          p.channo = channel;
12198          /* Override timing settings based on config file */
12199          if (conf->timing.prewinktime >= 0)
12200             p.prewinktime = conf->timing.prewinktime;
12201          if (conf->timing.preflashtime >= 0)
12202             p.preflashtime = conf->timing.preflashtime;
12203          if (conf->timing.winktime >= 0)
12204             p.winktime = conf->timing.winktime;
12205          if (conf->timing.flashtime >= 0)
12206             p.flashtime = conf->timing.flashtime;
12207          if (conf->timing.starttime >= 0)
12208             p.starttime = conf->timing.starttime;
12209          if (conf->timing.rxwinktime >= 0)
12210             p.rxwinktime = conf->timing.rxwinktime;
12211          if (conf->timing.rxflashtime >= 0)
12212             p.rxflashtime = conf->timing.rxflashtime;
12213          if (conf->timing.debouncetime >= 0)
12214             p.debouncetime = conf->timing.debouncetime;
12215       }
12216 
12217       /* don't set parms on a pseudo-channel */
12218       if (tmp->subs[SUB_REAL].dfd >= 0)
12219       {
12220          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_PARAMS, &p);
12221          if (res < 0) {
12222             ast_log(LOG_ERROR, "Unable to set parameters: %s\n", strerror(errno));
12223             destroy_dahdi_pvt(tmp);
12224             return NULL;
12225          }
12226       }
12227 #if 1
12228       if (!here && (tmp->subs[SUB_REAL].dfd > -1)) {
12229          memset(&bi, 0, sizeof(bi));
12230          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
12231          if (!res) {
12232             bi.txbufpolicy = conf->chan.buf_policy;
12233             bi.rxbufpolicy = conf->chan.buf_policy;
12234             bi.numbufs = conf->chan.buf_no;
12235             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
12236             if (res < 0) {
12237                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", channel, strerror(errno));
12238             }
12239          } else {
12240             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", channel, strerror(errno));
12241          }
12242          tmp->buf_policy = conf->chan.buf_policy;
12243          tmp->buf_no = conf->chan.buf_no;
12244          tmp->usefaxbuffers = conf->chan.usefaxbuffers;
12245          tmp->faxbuf_policy = conf->chan.faxbuf_policy;
12246          tmp->faxbuf_no = conf->chan.faxbuf_no;
12247          /* This is not as gnarly as it may first appear.  If the ioctl above failed, we'd be setting
12248           * tmp->bufsize to zero which would cause subsequent faxbuffer-related ioctl calls to fail.
12249           * The reason the ioctl call above failed should to be determined before worrying about the
12250           * faxbuffer-related ioctl calls */
12251          tmp->bufsize = bi.bufsize;
12252       }
12253 #endif
12254       tmp->immediate = conf->chan.immediate;
12255       tmp->transfertobusy = conf->chan.transfertobusy;
12256       if (chan_sig & __DAHDI_SIG_FXS) {
12257          tmp->mwimonitor_fsk = conf->chan.mwimonitor_fsk;
12258          tmp->mwimonitor_neon = conf->chan.mwimonitor_neon;
12259          tmp->mwimonitor_rpas = conf->chan.mwimonitor_rpas;
12260       }
12261       tmp->ringt_base = ringt_base;
12262       tmp->firstradio = 0;
12263       if ((chan_sig == SIG_FXOKS) || (chan_sig == SIG_FXOLS) || (chan_sig == SIG_FXOGS))
12264          tmp->permcallwaiting = conf->chan.callwaiting;
12265       else
12266          tmp->permcallwaiting = 0;
12267       /* Flag to destroy the channel must be cleared on new mkif.  Part of changes for reload to work */
12268       tmp->destroy = 0;
12269       tmp->drings = conf->chan.drings;
12270 
12271       /* 10 is a nice default. */
12272       if (tmp->drings.ringnum[0].range == 0)
12273          tmp->drings.ringnum[0].range = 10;
12274       if (tmp->drings.ringnum[1].range == 0)
12275          tmp->drings.ringnum[1].range = 10;
12276       if (tmp->drings.ringnum[2].range == 0)
12277          tmp->drings.ringnum[2].range = 10;
12278 
12279       tmp->usedistinctiveringdetection = usedistinctiveringdetection;
12280       tmp->callwaitingcallerid = conf->chan.callwaitingcallerid;
12281       tmp->threewaycalling = conf->chan.threewaycalling;
12282       tmp->adsi = conf->chan.adsi;
12283       tmp->use_smdi = conf->chan.use_smdi;
12284       tmp->permhidecallerid = conf->chan.hidecallerid;
12285       tmp->hidecalleridname = conf->chan.hidecalleridname;
12286       tmp->callreturn = conf->chan.callreturn;
12287       tmp->echocancel = conf->chan.echocancel;
12288       tmp->echotraining = conf->chan.echotraining;
12289       tmp->pulse = conf->chan.pulse;
12290       if (tmp->echocancel.head.tap_length) {
12291          tmp->echocanbridged = conf->chan.echocanbridged;
12292       } else {
12293          if (conf->chan.echocanbridged)
12294             ast_log(LOG_NOTICE, "echocancelwhenbridged requires echocancel to be enabled; ignoring\n");
12295          tmp->echocanbridged = 0;
12296       }
12297       tmp->busydetect = conf->chan.busydetect;
12298       tmp->busycount = conf->chan.busycount;
12299       tmp->busy_tonelength = conf->chan.busy_tonelength;
12300       tmp->busy_quietlength = conf->chan.busy_quietlength;
12301       tmp->callprogress = conf->chan.callprogress;
12302       tmp->waitfordialtone = conf->chan.waitfordialtone;
12303       tmp->cancallforward = conf->chan.cancallforward;
12304       tmp->dtmfrelax = conf->chan.dtmfrelax;
12305       tmp->callwaiting = tmp->permcallwaiting;
12306       tmp->hidecallerid = tmp->permhidecallerid;
12307       tmp->channel = channel;
12308       tmp->stripmsd = conf->chan.stripmsd;
12309       tmp->use_callerid = conf->chan.use_callerid;
12310       tmp->cid_signalling = conf->chan.cid_signalling;
12311       tmp->cid_start = conf->chan.cid_start;
12312       tmp->dahditrcallerid = conf->chan.dahditrcallerid;
12313       tmp->restrictcid = conf->chan.restrictcid;
12314       tmp->use_callingpres = conf->chan.use_callingpres;
12315       if (tmp->usedistinctiveringdetection) {
12316          if (!tmp->use_callerid) {
12317             ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
12318             tmp->use_callerid = 1;
12319          }
12320       }
12321 
12322       if (tmp->cid_signalling == CID_SIG_SMDI) {
12323          if (!tmp->use_smdi) {
12324             ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
12325             tmp->use_smdi = 1;
12326          }
12327       }
12328       if (tmp->use_smdi) {
12329          tmp->smdi_iface = ast_smdi_interface_find(conf->smdi_port);
12330          if (!(tmp->smdi_iface)) {
12331             ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
12332             tmp->use_smdi = 0;
12333          }
12334       }
12335 
12336       ast_copy_string(tmp->accountcode, conf->chan.accountcode, sizeof(tmp->accountcode));
12337       tmp->amaflags = conf->chan.amaflags;
12338       if (!here) {
12339          tmp->confno = -1;
12340          tmp->propconfno = -1;
12341       }
12342       tmp->canpark = conf->chan.canpark;
12343       tmp->transfer = conf->chan.transfer;
12344       ast_copy_string(tmp->defcontext,conf->chan.context,sizeof(tmp->defcontext));
12345       ast_copy_string(tmp->language, conf->chan.language, sizeof(tmp->language));
12346       ast_copy_string(tmp->mohinterpret, conf->chan.mohinterpret, sizeof(tmp->mohinterpret));
12347       ast_copy_string(tmp->mohsuggest, conf->chan.mohsuggest, sizeof(tmp->mohsuggest));
12348       ast_copy_string(tmp->context, conf->chan.context, sizeof(tmp->context));
12349       ast_copy_string(tmp->parkinglot, conf->chan.parkinglot, sizeof(tmp->parkinglot));
12350       tmp->cid_ton = 0;
12351       if (analog_lib_handles(tmp->sig, tmp->radio, tmp->oprmode)) {
12352          ast_copy_string(tmp->cid_num, conf->chan.cid_num, sizeof(tmp->cid_num));
12353          ast_copy_string(tmp->cid_name, conf->chan.cid_name, sizeof(tmp->cid_name));
12354       } else {
12355          tmp->cid_num[0] = '\0';
12356          tmp->cid_name[0] = '\0';
12357       }
12358 #if defined(HAVE_PRI)
12359       if (dahdi_sig_pri_lib_handles(tmp->sig)) {
12360          tmp->cid_tag[0] = '\0';
12361       } else
12362 #endif   /* defined(HAVE_PRI) */
12363       {
12364          ast_copy_string(tmp->cid_tag, conf->chan.cid_tag, sizeof(tmp->cid_tag));
12365       }
12366       tmp->cid_subaddr[0] = '\0';
12367       ast_copy_string(tmp->mailbox, conf->chan.mailbox, sizeof(tmp->mailbox));
12368       if (channel != CHAN_PSEUDO && !ast_strlen_zero(tmp->mailbox)) {
12369          char *mailbox, *context;
12370          mailbox = context = ast_strdupa(tmp->mailbox);
12371          strsep(&context, "@");
12372          if (ast_strlen_zero(context))
12373             context = "default";
12374          tmp->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "Dahdi MWI subscription", NULL,
12375             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12376             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12377             AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
12378             AST_EVENT_IE_END);
12379       }
12380 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
12381       tmp->mwisend_setting = conf->chan.mwisend_setting;
12382       tmp->mwisend_fsk  = conf->chan.mwisend_fsk;
12383       tmp->mwisend_rpas = conf->chan.mwisend_rpas;
12384 #endif
12385 
12386       tmp->group = conf->chan.group;
12387       tmp->callgroup = conf->chan.callgroup;
12388       tmp->pickupgroup= conf->chan.pickupgroup;
12389       if (conf->chan.vars) {
12390          struct ast_variable *v, *tmpvar;
12391                    for (v = conf->chan.vars ; v ; v = v->next) {
12392                          if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
12393                                   tmpvar->next = tmp->vars;
12394                                    tmp->vars = tmpvar;
12395                            }
12396                   }
12397       }
12398       tmp->cid_rxgain = conf->chan.cid_rxgain;
12399       tmp->rxgain = conf->chan.rxgain;
12400       tmp->txgain = conf->chan.txgain;
12401       tmp->txdrc = conf->chan.txdrc;
12402       tmp->rxdrc = conf->chan.rxdrc;
12403       tmp->tonezone = conf->chan.tonezone;
12404       if (tmp->subs[SUB_REAL].dfd > -1) {
12405          set_actual_gain(tmp->subs[SUB_REAL].dfd, tmp->rxgain, tmp->txgain, tmp->rxdrc, tmp->txdrc, tmp->law);
12406          if (tmp->dsp)
12407             ast_dsp_set_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
12408          update_conf(tmp);
12409          if (!here) {
12410             switch (chan_sig) {
12411             case SIG_PRI_LIB_HANDLE_CASES:
12412             case SIG_SS7:
12413             case SIG_MFCR2:
12414                break;
12415             default:
12416                /* Hang it up to be sure it's good */
12417                dahdi_set_hook(tmp->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
12418                break;
12419             }
12420          }
12421          ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SETTONEZONE,&tmp->tonezone);
12422 #ifdef HAVE_PRI
12423          memset(&si, 0, sizeof(si));
12424          if (ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SPANSTAT,&si) == -1) {
12425             ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
12426             destroy_dahdi_pvt(tmp);
12427             return NULL;
12428          }
12429 #endif
12430          if ((res = get_alarms(tmp)) != DAHDI_ALARM_NONE) {
12431             /* the dchannel is down so put the channel in alarm */
12432             switch (tmp->sig) {
12433 #ifdef HAVE_PRI
12434             case SIG_PRI_LIB_HANDLE_CASES:
12435                sig_pri_chan_alarm_notify(tmp->sig_pvt, si.alarms);
12436                break;
12437 #endif
12438 #if defined(HAVE_SS7)
12439             case SIG_SS7:
12440                sig_ss7_set_alarm(tmp->sig_pvt, 1);
12441                break;
12442 #endif   /* defined(HAVE_SS7) */
12443             default:
12444                /* The only sig submodule left should be sig_analog. */
12445                analog_p = tmp->sig_pvt;
12446                if (analog_p) {
12447                   analog_p->inalarm = 1;
12448                }
12449                tmp->inalarm = 1;
12450                break;
12451             }
12452             handle_alarms(tmp, res);
12453          }
12454       }
12455 
12456       tmp->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
12457       tmp->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
12458       tmp->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
12459       tmp->sendcalleridafter = conf->chan.sendcalleridafter;
12460       ast_cc_copy_config_params(tmp->cc_params, conf->chan.cc_params);
12461 
12462       if (!here) {
12463          tmp->locallyblocked = 0;
12464          tmp->remotelyblocked = 0;
12465          switch (tmp->sig) {
12466 #if defined(HAVE_PRI)
12467          case SIG_PRI_LIB_HANDLE_CASES:
12468             tmp->inservice = 1;/* Inservice until actually implemented. */
12469 #if defined(HAVE_PRI_SERVICE_MESSAGES)
12470             ((struct sig_pri_chan *) tmp->sig_pvt)->service_status = 0;
12471             if (chan_sig == SIG_PRI) {
12472                char db_chan_name[20];
12473                char db_answer[5];
12474 
12475                /*
12476                 * Initialize the active out-of-service status
12477                 * and delete any record if the feature is not enabled.
12478                 */
12479                snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, tmp->channel);
12480                if (!ast_db_get(db_chan_name, SRVST_DBKEY, db_answer, sizeof(db_answer))) {
12481                   unsigned *why;
12482 
12483                   why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
12484                   if (tmp->pri->enable_service_message_support) {
12485                      char state;
12486 
12487                      sscanf(db_answer, "%1c:%30u", &state, why);
12488 
12489                      /* Ensure that only the implemented bits could be set.*/
12490                      *why &= (SRVST_NEAREND | SRVST_FAREND);
12491                   }
12492                   if (!*why) {
12493                      ast_db_del(db_chan_name, SRVST_DBKEY);
12494                   }
12495                }
12496             }
12497 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
12498             break;
12499 #endif   /* defined(HAVE_PRI) */
12500 #if defined(HAVE_SS7)
12501          case SIG_SS7:
12502             tmp->inservice = 0;
12503             break;
12504 #endif   /* defined(HAVE_SS7) */
12505          default:
12506              /* We default to in service on protocols that don't have a reset */
12507             tmp->inservice = 1;
12508             break;
12509          }
12510       }
12511 
12512       switch (tmp->sig) {
12513 #if defined(HAVE_PRI)
12514       case SIG_PRI_LIB_HANDLE_CASES:
12515          if (pri_chan) {
12516             pri_chan->channel = tmp->channel;
12517             pri_chan->hidecallerid = tmp->hidecallerid;
12518             pri_chan->hidecalleridname = tmp->hidecalleridname;
12519             pri_chan->immediate = tmp->immediate;
12520             pri_chan->inalarm = tmp->inalarm;
12521             pri_chan->priexclusive = tmp->priexclusive;
12522             pri_chan->priindication_oob = tmp->priindication_oob;
12523             pri_chan->use_callerid = tmp->use_callerid;
12524             pri_chan->use_callingpres = tmp->use_callingpres;
12525             ast_copy_string(pri_chan->context, tmp->context,
12526                sizeof(pri_chan->context));
12527             ast_copy_string(pri_chan->mohinterpret, tmp->mohinterpret,
12528                sizeof(pri_chan->mohinterpret));
12529             pri_chan->stripmsd = tmp->stripmsd;
12530          }
12531          break;
12532 #endif   /* defined(HAVE_PRI) */
12533 #if defined(HAVE_SS7)
12534       case SIG_SS7:
12535          if (ss7_chan) {
12536             ss7_chan->inalarm = tmp->inalarm;
12537 
12538             ss7_chan->stripmsd = tmp->stripmsd;
12539             ss7_chan->hidecallerid = tmp->hidecallerid;
12540             ss7_chan->use_callerid = tmp->use_callerid;
12541             ss7_chan->use_callingpres = tmp->use_callingpres;
12542             ss7_chan->immediate = tmp->immediate;
12543             ss7_chan->locallyblocked = tmp->locallyblocked;
12544             ss7_chan->remotelyblocked = tmp->remotelyblocked;
12545             ast_copy_string(ss7_chan->context, tmp->context,
12546                sizeof(ss7_chan->context));
12547             ast_copy_string(ss7_chan->mohinterpret, tmp->mohinterpret,
12548                sizeof(ss7_chan->mohinterpret));
12549          }
12550          break;
12551 #endif   /* defined(HAVE_SS7) */
12552       default:
12553          /* The only sig submodule left should be sig_analog. */
12554          analog_p = tmp->sig_pvt;
12555          if (analog_p) {
12556             analog_p->channel = tmp->channel;
12557             analog_p->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
12558             analog_p->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
12559             analog_p->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
12560             analog_p->permcallwaiting = conf->chan.callwaiting; /* permcallwaiting possibly modified in analog_config_complete */
12561             analog_p->callreturn = conf->chan.callreturn;
12562             analog_p->cancallforward = conf->chan.cancallforward;
12563             analog_p->canpark = conf->chan.canpark;
12564             analog_p->dahditrcallerid = conf->chan.dahditrcallerid;
12565             analog_p->immediate = conf->chan.immediate;
12566             analog_p->permhidecallerid = conf->chan.permhidecallerid;
12567             analog_p->pulse = conf->chan.pulse;
12568             analog_p->threewaycalling = conf->chan.threewaycalling;
12569             analog_p->transfer = conf->chan.transfer;
12570             analog_p->transfertobusy = conf->chan.transfertobusy;
12571             analog_p->use_callerid = conf->chan.use_callerid;
12572             analog_p->outsigmod = ANALOG_SIG_NONE;
12573             analog_p->echotraining = conf->chan.echotraining;
12574             analog_p->cid_signalling = conf->chan.cid_signalling;
12575             analog_p->stripmsd = conf->chan.stripmsd;
12576             switch (conf->chan.cid_start) {
12577             case CID_START_POLARITY:
12578                analog_p->cid_start = ANALOG_CID_START_POLARITY;
12579                break;
12580             case CID_START_POLARITY_IN:
12581                analog_p->cid_start = ANALOG_CID_START_POLARITY_IN;
12582                break;
12583             case CID_START_DTMF_NOALERT:
12584                analog_p->cid_start = ANALOG_CID_START_DTMF_NOALERT;
12585                break;
12586             default:
12587                analog_p->cid_start = ANALOG_CID_START_RING;
12588                break;
12589             }
12590             analog_p->callwaitingcallerid = conf->chan.callwaitingcallerid;
12591             analog_p->usedistinctiveringdetection = conf->chan.usedistinctiveringdetection;
12592             analog_p->ringt = conf->chan.ringt;
12593             analog_p->ringt_base = ringt_base;
12594             analog_p->chan_tech = &dahdi_tech;
12595             analog_p->onhooktime = time(NULL);
12596             if (chan_sig & __DAHDI_SIG_FXO) {
12597                memset(&p, 0, sizeof(p));
12598                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
12599                if (!res) {
12600                   analog_p->fxsoffhookstate = p.rxisoffhook;
12601                }
12602 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
12603                res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_VMWI_CONFIG, &tmp->mwisend_setting);
12604 #endif
12605             }
12606             analog_p->msgstate = -1;
12607 
12608             ast_copy_string(analog_p->mohsuggest, conf->chan.mohsuggest, sizeof(analog_p->mohsuggest));
12609             ast_copy_string(analog_p->cid_num, conf->chan.cid_num, sizeof(analog_p->cid_num));
12610             ast_copy_string(analog_p->cid_name, conf->chan.cid_name, sizeof(analog_p->cid_name));
12611 
12612             analog_config_complete(analog_p);
12613          }
12614          break;
12615       }
12616 #if defined(HAVE_PRI)
12617       if (tmp->channel == CHAN_PSEUDO) {
12618          /*
12619           * Save off pseudo channel buffer policy values for dynamic creation of
12620           * no B channel interfaces.
12621           */
12622          dahdi_pseudo_parms.buf_no = tmp->buf_no;
12623          dahdi_pseudo_parms.buf_policy = tmp->buf_policy;
12624          dahdi_pseudo_parms.faxbuf_no = tmp->faxbuf_no;
12625          dahdi_pseudo_parms.faxbuf_policy = tmp->faxbuf_policy;
12626       }
12627 #endif   /* defined(HAVE_PRI) */
12628    }
12629    if (tmp && !here) {
12630       /* Add the new channel interface to the sorted channel interface list. */
12631       dahdi_iflist_insert(tmp);
12632    }
12633    return tmp;
12634 }
12635 
12636 static int is_group_or_channel_match(struct dahdi_pvt *p, int span, ast_group_t groupmatch, int *groupmatched, int channelmatch, int *channelmatched)
12637 {
12638 #if defined(HAVE_PRI)
12639    if (0 < span) {
12640       /* The channel must be on the specified PRI span. */
12641       if (!p->pri || p->pri->span != span) {
12642          return 0;
12643       }
12644    }
12645 #endif   /* defined(HAVE_PRI) */
12646    /* check group matching */
12647    if (groupmatch) {
12648       if ((p->group & groupmatch) != groupmatch)
12649          /* Doesn't match the specified group, try the next one */
12650          return 0;
12651       *groupmatched = 1;
12652    }
12653    /* Check to see if we have a channel match */
12654    if (channelmatch != -1) {
12655       if (p->channel != channelmatch)
12656          /* Doesn't match the specified channel, try the next one */
12657          return 0;
12658       *channelmatched = 1;
12659    }
12660 
12661    return 1;
12662 }
12663 
12664 static int available(struct dahdi_pvt **pvt, int is_specific_channel)
12665 {
12666    struct dahdi_pvt *p = *pvt;
12667 
12668    if (p->inalarm)
12669       return 0;
12670 
12671    if (analog_lib_handles(p->sig, p->radio, p->oprmode))
12672       return analog_available(p->sig_pvt);
12673 
12674    switch (p->sig) {
12675 #if defined(HAVE_PRI)
12676    case SIG_PRI_LIB_HANDLE_CASES:
12677       {
12678          struct sig_pri_chan *pvt_chan;
12679          int res;
12680 
12681          pvt_chan = p->sig_pvt;
12682          res = sig_pri_available(&pvt_chan, is_specific_channel);
12683          *pvt = pvt_chan->chan_pvt;
12684          return res;
12685       }
12686 #endif   /* defined(HAVE_PRI) */
12687 #if defined(HAVE_SS7)
12688    case SIG_SS7:
12689       return sig_ss7_available(p->sig_pvt);
12690 #endif   /* defined(HAVE_SS7) */
12691    default:
12692       break;
12693    }
12694 
12695    if (p->locallyblocked || p->remotelyblocked) {
12696       return 0;
12697    }
12698 
12699    /* If no owner definitely available */
12700    if (!p->owner) {
12701 #ifdef HAVE_OPENR2
12702       /* Trust MFC/R2 */
12703       if (p->mfcr2) {
12704          if (p->mfcr2call) {
12705             return 0;
12706          } else {
12707             return 1;
12708          }
12709       }
12710 #endif
12711       return 1;
12712    }
12713 
12714    return 0;
12715 }
12716 
12717 #if defined(HAVE_PRI)
12718 #if defined(HAVE_PRI_CALL_WAITING)
12719 /*!
12720  * \internal
12721  * \brief Init the private channel configuration using the span controller.
12722  * \since 1.8
12723  *
12724  * \param priv Channel to init the configuration.
12725  * \param pri sig_pri PRI control structure.
12726  *
12727  * \note Assumes the pri->lock is already obtained.
12728  *
12729  * \return Nothing
12730  */
12731 static void my_pri_init_config(void *priv, struct sig_pri_span *pri)
12732 {
12733    struct dahdi_pvt *pvt = priv;
12734 
12735    pvt->stripmsd = pri->ch_cfg.stripmsd;
12736    pvt->hidecallerid = pri->ch_cfg.hidecallerid;
12737    pvt->hidecalleridname = pri->ch_cfg.hidecalleridname;
12738    pvt->immediate = pri->ch_cfg.immediate;
12739    pvt->priexclusive = pri->ch_cfg.priexclusive;
12740    pvt->priindication_oob = pri->ch_cfg.priindication_oob;
12741    pvt->use_callerid = pri->ch_cfg.use_callerid;
12742    pvt->use_callingpres = pri->ch_cfg.use_callingpres;
12743    ast_copy_string(pvt->context, pri->ch_cfg.context, sizeof(pvt->context));
12744    ast_copy_string(pvt->mohinterpret, pri->ch_cfg.mohinterpret, sizeof(pvt->mohinterpret));
12745 }
12746 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
12747 #endif   /* defined(HAVE_PRI) */
12748 
12749 #if defined(HAVE_PRI)
12750 /*!
12751  * \internal
12752  * \brief Create a no B channel interface.
12753  * \since 1.8
12754  *
12755  * \param pri sig_pri span controller to add interface.
12756  *
12757  * \note Assumes the pri->lock is already obtained.
12758  *
12759  * \retval array-index into private pointer array on success.
12760  * \retval -1 on error.
12761  */
12762 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri)
12763 {
12764    int pvt_idx;
12765    int res;
12766    unsigned idx;
12767    struct dahdi_pvt *pvt;
12768    struct sig_pri_chan *chan;
12769    struct dahdi_bufferinfo bi;
12770 
12771    static int nobch_channel = CHAN_PSEUDO;
12772 
12773    /* Find spot in the private pointer array for new interface. */
12774    for (pvt_idx = 0; pvt_idx < pri->numchans; ++pvt_idx) {
12775       if (!pri->pvts[pvt_idx]) {
12776          break;
12777       }
12778    }
12779    if (pri->numchans == pvt_idx) {
12780       if (ARRAY_LEN(pri->pvts) <= pvt_idx) {
12781          ast_log(LOG_ERROR, "Unable to add a no-B-channel interface!\n");
12782          return -1;
12783       }
12784 
12785       /* Add new spot to the private pointer array. */
12786       pri->pvts[pvt_idx] = NULL;
12787       ++pri->numchans;
12788    }
12789 
12790    pvt = ast_calloc(1, sizeof(*pvt));
12791    if (!pvt) {
12792       return -1;
12793    }
12794    pvt->cc_params = ast_cc_config_params_init();
12795    if (!pvt->cc_params) {
12796       ast_free(pvt);
12797       return -1;
12798    }
12799    ast_mutex_init(&pvt->lock);
12800    for (idx = 0; idx < ARRAY_LEN(pvt->subs); ++idx) {
12801       pvt->subs[idx].dfd = -1;
12802    }
12803    pvt->buf_no = dahdi_pseudo_parms.buf_no;
12804    pvt->buf_policy = dahdi_pseudo_parms.buf_policy;
12805    pvt->faxbuf_no = dahdi_pseudo_parms.faxbuf_no;
12806    pvt->faxbuf_policy = dahdi_pseudo_parms.faxbuf_policy;
12807 
12808    chan = sig_pri_chan_new(pvt, &dahdi_pri_callbacks, pri, 0, 0, 0);
12809    if (!chan) {
12810       destroy_dahdi_pvt(pvt);
12811       return -1;
12812    }
12813    chan->no_b_channel = 1;
12814 
12815    /*
12816     * Pseudo channel companding law.
12817     * Needed for outgoing call waiting calls.
12818     * XXX May need to make this determined by switchtype or user option.
12819     */
12820    pvt->law_default = DAHDI_LAW_ALAW;
12821 
12822    pvt->sig = pri->sig;
12823    pvt->outsigmod = -1;
12824    pvt->pri = pri;
12825    pvt->sig_pvt = chan;
12826    pri->pvts[pvt_idx] = chan;
12827 
12828    pvt->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
12829    if (pvt->subs[SUB_REAL].dfd < 0) {
12830       ast_log(LOG_ERROR, "Unable to open no B channel interface pseudo channel: %s\n",
12831          strerror(errno));
12832       destroy_dahdi_pvt(pvt);
12833       return -1;
12834    }
12835    memset(&bi, 0, sizeof(bi));
12836    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
12837    if (!res) {
12838       pvt->bufsize = bi.bufsize;
12839       bi.txbufpolicy = pvt->buf_policy;
12840       bi.rxbufpolicy = pvt->buf_policy;
12841       bi.numbufs = pvt->buf_no;
12842       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
12843       if (res < 0) {
12844          ast_log(LOG_WARNING,
12845             "Unable to set buffer policy on no B channel interface: %s\n",
12846             strerror(errno));
12847       }
12848    } else
12849       ast_log(LOG_WARNING,
12850          "Unable to check buffer policy on no B channel interface: %s\n",
12851          strerror(errno));
12852 
12853    --nobch_channel;
12854    if (CHAN_PSEUDO < nobch_channel) {
12855       nobch_channel = CHAN_PSEUDO - 1;
12856    }
12857    pvt->channel = nobch_channel;
12858    chan->channel = pvt->channel;
12859 
12860    dahdi_nobch_insert(pri, pvt);
12861 
12862    return pvt_idx;
12863 }
12864 #endif   /* defined(HAVE_PRI) */
12865 
12866 /* This function can *ONLY* be used for copying pseudo (CHAN_PSEUDO) private
12867    structures; it makes no attempt to safely copy regular channel private
12868    structures that might contain reference-counted object pointers and other
12869    scary bits
12870 */
12871 static struct dahdi_pvt *duplicate_pseudo(struct dahdi_pvt *src)
12872 {
12873    struct dahdi_pvt *p;
12874    struct dahdi_bufferinfo bi;
12875    int res;
12876 
12877    p = ast_malloc(sizeof(*p));
12878    if (!p) {
12879       return NULL;
12880    }
12881    *p = *src;
12882 
12883    /* Must deep copy the cc_params. */
12884    p->cc_params = ast_cc_config_params_init();
12885    if (!p->cc_params) {
12886       ast_free(p);
12887       return NULL;
12888    }
12889    ast_cc_copy_config_params(p->cc_params, src->cc_params);
12890 
12891    p->which_iflist = DAHDI_IFLIST_NONE;
12892    p->next = NULL;
12893    p->prev = NULL;
12894    ast_mutex_init(&p->lock);
12895    p->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
12896    if (p->subs[SUB_REAL].dfd < 0) {
12897       ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
12898       destroy_dahdi_pvt(p);
12899       return NULL;
12900    }
12901    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
12902    if (!res) {
12903       bi.txbufpolicy = src->buf_policy;
12904       bi.rxbufpolicy = src->buf_policy;
12905       bi.numbufs = src->buf_no;
12906       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
12907       if (res < 0) {
12908          ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel: %s\n", strerror(errno));
12909       }
12910    } else
12911       ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel: %s\n", strerror(errno));
12912    p->destroy = 1;
12913    dahdi_iflist_insert(p);
12914    return p;
12915 }
12916 
12917 struct dahdi_starting_point {
12918    /*! Group matching mask.  Zero if not specified. */
12919    ast_group_t groupmatch;
12920    /*! DAHDI channel to match with.  -1 if not specified. */
12921    int channelmatch;
12922    /*! Round robin saved search location index. (Valid if roundrobin TRUE) */
12923    int rr_starting_point;
12924    /*! ISDN span where channels can be picked (Zero if not specified) */
12925    int span;
12926    /*! Analog channel distinctive ring cadance index. */
12927    int cadance;
12928    /*! Dialing option. c/r/d if present and valid. */
12929    char opt;
12930    /*! TRUE if to search the channel list backwards. */
12931    char backwards;
12932    /*! TRUE if search is done with round robin sequence. */
12933    char roundrobin;
12934 };
12935 static struct dahdi_pvt *determine_starting_point(const char *data, struct dahdi_starting_point *param)
12936 {
12937    char *dest;
12938    char *s;
12939    int x;
12940    int res = 0;
12941    struct dahdi_pvt *p;
12942    char *subdir = NULL;
12943    AST_DECLARE_APP_ARGS(args,
12944       AST_APP_ARG(group);  /* channel/group token */
12945       //AST_APP_ARG(ext);  /* extension token */
12946       //AST_APP_ARG(opts); /* options token */
12947       AST_APP_ARG(other);  /* Any remining unused arguments */
12948    );
12949 
12950    /*
12951     * data is ---v
12952     * Dial(DAHDI/pseudo[/extension[/options]])
12953     * Dial(DAHDI/<channel#>[c|r<cadance#>|d][/extension[/options]])
12954     * Dial(DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]])
12955     * Dial(DAHDI/<subdir>!<channel#>[c|r<cadance#>|d][/extension[/options]])
12956     *
12957     * i - ISDN span channel restriction.
12958     *     Used by CC to ensure that the CC recall goes out the same span.
12959     *
12960     * g - channel group allocation search forward
12961     * G - channel group allocation search backward
12962     * r - channel group allocation round robin search forward
12963     * R - channel group allocation round robin search backward
12964     *
12965     * c - Wait for DTMF digit to confirm answer
12966     * r<cadance#> - Set distintive ring cadance number
12967     * d - Force bearer capability for ISDN/SS7 call to digital.
12968     */
12969 
12970    if (data) {
12971       dest = ast_strdupa(data);
12972    } else {
12973       ast_log(LOG_WARNING, "Channel requested with no data\n");
12974       return NULL;
12975    }
12976    AST_NONSTANDARD_APP_ARGS(args, dest, '/');
12977    if (!args.argc || ast_strlen_zero(args.group)) {
12978       ast_log(LOG_WARNING, "No channel/group specified\n");
12979       return NULL;
12980    }
12981 
12982    /* Initialize the output parameters */
12983    memset(param, 0, sizeof(*param));
12984    param->channelmatch = -1;
12985 
12986    if (strchr(args.group, '!') != NULL) {
12987       char *prev = args.group;
12988       while ((s = strchr(prev, '!')) != NULL) {
12989          *s++ = '/';
12990          prev = s;
12991       }
12992       *(prev - 1) = '\0';
12993       subdir = args.group;
12994       args.group = prev;
12995    } else if (args.group[0] == 'i') {
12996       /* Extract the ISDN span channel restriction specifier. */
12997       res = sscanf(args.group + 1, "%30d", &x);
12998       if (res < 1) {
12999          ast_log(LOG_WARNING, "Unable to determine ISDN span for data %s\n", data);
13000          return NULL;
13001       }
13002       param->span = x;
13003 
13004       /* Remove the ISDN span channel restriction specifier. */
13005       s = strchr(args.group, '-');
13006       if (!s) {
13007          ast_log(LOG_WARNING, "Bad ISDN span format for data %s\n", data);
13008          return NULL;
13009       }
13010       args.group = s + 1;
13011       res = 0;
13012    }
13013    if (toupper(args.group[0]) == 'G' || toupper(args.group[0])=='R') {
13014       /* Retrieve the group number */
13015       s = args.group + 1;
13016       res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13017       if (res < 1) {
13018          ast_log(LOG_WARNING, "Unable to determine group for data %s\n", data);
13019          return NULL;
13020       }
13021       param->groupmatch = ((ast_group_t) 1 << x);
13022 
13023       if (toupper(args.group[0]) == 'G') {
13024          if (args.group[0] == 'G') {
13025             param->backwards = 1;
13026             p = ifend;
13027          } else
13028             p = iflist;
13029       } else {
13030          if (ARRAY_LEN(round_robin) <= x) {
13031             ast_log(LOG_WARNING, "Round robin index %d out of range for data %s\n",
13032                x, data);
13033             return NULL;
13034          }
13035          if (args.group[0] == 'R') {
13036             param->backwards = 1;
13037             p = round_robin[x] ? round_robin[x]->prev : ifend;
13038             if (!p)
13039                p = ifend;
13040          } else {
13041             p = round_robin[x] ? round_robin[x]->next : iflist;
13042             if (!p)
13043                p = iflist;
13044          }
13045          param->roundrobin = 1;
13046          param->rr_starting_point = x;
13047       }
13048    } else {
13049       s = args.group;
13050       if (!strcasecmp(s, "pseudo")) {
13051          /* Special case for pseudo */
13052          x = CHAN_PSEUDO;
13053          param->channelmatch = x;
13054       } else {
13055          res = sscanf(s, "%30d%1c%30d", &x, &param->opt, &param->cadance);
13056          if (res < 1) {
13057             ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", data);
13058             return NULL;
13059          } else {
13060             param->channelmatch = x;
13061          }
13062       }
13063       if (subdir) {
13064          char path[PATH_MAX];
13065          struct stat stbuf;
13066 
13067          snprintf(path, sizeof(path), "/dev/dahdi/%s/%d",
13068                subdir, param->channelmatch);
13069          if (stat(path, &stbuf) < 0) {
13070             ast_log(LOG_WARNING, "stat(%s) failed: %s\n",
13071                   path, strerror(errno));
13072             return NULL;
13073          }
13074          if (!S_ISCHR(stbuf.st_mode)) {
13075             ast_log(LOG_ERROR, "%s: Not a character device file\n",
13076                   path);
13077             return NULL;
13078          }
13079          param->channelmatch = minor(stbuf.st_rdev);
13080       }
13081 
13082       p = iflist;
13083    }
13084 
13085    if (param->opt == 'r' && res < 3) {
13086       ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", data);
13087       param->opt = '\0';
13088    }
13089 
13090    return p;
13091 }
13092 
13093 static struct ast_channel *dahdi_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
13094 {
13095    int callwait = 0;
13096    struct dahdi_pvt *p;
13097    struct ast_channel *tmp = NULL;
13098    struct dahdi_pvt *exitpvt;
13099    int channelmatched = 0;
13100    int groupmatched = 0;
13101    int transcapdigital = 0;
13102    struct dahdi_starting_point start;
13103 
13104    ast_mutex_lock(&iflock);
13105    p = determine_starting_point(data, &start);
13106    if (!p) {
13107       /* We couldn't determine a starting point, which likely means badly-formatted channel name. Abort! */
13108       ast_mutex_unlock(&iflock);
13109       return NULL;
13110    }
13111 
13112    /* Search for an unowned channel */
13113    exitpvt = p;
13114    while (p && !tmp) {
13115       if (start.roundrobin)
13116          round_robin[start.rr_starting_point] = p;
13117 
13118       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)
13119          && available(&p, channelmatched)) {
13120          ast_debug(1, "Using channel %d\n", p->channel);
13121 
13122          callwait = (p->owner != NULL);
13123 #ifdef HAVE_OPENR2
13124          if (p->mfcr2) {
13125             ast_mutex_lock(&p->lock);
13126             if (p->mfcr2call) {
13127                ast_mutex_unlock(&p->lock);
13128                ast_log(LOG_DEBUG, "Yay!, someone just beat us in the race for channel %d.\n", p->channel);
13129                goto next;
13130             }
13131             p->mfcr2call = 1;
13132             ast_mutex_unlock(&p->lock);
13133          }
13134 #endif
13135          if (p->channel == CHAN_PSEUDO) {
13136             p = duplicate_pseudo(p);
13137             if (!p) {
13138                break;
13139             }
13140          }
13141 
13142          /* Make special notes */
13143          switch (start.opt) {
13144          case '\0':
13145             /* No option present. */
13146             break;
13147          case 'c':
13148             /* Confirm answer */
13149             p->confirmanswer = 1;
13150             break;
13151          case 'r':
13152             /* Distinctive ring */
13153             p->distinctivering = start.cadance;
13154             break;
13155          case 'd':
13156             /* If this is an ISDN call, make it digital */
13157             transcapdigital = AST_TRANS_CAP_DIGITAL;
13158             break;
13159          default:
13160             ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", start.opt, (char *)data);
13161             break;
13162          }
13163 
13164          p->outgoing = 1;
13165          if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
13166             tmp = analog_request(p->sig_pvt, &callwait, requestor);
13167 #ifdef HAVE_PRI
13168          } else if (dahdi_sig_pri_lib_handles(p->sig)) {
13169             sig_pri_extract_called_num_subaddr(p->sig_pvt, data, p->dnid,
13170                sizeof(p->dnid));
13171             tmp = sig_pri_request(p->sig_pvt, SIG_PRI_DEFLAW, requestor, transcapdigital);
13172 #endif
13173 #if defined(HAVE_SS7)
13174          } else if (p->sig == SIG_SS7) {
13175             tmp = sig_ss7_request(p->sig_pvt, SIG_SS7_DEFLAW, requestor, transcapdigital);
13176 #endif   /* defined(HAVE_SS7) */
13177          } else {
13178             tmp = dahdi_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, requestor ? requestor->linkedid : "");
13179          }
13180          if (!tmp) {
13181             p->outgoing = 0;
13182 #if defined(HAVE_PRI)
13183 #if defined(HAVE_PRI_CALL_WAITING)
13184             switch (p->sig) {
13185             case SIG_PRI_LIB_HANDLE_CASES:
13186                if (((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting) {
13187                   ((struct sig_pri_chan *) p->sig_pvt)->is_call_waiting = 0;
13188                   ast_atomic_fetchadd_int(&p->pri->num_call_waiting_calls, -1);
13189                }
13190                break;
13191             default:
13192                break;
13193             }
13194 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
13195 #endif   /* defined(HAVE_PRI) */
13196          } else {
13197             snprintf(p->dialstring, sizeof(p->dialstring), "DAHDI/%s", (char *) data);
13198          }
13199          break;
13200       }
13201 #ifdef HAVE_OPENR2
13202 next:
13203 #endif
13204       if (start.backwards) {
13205          p = p->prev;
13206          if (!p)
13207             p = ifend;
13208       } else {
13209          p = p->next;
13210          if (!p)
13211             p = iflist;
13212       }
13213       /* stop when you roll to the one that we started from */
13214       if (p == exitpvt)
13215          break;
13216    }
13217    ast_mutex_unlock(&iflock);
13218    restart_monitor();
13219    if (cause && !tmp) {
13220       if (callwait || channelmatched) {
13221          *cause = AST_CAUSE_BUSY;
13222       } else if (groupmatched) {
13223          *cause = AST_CAUSE_CONGESTION;
13224       } else {
13225          /*
13226           * We did not match any channel requested.
13227           * Dialplan error requesting non-existant channel?
13228           */
13229       }
13230    }
13231 
13232    return tmp;
13233 }
13234 
13235 /*!
13236  * \internal
13237  * \brief Determine the device state for a given DAHDI device if we can.
13238  * \since 1.8
13239  *
13240  * \param data DAHDI device name after "DAHDI/".
13241  *
13242  * \retval device_state enum ast_device_state value.
13243  * \retval AST_DEVICE_UNKNOWN if we could not determine the device's state.
13244  */
13245 static int dahdi_devicestate(void *data)
13246 {
13247 #if defined(HAVE_PRI)
13248    char *device;
13249    unsigned span;
13250    int res;
13251 
13252    device = data;
13253 
13254    if (*device != 'I') {
13255       /* The request is not for an ISDN span device. */
13256       return AST_DEVICE_UNKNOWN;
13257    }
13258    res = sscanf(device, "I%30u", &span);
13259    if (res != 1 || !span || NUM_SPANS < span) {
13260       /* Bad format for ISDN span device name. */
13261       return AST_DEVICE_UNKNOWN;
13262    }
13263    device = strchr(device, '/');
13264    if (!device) {
13265       /* Bad format for ISDN span device name. */
13266       return AST_DEVICE_UNKNOWN;
13267    }
13268 
13269    /*
13270     * Since there are currently no other span devstate's defined,
13271     * it must be congestion.
13272     */
13273 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13274    ++device;
13275    if (!strcmp(device, "congestion"))
13276 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13277    {
13278       return pris[span - 1].pri.congestion_devstate;
13279    }
13280 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
13281    else if (!strcmp(device, "threshold")) {
13282       return pris[span - 1].pri.threshold_devstate;
13283    }
13284    return AST_DEVICE_UNKNOWN;
13285 #endif   /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
13286 #else
13287    return AST_DEVICE_UNKNOWN;
13288 #endif   /* defined(HAVE_PRI) */
13289 }
13290 
13291 /*!
13292  * \brief Callback made when dial failed to get a channel out of dahdi_request().
13293  * \since 1.8
13294  *
13295  * \param inbound Incoming asterisk channel.
13296  * \param dest Same dial string passed to dahdi_request().
13297  * \param callback Callback into CC core to announce a busy channel available for CC.
13298  *
13299  * \details
13300  * This callback acts like a forked dial with all prongs of the fork busy.
13301  * Essentially, for each channel that could have taken the call, indicate that
13302  * it is busy.
13303  *
13304  * \retval 0 on success.
13305  * \retval -1 on error.
13306  */
13307 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback)
13308 {
13309    struct dahdi_pvt *p;
13310    struct dahdi_pvt *exitpvt;
13311    struct dahdi_starting_point start;
13312    int groupmatched = 0;
13313    int channelmatched = 0;
13314 
13315    ast_mutex_lock(&iflock);
13316    p = determine_starting_point(dest, &start);
13317    if (!p) {
13318       ast_mutex_unlock(&iflock);
13319       return -1;
13320    }
13321    exitpvt = p;
13322    for (;;) {
13323       if (is_group_or_channel_match(p, start.span, start.groupmatch, &groupmatched, start.channelmatch, &channelmatched)) {
13324          /* We found a potential match. call the callback */
13325          struct ast_str *device_name;
13326          char *dash;
13327          const char *monitor_type;
13328          char dialstring[AST_CHANNEL_NAME];
13329          char full_device_name[AST_CHANNEL_NAME];
13330 
13331          switch (ast_get_cc_monitor_policy(p->cc_params)) {
13332          case AST_CC_MONITOR_NEVER:
13333             break;
13334          case AST_CC_MONITOR_NATIVE:
13335          case AST_CC_MONITOR_ALWAYS:
13336          case AST_CC_MONITOR_GENERIC:
13337 #if defined(HAVE_PRI)
13338             if (dahdi_sig_pri_lib_handles(p->sig)) {
13339                /*
13340                 * ISDN is in a trunk busy condition so we need to monitor
13341                 * the span congestion device state.
13342                 */
13343                snprintf(full_device_name, sizeof(full_device_name),
13344                   "DAHDI/I%d/congestion", p->pri->span);
13345             } else
13346 #endif   /* defined(HAVE_PRI) */
13347             {
13348 #if defined(HAVE_PRI)
13349                device_name = create_channel_name(p, 1, "");
13350 #else
13351                device_name = create_channel_name(p);
13352 #endif   /* defined(HAVE_PRI) */
13353                snprintf(full_device_name, sizeof(full_device_name), "DAHDI/%s",
13354                   device_name ? ast_str_buffer(device_name) : "");
13355                ast_free(device_name);
13356                /*
13357                 * The portion after the '-' in the channel name is either a random
13358                 * number, a sequence number, or a subchannel number. None are
13359                 * necessary so strip them off.
13360                 */
13361                dash = strrchr(full_device_name, '-');
13362                if (dash) {
13363                   *dash = '\0';
13364                }
13365             }
13366             snprintf(dialstring, sizeof(dialstring), "DAHDI/%s", dest);
13367 
13368             /*
13369              * Analog can only do generic monitoring.
13370              * ISDN is in a trunk busy condition and any "device" is going
13371              * to be busy until a B channel becomes available.  The generic
13372              * monitor can do this task.
13373              */
13374             monitor_type = AST_CC_GENERIC_MONITOR_TYPE;
13375             callback(inbound,
13376 #if defined(HAVE_PRI)
13377                p->pri ? p->pri->cc_params : p->cc_params,
13378 #else
13379                p->cc_params,
13380 #endif   /* defined(HAVE_PRI) */
13381                monitor_type, full_device_name, dialstring, NULL);
13382             break;
13383          }
13384       }
13385       p = start.backwards ? p->prev : p->next;
13386       if (!p) {
13387          p = start.backwards ? ifend : iflist;
13388       }
13389       if (p == exitpvt) {
13390          break;
13391       }
13392    }
13393    ast_mutex_unlock(&iflock);
13394    return 0;
13395 }
13396 
13397 #if defined(HAVE_SS7)
13398 static void dahdi_ss7_message(struct ss7 *ss7, char *s)
13399 {
13400    int i;
13401 
13402    if (ss7) {
13403       for (i = 0; i < NUM_SPANS; i++) {
13404          if (linksets[i].ss7.ss7 == ss7) {
13405             ast_verbose("[%d] %s", i + 1, s);
13406             return;
13407          }
13408       }
13409    }
13410    ast_verbose("%s", s);
13411 }
13412 #endif   /* defined(HAVE_SS7) */
13413 
13414 #if defined(HAVE_SS7)
13415 static void dahdi_ss7_error(struct ss7 *ss7, char *s)
13416 {
13417    int i;
13418 
13419    if (ss7) {
13420       for (i = 0; i < NUM_SPANS; i++) {
13421          if (linksets[i].ss7.ss7 == ss7) {
13422             ast_log(LOG_ERROR, "[%d] %s", i + 1, s);
13423             return;
13424          }
13425       }
13426    }
13427    ast_log(LOG_ERROR, "%s", s);
13428 }
13429 #endif   /* defined(HAVE_SS7) */
13430 
13431 #if defined(HAVE_OPENR2)
13432 static void *mfcr2_monitor(void *data)
13433 {
13434    struct dahdi_mfcr2 *mfcr2 = data;
13435    /* we should be using pthread_key_create
13436       and allocate pollers dynamically.
13437       I think do_monitor() could be leaking, since it
13438       could be cancelled at any time and is not
13439       using thread keys, why?, */
13440    struct pollfd pollers[ARRAY_LEN(mfcr2->pvts)];
13441    int res = 0;
13442    int i = 0;
13443    int oldstate = 0;
13444    int quit_loop = 0;
13445    int maxsleep = 20;
13446    int was_idle = 0;
13447    int pollsize = 0;
13448    /* now that we're ready to get calls, unblock our side and
13449       get current line state */
13450    for (i = 0; i < mfcr2->numchans; i++) {
13451       openr2_chan_set_idle(mfcr2->pvts[i]->r2chan);
13452       openr2_chan_handle_cas(mfcr2->pvts[i]->r2chan);
13453    }
13454    while (1) {
13455       /* we trust here that the mfcr2 channel list will not ever change once
13456          the module is loaded */
13457       pollsize = 0;
13458       for (i = 0; i < mfcr2->numchans; i++) {
13459          pollers[i].revents = 0;
13460          pollers[i].events = 0;
13461          if (mfcr2->pvts[i]->owner) {
13462             continue;
13463          }
13464          if (!mfcr2->pvts[i]->r2chan) {
13465             ast_log(LOG_DEBUG, "Wow, no r2chan on channel %d\n", mfcr2->pvts[i]->channel);
13466             quit_loop = 1;
13467             break;
13468          }
13469          openr2_chan_enable_read(mfcr2->pvts[i]->r2chan);
13470          pollers[i].events = POLLIN | POLLPRI;
13471          pollers[i].fd = mfcr2->pvts[i]->subs[SUB_REAL].dfd;
13472          pollsize++;
13473       }
13474       if (quit_loop) {
13475          break;
13476       }
13477       if (pollsize == 0) {
13478          if (!was_idle) {
13479             ast_log(LOG_DEBUG, "Monitor thread going idle since everybody has an owner\n");
13480             was_idle = 1;
13481          }
13482          poll(NULL, 0, maxsleep);
13483          continue;
13484       }
13485       was_idle = 0;
13486       /* probably poll() is a valid cancel point, lets just be on the safe side
13487          by calling pthread_testcancel */
13488       pthread_testcancel();
13489       res = poll(pollers, mfcr2->numchans, maxsleep);
13490       pthread_testcancel();
13491       if ((res < 0) && (errno != EINTR)) {
13492          ast_log(LOG_ERROR, "going out, poll failed: %s\n", strerror(errno));
13493          break;
13494       }
13495       /* do we want to allow to cancel while processing events? */
13496       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
13497       for (i = 0; i < mfcr2->numchans; i++) {
13498          if (pollers[i].revents & POLLPRI || pollers[i].revents & POLLIN) {
13499             openr2_chan_process_event(mfcr2->pvts[i]->r2chan);
13500          }
13501       }
13502       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
13503    }
13504    ast_log(LOG_NOTICE, "Quitting MFC/R2 monitor thread\n");
13505    return 0;
13506 }
13507 #endif /* HAVE_OPENR2 */
13508 
13509 #if defined(HAVE_PRI)
13510 #ifndef PRI_RESTART
13511 #error "Upgrade your libpri"
13512 #endif
13513 static void dahdi_pri_message(struct pri *pri, char *s)
13514 {
13515    int x, y;
13516    int dchan = -1, span = -1, dchancount = 0;
13517 
13518    if (pri) {
13519       for (x = 0; x < NUM_SPANS; x++) {
13520          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
13521             if (pris[x].pri.dchans[y])
13522                dchancount++;
13523 
13524             if (pris[x].pri.dchans[y] == pri)
13525                dchan = y;
13526          }
13527          if (dchan >= 0) {
13528             span = x;
13529             break;
13530          }
13531          dchancount = 0;
13532       }
13533       if (dchancount > 1 && (span > -1))
13534          ast_verbose("[Span %d D-Channel %d]%s", span, dchan, s);
13535       else if (span > -1)
13536          ast_verbose("%d %s", span+1, s);
13537       else
13538          ast_verbose("%s", s);
13539    } else
13540       ast_verbose("%s", s);
13541 
13542    ast_mutex_lock(&pridebugfdlock);
13543 
13544    if (pridebugfd >= 0) {
13545       if (write(pridebugfd, s, strlen(s)) < 0) {
13546          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13547       }
13548    }
13549 
13550    ast_mutex_unlock(&pridebugfdlock);
13551 }
13552 #endif   /* defined(HAVE_PRI) */
13553 
13554 #if defined(HAVE_PRI)
13555 static void dahdi_pri_error(struct pri *pri, char *s)
13556 {
13557    int x, y;
13558    int dchan = -1, span = -1;
13559    int dchancount = 0;
13560 
13561    if (pri) {
13562       for (x = 0; x < NUM_SPANS; x++) {
13563          for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
13564             if (pris[x].pri.dchans[y])
13565                dchancount++;
13566 
13567             if (pris[x].pri.dchans[y] == pri)
13568                dchan = y;
13569          }
13570          if (dchan >= 0) {
13571             span = x;
13572             break;
13573          }
13574          dchancount = 0;
13575       }
13576       if ((dchancount > 1) && (span > -1))
13577          ast_log(LOG_ERROR, "[Span %d D-Channel %d] PRI: %s", span, dchan, s);
13578       else if (span > -1)
13579          ast_log(LOG_ERROR, "%d %s", span+1, s);
13580       else
13581          ast_log(LOG_ERROR, "%s", s);
13582    } else
13583       ast_log(LOG_ERROR, "%s", s);
13584 
13585    ast_mutex_lock(&pridebugfdlock);
13586 
13587    if (pridebugfd >= 0) {
13588       if (write(pridebugfd, s, strlen(s)) < 0) {
13589          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13590       }
13591    }
13592 
13593    ast_mutex_unlock(&pridebugfdlock);
13594 }
13595 #endif   /* defined(HAVE_PRI) */
13596 
13597 #if defined(HAVE_PRI)
13598 static int prepare_pri(struct dahdi_pri *pri)
13599 {
13600    int i, res, x;
13601    struct dahdi_params p;
13602    struct dahdi_bufferinfo bi;
13603    struct dahdi_spaninfo si;
13604 
13605    pri->pri.calls = &dahdi_pri_callbacks;
13606 
13607    for (i = 0; i < SIG_PRI_NUM_DCHANS; i++) {
13608       if (!pri->dchannels[i])
13609          break;
13610       pri->pri.fds[i] = open("/dev/dahdi/channel", O_RDWR);
13611       x = pri->dchannels[i];
13612       if ((pri->pri.fds[i] < 0) || (ioctl(pri->pri.fds[i],DAHDI_SPECIFY,&x) == -1)) {
13613          ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
13614          return -1;
13615       }
13616       memset(&p, 0, sizeof(p));
13617       res = ioctl(pri->pri.fds[i], DAHDI_GET_PARAMS, &p);
13618       if (res) {
13619          dahdi_close_pri_fd(pri, i);
13620          ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
13621          return -1;
13622       }
13623       if ((p.sigtype != DAHDI_SIG_HDLCFCS) && (p.sigtype != DAHDI_SIG_HARDHDLC)) {
13624          dahdi_close_pri_fd(pri, i);
13625          ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode.\n", x);
13626          return -1;
13627       }
13628       memset(&si, 0, sizeof(si));
13629       res = ioctl(pri->pri.fds[i], DAHDI_SPANSTAT, &si);
13630       if (res) {
13631          dahdi_close_pri_fd(pri, i);
13632          ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
13633       }
13634       if (!si.alarms) {
13635          pri_event_noalarm(&pri->pri, i, 1);
13636       } else {
13637          pri_event_alarm(&pri->pri, i, 1);
13638       }
13639       memset(&bi, 0, sizeof(bi));
13640       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
13641       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
13642       bi.numbufs = 32;
13643       bi.bufsize = 1024;
13644       if (ioctl(pri->pri.fds[i], DAHDI_SET_BUFINFO, &bi)) {
13645          ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n", x, strerror(errno));
13646          dahdi_close_pri_fd(pri, i);
13647          return -1;
13648       }
13649       pri->pri.dchan_logical_span[i] = pris[p.spanno - 1].prilogicalspan;
13650    }
13651    return 0;
13652 }
13653 #endif   /* defined(HAVE_PRI) */
13654 
13655 #if defined(HAVE_PRI)
13656 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
13657 {
13658    int which, span;
13659    char *ret = NULL;
13660 
13661    if (pos != rpos)
13662       return ret;
13663 
13664    for (which = span = 0; span < NUM_SPANS; span++) {
13665       if (pris[span].pri.pri && ++which > state) {
13666          if (asprintf(&ret, "%d", span + 1) < 0) { /* user indexes start from 1 */
13667             ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
13668          }
13669          break;
13670       }
13671    }
13672    return ret;
13673 }
13674 #endif   /* defined(HAVE_PRI) */
13675 
13676 #if defined(HAVE_PRI)
13677 static char *complete_span_4(const char *line, const char *word, int pos, int state)
13678 {
13679    return complete_span_helper(line,word,pos,state,3);
13680 }
13681 #endif   /* defined(HAVE_PRI) */
13682 
13683 #if defined(HAVE_PRI)
13684 static char *handle_pri_set_debug_file(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13685 {
13686    int myfd;
13687    switch (cmd) {
13688    case CLI_INIT:
13689       e->command = "pri set debug file";
13690       e->usage = "Usage: pri set debug file [output-file]\n"
13691          "       Sends PRI debug output to the specified output file\n";
13692       return NULL;
13693    case CLI_GENERATE:
13694       return NULL;
13695    }
13696    if (a->argc < 5)
13697       return CLI_SHOWUSAGE;
13698 
13699    if (ast_strlen_zero(a->argv[4]))
13700       return CLI_SHOWUSAGE;
13701 
13702    myfd = open(a->argv[4], O_CREAT|O_WRONLY, AST_FILE_MODE);
13703    if (myfd < 0) {
13704       ast_cli(a->fd, "Unable to open '%s' for writing\n", a->argv[4]);
13705       return CLI_SUCCESS;
13706    }
13707 
13708    ast_mutex_lock(&pridebugfdlock);
13709 
13710    if (pridebugfd >= 0)
13711       close(pridebugfd);
13712 
13713    pridebugfd = myfd;
13714    ast_copy_string(pridebugfilename,a->argv[4],sizeof(pridebugfilename));
13715    ast_mutex_unlock(&pridebugfdlock);
13716    ast_cli(a->fd, "PRI debug output will be sent to '%s'\n", a->argv[4]);
13717    return CLI_SUCCESS;
13718 }
13719 #endif   /* defined(HAVE_PRI) */
13720 
13721 #if defined(HAVE_PRI)
13722 static char *handle_pri_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13723 {
13724    int span;
13725    int x;
13726    int level = 0;
13727    switch (cmd) {
13728    case CLI_INIT:
13729       e->command = "pri set debug {on|off|0|1|2} span";
13730       e->usage =
13731          "Usage: pri set debug {<level>|on|off} span <span>\n"
13732          "       Enables debugging on a given PRI span\n";
13733       return NULL;
13734    case CLI_GENERATE:
13735       return complete_span_4(a->line, a->word, a->pos, a->n);
13736    }
13737    if (a->argc < 6) {
13738       return CLI_SHOWUSAGE;
13739    }
13740 
13741    if (!strcasecmp(a->argv[3], "on")) {
13742       level = 1;
13743    } else if (!strcasecmp(a->argv[3], "off")) {
13744       level = 0;
13745    } else {
13746       level = atoi(a->argv[3]);
13747    }
13748    span = atoi(a->argv[5]);
13749    if ((span < 1) || (span > NUM_SPANS)) {
13750       ast_cli(a->fd, "Invalid span %s.  Should be a number %d to %d\n", a->argv[5], 1, NUM_SPANS);
13751       return CLI_SUCCESS;
13752    }
13753    if (!pris[span-1].pri.pri) {
13754       ast_cli(a->fd, "No PRI running on span %d\n", span);
13755       return CLI_SUCCESS;
13756    }
13757 
13758    /* Set debug level in libpri */
13759    for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
13760       if (pris[span - 1].pri.dchans[x]) {
13761          switch (level) {
13762          case 0:
13763             pri_set_debug(pris[span - 1].pri.dchans[x], 0);
13764             break;
13765          case 1:
13766             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_NORMAL);
13767             break;
13768          default:
13769             pri_set_debug(pris[span - 1].pri.dchans[x], SIG_PRI_DEBUG_INTENSE);
13770             break;
13771          }
13772       }
13773    }
13774    if (level == 0) {
13775       /* Close the debugging file if it's set */
13776       ast_mutex_lock(&pridebugfdlock);
13777       if (0 <= pridebugfd) {
13778          close(pridebugfd);
13779          pridebugfd = -1;
13780          ast_cli(a->fd, "Disabled PRI debug output to file '%s'\n",
13781             pridebugfilename);
13782       }
13783       ast_mutex_unlock(&pridebugfdlock);
13784    }
13785    pris[span - 1].pri.debug = (level) ? 1 : 0;
13786    ast_cli(a->fd, "%s debugging on span %d\n", (level) ? "Enabled" : "Disabled", span);
13787    return CLI_SUCCESS;
13788 }
13789 #endif   /* defined(HAVE_PRI) */
13790 
13791 #if defined(HAVE_PRI_SERVICE_MESSAGES)
13792 static char *handle_pri_service_generic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a, int changestatus)
13793 {
13794    unsigned *why;
13795    int channel;
13796    int trunkgroup;
13797    int x, y, fd = a->fd;
13798    int interfaceid = 0;
13799    char *c;
13800    char db_chan_name[20], db_answer[5];
13801    struct dahdi_pvt *tmp;
13802    struct dahdi_pri *pri;
13803 
13804    if (a->argc < 5 || a->argc > 6)
13805       return CLI_SHOWUSAGE;
13806    if ((c = strchr(a->argv[4], ':'))) {
13807       if (sscanf(a->argv[4], "%30d:%30d", &trunkgroup, &channel) != 2)
13808          return CLI_SHOWUSAGE;
13809       if ((trunkgroup < 1) || (channel < 1))
13810          return CLI_SHOWUSAGE;
13811       pri = NULL;
13812       for (x=0;x<NUM_SPANS;x++) {
13813          if (pris[x].pri.trunkgroup == trunkgroup) {
13814             pri = pris + x;
13815             break;
13816          }
13817       }
13818       if (!pri) {
13819          ast_cli(fd, "No such trunk group %d\n", trunkgroup);
13820          return CLI_FAILURE;
13821       }
13822    } else
13823       channel = atoi(a->argv[4]);
13824 
13825    if (a->argc == 6)
13826       interfaceid = atoi(a->argv[5]);
13827 
13828    /* either servicing a D-Channel */
13829    for (x = 0; x < NUM_SPANS; x++) {
13830       for (y = 0; y < SIG_PRI_NUM_DCHANS; y++) {
13831          if (pris[x].dchannels[y] == channel) {
13832             pri = pris + x;
13833             if (pri->pri.enable_service_message_support) {
13834                ast_mutex_lock(&pri->pri.lock);
13835                pri_maintenance_service(pri->pri.pri, interfaceid, -1, changestatus);
13836                ast_mutex_unlock(&pri->pri.lock);
13837             } else {
13838                ast_cli(fd,
13839                   "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
13840                   "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
13841             }
13842             return CLI_SUCCESS;
13843          }
13844       }
13845    }
13846 
13847    /* or servicing a B-Channel */
13848    ast_mutex_lock(&iflock);
13849    for (tmp = iflist; tmp; tmp = tmp->next) {
13850       if (tmp->pri && tmp->channel == channel) {
13851          ast_mutex_unlock(&iflock);
13852          ast_mutex_lock(&tmp->pri->lock);
13853          if (!tmp->pri->enable_service_message_support) {
13854             ast_mutex_unlock(&tmp->pri->lock);
13855             ast_cli(fd,
13856                "\n\tThis operation has not been enabled in chan_dahdi.conf, set 'service_message_support=yes' to use this operation.\n"
13857                "\tNote only 4ESS, 5ESS, and NI2 switch types are supported.\n\n");
13858             return CLI_SUCCESS;
13859          }
13860          snprintf(db_chan_name, sizeof(db_chan_name), "%s/%d:%d", dahdi_db, tmp->span, channel);
13861          why = &((struct sig_pri_chan *) tmp->sig_pvt)->service_status;
13862          switch(changestatus) {
13863          case 0: /* enable */
13864             /* Near end wants to be in service now. */
13865             ast_db_del(db_chan_name, SRVST_DBKEY);
13866             *why &= ~SRVST_NEAREND;
13867             if (*why) {
13868                snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
13869                ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
13870             } else {
13871                dahdi_pri_update_span_devstate(tmp->pri);
13872             }
13873             break;
13874          /* case 1:  -- loop */
13875          case 2: /* disable */
13876             /* Near end wants to be out-of-service now. */
13877             ast_db_del(db_chan_name, SRVST_DBKEY);
13878             *why |= SRVST_NEAREND;
13879             snprintf(db_answer, sizeof(db_answer), "%s:%u", SRVST_TYPE_OOS, *why);
13880             ast_db_put(db_chan_name, SRVST_DBKEY, db_answer);
13881             dahdi_pri_update_span_devstate(tmp->pri);
13882             break;
13883          /* case 3:  -- continuity */
13884          /* case 4:  -- shutdown */
13885          default:
13886             ast_log(LOG_WARNING, "Unsupported changestatus: '%d'\n", changestatus);
13887             break;
13888          }
13889          pri_maintenance_bservice(tmp->pri->pri, tmp->sig_pvt, changestatus);
13890          ast_mutex_unlock(&tmp->pri->lock);
13891          return CLI_SUCCESS;
13892       }
13893    }
13894    ast_mutex_unlock(&iflock);
13895 
13896    ast_cli(fd, "Unable to find given channel %d, possibly not a PRI\n", channel);
13897    return CLI_FAILURE;
13898 }
13899 
13900 static char *handle_pri_service_enable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13901 {
13902    switch (cmd) {
13903    case CLI_INIT:
13904       e->command = "pri service enable channel";
13905       e->usage =
13906          "Usage: pri service enable channel <channel> [<interface id>]\n"
13907          "       Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
13908          "  to restore a channel to service, with optional interface id\n"
13909          "  as agreed upon with remote switch operator\n";
13910       return NULL;
13911    case CLI_GENERATE:
13912       return NULL;
13913    }
13914    return handle_pri_service_generic(e, cmd, a, 0);
13915 }
13916 
13917 static char *handle_pri_service_disable_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13918 {
13919    switch (cmd) {
13920    case CLI_INIT:
13921       e->command = "pri service disable channel";
13922       e->usage =
13923          "Usage: pri service disable channel <chan num> [<interface id>]\n"
13924          "  Send an AT&T / NFAS / CCS ANSI T1.607 maintenance message\n"
13925          "  to remove a channel from service, with optional interface id\n"
13926          "  as agreed upon with remote switch operator\n";
13927       return NULL;
13928    case CLI_GENERATE:
13929       return NULL;
13930    }
13931    return handle_pri_service_generic(e, cmd, a, 2);
13932 }
13933 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
13934 
13935 #if defined(HAVE_PRI)
13936 static char *handle_pri_show_spans(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13937 {
13938    int span;
13939 
13940    switch (cmd) {
13941    case CLI_INIT:
13942       e->command = "pri show spans";
13943       e->usage =
13944          "Usage: pri show spans\n"
13945          "       Displays PRI Information\n";
13946       return NULL;
13947    case CLI_GENERATE:
13948       return NULL;
13949    }
13950 
13951    if (a->argc != 3)
13952       return CLI_SHOWUSAGE;
13953 
13954    for (span = 0; span < NUM_SPANS; span++) {
13955       if (pris[span].pri.pri) {
13956          sig_pri_cli_show_spans(a->fd, span + 1, &pris[span].pri);
13957       }
13958    }
13959    return CLI_SUCCESS;
13960 }
13961 #endif   /* defined(HAVE_PRI) */
13962 
13963 #if defined(HAVE_PRI)
13964 static char *handle_pri_show_span(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13965 {
13966    int span;
13967 
13968    switch (cmd) {
13969    case CLI_INIT:
13970       e->command = "pri show span";
13971       e->usage =
13972          "Usage: pri show span <span>\n"
13973          "       Displays PRI Information on a given PRI span\n";
13974       return NULL;
13975    case CLI_GENERATE:
13976       return complete_span_4(a->line, a->word, a->pos, a->n);
13977    }
13978 
13979    if (a->argc < 4)
13980       return CLI_SHOWUSAGE;
13981    span = atoi(a->argv[3]);
13982    if ((span < 1) || (span > NUM_SPANS)) {
13983       ast_cli(a->fd, "Invalid span '%s'.  Should be a number from %d to %d\n", a->argv[3], 1, NUM_SPANS);
13984       return CLI_SUCCESS;
13985    }
13986    if (!pris[span-1].pri.pri) {
13987       ast_cli(a->fd, "No PRI running on span %d\n", span);
13988       return CLI_SUCCESS;
13989    }
13990 
13991    sig_pri_cli_show_span(a->fd, pris[span-1].dchannels, &pris[span-1].pri);
13992 
13993    return CLI_SUCCESS;
13994 }
13995 #endif   /* defined(HAVE_PRI) */
13996 
13997 #if defined(HAVE_PRI)
13998 static char *handle_pri_show_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13999 {
14000    int x;
14001    int span;
14002    int count=0;
14003    int debug;
14004 
14005    switch (cmd) {
14006    case CLI_INIT:
14007       e->command = "pri show debug";
14008       e->usage =
14009          "Usage: pri show debug\n"
14010          "  Show the debug state of pri spans\n";
14011       return NULL;
14012    case CLI_GENERATE:
14013       return NULL;
14014    }
14015 
14016    for (span = 0; span < NUM_SPANS; span++) {
14017       if (pris[span].pri.pri) {
14018          for (x = 0; x < SIG_PRI_NUM_DCHANS; x++) {
14019             if (pris[span].pri.dchans[x]) {
14020                debug = pri_get_debug(pris[span].pri.dchans[x]);
14021                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" );
14022                count++;
14023             }
14024          }
14025       }
14026 
14027    }
14028    ast_mutex_lock(&pridebugfdlock);
14029    if (pridebugfd >= 0)
14030       ast_cli(a->fd, "Logging PRI debug to file %s\n", pridebugfilename);
14031    ast_mutex_unlock(&pridebugfdlock);
14032 
14033    if (!count)
14034       ast_cli(a->fd, "No PRI running\n");
14035    return CLI_SUCCESS;
14036 }
14037 #endif   /* defined(HAVE_PRI) */
14038 
14039 #if defined(HAVE_PRI)
14040 static char *handle_pri_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14041 {
14042    switch (cmd) {
14043    case CLI_INIT:
14044       e->command = "pri show version";
14045       e->usage =
14046          "Usage: pri show version\n"
14047          "Show libpri version information\n";
14048       return NULL;
14049    case CLI_GENERATE:
14050       return NULL;
14051    }
14052 
14053    ast_cli(a->fd, "libpri version: %s\n", pri_get_version());
14054 
14055    return CLI_SUCCESS;
14056 }
14057 #endif   /* defined(HAVE_PRI) */
14058 
14059 #if defined(HAVE_PRI)
14060 static struct ast_cli_entry dahdi_pri_cli[] = {
14061    AST_CLI_DEFINE(handle_pri_debug, "Enables PRI debugging on a span"),
14062 #if defined(HAVE_PRI_SERVICE_MESSAGES)
14063    AST_CLI_DEFINE(handle_pri_service_enable_channel, "Return a channel to service"),
14064    AST_CLI_DEFINE(handle_pri_service_disable_channel, "Remove a channel from service"),
14065 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
14066    AST_CLI_DEFINE(handle_pri_show_spans, "Displays PRI Information"),
14067    AST_CLI_DEFINE(handle_pri_show_span, "Displays PRI Information"),
14068    AST_CLI_DEFINE(handle_pri_show_debug, "Displays current PRI debug settings"),
14069    AST_CLI_DEFINE(handle_pri_set_debug_file, "Sends PRI debug output to the specified file"),
14070    AST_CLI_DEFINE(handle_pri_version, "Displays libpri version"),
14071 };
14072 #endif   /* defined(HAVE_PRI) */
14073 
14074 #ifdef HAVE_OPENR2
14075 
14076 static char *handle_mfcr2_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14077 {
14078    switch (cmd) {
14079    case CLI_INIT:
14080       e->command = "mfcr2 show version";
14081       e->usage =
14082          "Usage: mfcr2 show version\n"
14083          "       Shows the version of the OpenR2 library being used.\n";
14084       return NULL;
14085    case CLI_GENERATE:
14086       return NULL;
14087    }
14088    ast_cli(a->fd, "OpenR2 version: %s, revision: %s\n", openr2_get_version(), openr2_get_revision());
14089    return CLI_SUCCESS;
14090 }
14091 
14092 static char *handle_mfcr2_show_variants(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14093 {
14094 #define FORMAT "%4s %40s\n"
14095    int i = 0;
14096    int numvariants = 0;
14097    const openr2_variant_entry_t *variants;
14098    switch (cmd) {
14099    case CLI_INIT:
14100       e->command = "mfcr2 show variants";
14101       e->usage =
14102          "Usage: mfcr2 show variants\n"
14103          "       Shows the list of MFC/R2 variants supported.\n";
14104       return NULL;
14105    case CLI_GENERATE:
14106       return NULL;
14107    }
14108    if (!(variants = openr2_proto_get_variant_list(&numvariants))) {
14109       ast_cli(a->fd, "Failed to get list of variants.\n");
14110       return CLI_FAILURE;
14111    }
14112    ast_cli(a->fd, FORMAT, "Variant Code", "Country");
14113    for (i = 0; i < numvariants; i++) {
14114       ast_cli(a->fd, FORMAT, variants[i].name, variants[i].country);
14115    }
14116    return CLI_SUCCESS;
14117 #undef FORMAT
14118 }
14119 
14120 static char *handle_mfcr2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14121 {
14122 #define FORMAT "%4s %-7.7s %-7.7s %-8.8s %-9.9s %-16.16s %-8.8s %-8.8s\n"
14123    int filtertype = 0;
14124    int targetnum = 0;
14125    char channo[5];
14126    char anino[5];
14127    char dnisno[5];
14128    struct dahdi_pvt *p;
14129    openr2_context_t *r2context;
14130    openr2_variant_t r2variant;
14131    switch (cmd) {
14132    case CLI_INIT:
14133       e->command = "mfcr2 show channels [group|context]";
14134       e->usage =
14135          "Usage: mfcr2 show channels [group <group> | context <context>]\n"
14136          "       Shows the DAHDI channels configured with MFC/R2 signaling.\n";
14137       return NULL;
14138    case CLI_GENERATE:
14139       return NULL;
14140    }
14141    if (!((a->argc == 3) || (a->argc == 5))) {
14142       return CLI_SHOWUSAGE;
14143    }
14144    if (a->argc == 5) {
14145       if (!strcasecmp(a->argv[3], "group")) {
14146          targetnum = atoi(a->argv[4]);
14147          if ((targetnum < 0) || (targetnum > 63))
14148             return CLI_SHOWUSAGE;
14149          targetnum = 1 << targetnum;
14150          filtertype = 1;
14151       } else if (!strcasecmp(a->argv[3], "context")) {
14152          filtertype = 2;
14153       } else {
14154          return CLI_SHOWUSAGE;
14155       }
14156    }
14157    ast_cli(a->fd, FORMAT, "Chan", "Variant", "Max ANI", "Max DNIS", "ANI First", "Immediate Accept", "Tx CAS", "Rx CAS");
14158    ast_mutex_lock(&iflock);
14159    for (p = iflist; p; p = p->next) {
14160       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14161          continue;
14162       }
14163       if (filtertype) {
14164          switch(filtertype) {
14165          case 1: /* mfcr2 show channels group <group> */
14166             if (p->group != targetnum) {
14167                continue;
14168             }
14169             break;
14170          case 2: /* mfcr2 show channels context <context> */
14171             if (strcasecmp(p->context, a->argv[4])) {
14172                continue;
14173             }
14174             break;
14175          default:
14176             ;
14177          }
14178       }
14179       r2context = openr2_chan_get_context(p->r2chan);
14180       r2variant = openr2_context_get_variant(r2context);
14181       snprintf(channo, sizeof(channo), "%d", p->channel);
14182       snprintf(anino, sizeof(anino), "%d", openr2_context_get_max_ani(r2context));
14183       snprintf(dnisno, sizeof(dnisno), "%d", openr2_context_get_max_dnis(r2context));
14184       ast_cli(a->fd, FORMAT, channo, openr2_proto_get_variant_string(r2variant),
14185             anino, dnisno, openr2_context_get_ani_first(r2context) ? "Yes" : "No",
14186             openr2_context_get_immediate_accept(r2context) ? "Yes" : "No",
14187             openr2_chan_get_tx_cas_string(p->r2chan), openr2_chan_get_rx_cas_string(p->r2chan));
14188    }
14189    ast_mutex_unlock(&iflock);
14190    return CLI_SUCCESS;
14191 #undef FORMAT
14192 }
14193 
14194 static char *handle_mfcr2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14195 {
14196    struct dahdi_pvt *p = NULL;
14197    int channo = 0;
14198    char *toklevel = NULL;
14199    char *saveptr = NULL;
14200    char *logval = NULL;
14201    openr2_log_level_t loglevel = OR2_LOG_NOTHING;
14202    openr2_log_level_t tmplevel = OR2_LOG_NOTHING;
14203    switch (cmd) {
14204    case CLI_INIT:
14205       e->command = "mfcr2 set debug";
14206       e->usage =
14207          "Usage: mfcr2 set debug <loglevel> <channel>\n"
14208          "       Set a new logging level for the specified channel.\n"
14209          "       If no channel is specified the logging level will be applied to all channels.\n";
14210       return NULL;
14211    case CLI_GENERATE:
14212       return NULL;
14213    }
14214    if (a->argc < 4) {
14215       return CLI_SHOWUSAGE;
14216    }
14217    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14218    logval = ast_strdupa(a->argv[3]);
14219    toklevel = strtok_r(logval, ",", &saveptr);
14220    if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14221       ast_cli(a->fd, "Invalid MFC/R2 logging level '%s'.\n", a->argv[3]);
14222       return CLI_FAILURE;
14223    } else if (OR2_LOG_NOTHING == tmplevel) {
14224       loglevel = tmplevel;
14225    } else {
14226       loglevel |= tmplevel;
14227       while ((toklevel = strtok_r(NULL, ",", &saveptr))) {
14228          if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14229             ast_cli(a->fd, "Ignoring invalid logging level: '%s'.\n", toklevel);
14230             continue;
14231          }
14232          loglevel |= tmplevel;
14233       }
14234    }
14235    ast_mutex_lock(&iflock);
14236    for (p = iflist; p; p = p->next) {
14237       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14238          continue;
14239       }
14240       if ((channo != -1) && (p->channel != channo )) {
14241          continue;
14242       }
14243       openr2_chan_set_log_level(p->r2chan, loglevel);
14244       if (channo != -1) {
14245          ast_cli(a->fd, "MFC/R2 debugging set to '%s' for channel %d.\n", a->argv[3], p->channel);
14246          break;
14247       }
14248    }
14249    if ((channo != -1) && !p) {
14250       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14251    }
14252    if (channo == -1) {
14253       ast_cli(a->fd, "MFC/R2 debugging set to '%s' for all channels.\n", a->argv[3]);
14254    }
14255    ast_mutex_unlock(&iflock);
14256    return CLI_SUCCESS;
14257 }
14258 
14259 static char *handle_mfcr2_call_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14260 {
14261    struct dahdi_pvt *p = NULL;
14262    int channo = 0;
14263    switch (cmd) {
14264    case CLI_INIT:
14265       e->command = "mfcr2 call files [on|off]";
14266       e->usage =
14267          "Usage: mfcr2 call files [on|off] <channel>\n"
14268          "       Enable call files creation on the specified channel.\n"
14269          "       If no channel is specified call files creation policy will be applied to all channels.\n";
14270       return NULL;
14271    case CLI_GENERATE:
14272       return NULL;
14273    }
14274    if (a->argc < 4) {
14275       return CLI_SHOWUSAGE;
14276    }
14277    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14278    ast_mutex_lock(&iflock);
14279    for (p = iflist; p; p = p->next) {
14280       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14281          continue;
14282       }
14283       if ((channo != -1) && (p->channel != channo )) {
14284          continue;
14285       }
14286       if (ast_true(a->argv[3])) {
14287          openr2_chan_enable_call_files(p->r2chan);
14288       } else {
14289          openr2_chan_disable_call_files(p->r2chan);
14290       }
14291       if (channo != -1) {
14292          if (ast_true(a->argv[3])) {
14293             ast_cli(a->fd, "MFC/R2 call files enabled for channel %d.\n", p->channel);
14294          } else {
14295             ast_cli(a->fd, "MFC/R2 call files disabled for channel %d.\n", p->channel);
14296          }
14297          break;
14298       }
14299    }
14300    if ((channo != -1) && !p) {
14301       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14302    }
14303    if (channo == -1) {
14304       if (ast_true(a->argv[3])) {
14305          ast_cli(a->fd, "MFC/R2 Call files enabled for all channels.\n");
14306       } else {
14307          ast_cli(a->fd, "MFC/R2 Call files disabled for all channels.\n");
14308       }
14309    }
14310    ast_mutex_unlock(&iflock);
14311    return CLI_SUCCESS;
14312 }
14313 
14314 static char *handle_mfcr2_set_idle(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14315 {
14316    struct dahdi_pvt *p = NULL;
14317    int channo = 0;
14318    switch (cmd) {
14319    case CLI_INIT:
14320       e->command = "mfcr2 set idle";
14321       e->usage =
14322          "Usage: mfcr2 set idle <channel>\n"
14323          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14324          "       Force the given channel into IDLE state.\n"
14325          "       If no channel is specified, all channels will be set to IDLE.\n";
14326       return NULL;
14327    case CLI_GENERATE:
14328       return NULL;
14329    }
14330    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14331    ast_mutex_lock(&iflock);
14332    for (p = iflist; p; p = p->next) {
14333       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14334          continue;
14335       }
14336       if ((channo != -1) && (p->channel != channo )) {
14337          continue;
14338       }
14339       openr2_chan_set_idle(p->r2chan);
14340       ast_mutex_lock(&p->lock);
14341       p->locallyblocked = 0;
14342       p->mfcr2call = 0;
14343       ast_mutex_unlock(&p->lock);
14344       if (channo != -1) {
14345          break;
14346       }
14347    }
14348    if ((channo != -1) && !p) {
14349       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14350    }
14351    ast_mutex_unlock(&iflock);
14352    return CLI_SUCCESS;
14353 }
14354 
14355 static char *handle_mfcr2_set_blocked(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14356 {
14357    struct dahdi_pvt *p = NULL;
14358    int channo = 0;
14359    switch (cmd) {
14360    case CLI_INIT:
14361       e->command = "mfcr2 set blocked";
14362       e->usage =
14363          "Usage: mfcr2 set blocked <channel>\n"
14364          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14365          "       Force the given channel into BLOCKED state.\n"
14366          "       If no channel is specified, all channels will be set to BLOCKED.\n";
14367       return NULL;
14368    case CLI_GENERATE:
14369       return NULL;
14370    }
14371    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14372    ast_mutex_lock(&iflock);
14373    for (p = iflist; p; p = p->next) {
14374       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14375          continue;
14376       }
14377       if ((channo != -1) && (p->channel != channo )) {
14378          continue;
14379       }
14380       openr2_chan_set_blocked(p->r2chan);
14381       ast_mutex_lock(&p->lock);
14382       p->locallyblocked = 1;
14383       ast_mutex_unlock(&p->lock);
14384       if (channo != -1) {
14385          break;
14386       }
14387    }
14388    if ((channo != -1) && !p) {
14389       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14390    }
14391    ast_mutex_unlock(&iflock);
14392    return CLI_SUCCESS;
14393 }
14394 
14395 static struct ast_cli_entry dahdi_mfcr2_cli[] = {
14396    AST_CLI_DEFINE(handle_mfcr2_version, "Show OpenR2 library version"),
14397    AST_CLI_DEFINE(handle_mfcr2_show_variants, "Show supported MFC/R2 variants"),
14398    AST_CLI_DEFINE(handle_mfcr2_show_channels, "Show MFC/R2 channels"),
14399    AST_CLI_DEFINE(handle_mfcr2_set_debug, "Set MFC/R2 channel logging level"),
14400    AST_CLI_DEFINE(handle_mfcr2_call_files, "Enable/Disable MFC/R2 call files"),
14401    AST_CLI_DEFINE(handle_mfcr2_set_idle, "Reset MFC/R2 channel forcing it to IDLE"),
14402    AST_CLI_DEFINE(handle_mfcr2_set_blocked, "Reset MFC/R2 channel forcing it to BLOCKED"),
14403 };
14404 
14405 #endif /* HAVE_OPENR2 */
14406 
14407 static char *dahdi_destroy_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14408 {
14409    int channel;
14410    int ret;
14411    switch (cmd) {
14412    case CLI_INIT:
14413       e->command = "dahdi destroy channel";
14414       e->usage =
14415          "Usage: dahdi destroy channel <chan num>\n"
14416          "  DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.  Immediately removes a given channel, whether it is in use or not\n";
14417       return NULL;
14418    case CLI_GENERATE:
14419       return NULL;
14420    }
14421    if (a->argc != 4)
14422       return CLI_SHOWUSAGE;
14423 
14424    channel = atoi(a->argv[3]);
14425    ret = dahdi_destroy_channel_bynum(channel);
14426    return ( RESULT_SUCCESS == ret ) ? CLI_SUCCESS : CLI_FAILURE;
14427 }
14428 
14429 static void dahdi_softhangup_all(void)
14430 {
14431    struct dahdi_pvt *p;
14432 retry:
14433    ast_mutex_lock(&iflock);
14434    for (p = iflist; p; p = p->next) {
14435       ast_mutex_lock(&p->lock);
14436       if (p->owner && !p->restartpending) {
14437          if (ast_channel_trylock(p->owner)) {
14438             if (option_debug > 2)
14439                ast_verbose("Avoiding deadlock\n");
14440             /* Avoid deadlock since you're not supposed to lock iflock or pvt before a channel */
14441             ast_mutex_unlock(&p->lock);
14442             ast_mutex_unlock(&iflock);
14443             goto retry;
14444          }
14445          if (option_debug > 2)
14446             ast_verbose("Softhanging up on %s\n", p->owner->name);
14447          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_EXPLICIT);
14448          p->restartpending = 1;
14449          num_restart_pending++;
14450          ast_channel_unlock(p->owner);
14451       }
14452       ast_mutex_unlock(&p->lock);
14453    }
14454    ast_mutex_unlock(&iflock);
14455 }
14456 
14457 static int setup_dahdi(int reload);
14458 static int dahdi_restart(void)
14459 {
14460 #if defined(HAVE_PRI) || defined(HAVE_SS7)
14461    int i, j;
14462 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
14463    int cancel_code;
14464    struct dahdi_pvt *p;
14465 
14466    ast_mutex_lock(&restart_lock);
14467    ast_verb(1, "Destroying channels and reloading DAHDI configuration.\n");
14468    dahdi_softhangup_all();
14469    ast_verb(4, "Initial softhangup of all DAHDI channels complete.\n");
14470 #ifdef HAVE_OPENR2
14471    dahdi_r2_destroy_links();
14472 #endif
14473 
14474 #if defined(HAVE_PRI)
14475    for (i = 0; i < NUM_SPANS; i++) {
14476       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL)) {
14477          cancel_code = pthread_cancel(pris[i].pri.master);
14478          pthread_kill(pris[i].pri.master, SIGURG);
14479          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);
14480          pthread_join(pris[i].pri.master, NULL);
14481          ast_debug(4, "Joined thread of span %d\n", i);
14482       }
14483    }
14484 #endif
14485 
14486 #if defined(HAVE_SS7)
14487    for (i = 0; i < NUM_SPANS; i++) {
14488       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL)) {
14489          cancel_code = pthread_cancel(linksets[i].ss7.master);
14490          pthread_kill(linksets[i].ss7.master, SIGURG);
14491          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);
14492          pthread_join(linksets[i].ss7.master, NULL);
14493          ast_debug(4, "Joined thread of span %d\n", i);
14494       }
14495    }
14496 #endif   /* defined(HAVE_SS7) */
14497 
14498    ast_mutex_lock(&monlock);
14499    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
14500       cancel_code = pthread_cancel(monitor_thread);
14501       pthread_kill(monitor_thread, SIGURG);
14502       ast_debug(4, "Waiting to join monitor thread with pid=%p, cancel_code=%d\n", (void *) monitor_thread, cancel_code);
14503       pthread_join(monitor_thread, NULL);
14504       ast_debug(4, "Joined monitor thread\n");
14505    }
14506    monitor_thread = AST_PTHREADT_NULL; /* prepare to restart thread in setup_dahdi once channels are reconfigured */
14507 
14508    ast_mutex_lock(&ss_thread_lock);
14509    while (ss_thread_count > 0) { /* let ss_threads finish and run dahdi_hangup before dahvi_pvts are destroyed */
14510       int x = DAHDI_FLASH;
14511       ast_debug(3, "Waiting on %d analog_ss_thread(s) to finish\n", ss_thread_count);
14512 
14513       ast_mutex_lock(&iflock);
14514       for (p = iflist; p; p = p->next) {
14515          if (p->owner) {
14516             /* important to create an event for dahdi_wait_event to register so that all analog_ss_threads terminate */
14517             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
14518          }
14519       }
14520       ast_mutex_unlock(&iflock);
14521       ast_cond_wait(&ss_thread_complete, &ss_thread_lock);
14522    }
14523 
14524    /* ensure any created channels before monitor threads were stopped are hungup */
14525    dahdi_softhangup_all();
14526    ast_verb(4, "Final softhangup of all DAHDI channels complete.\n");
14527    destroy_all_channels();
14528    ast_debug(1, "Channels destroyed. Now re-reading config. %d active channels remaining.\n", ast_active_channels());
14529 
14530    ast_mutex_unlock(&monlock);
14531 
14532 #ifdef HAVE_PRI
14533    for (i = 0; i < NUM_SPANS; i++) {
14534       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++)
14535          dahdi_close_pri_fd(&(pris[i]), j);
14536    }
14537 
14538    memset(pris, 0, sizeof(pris));
14539    for (i = 0; i < NUM_SPANS; i++) {
14540       sig_pri_init_pri(&pris[i].pri);
14541    }
14542    pri_set_error(dahdi_pri_error);
14543    pri_set_message(dahdi_pri_message);
14544 #endif
14545 #if defined(HAVE_SS7)
14546    for (i = 0; i < NUM_SPANS; i++) {
14547       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++)
14548          dahdi_close_ss7_fd(&(linksets[i]), j);
14549    }
14550 
14551    memset(linksets, 0, sizeof(linksets));
14552    for (i = 0; i < NUM_SPANS; i++) {
14553       sig_ss7_init_linkset(&linksets[i].ss7);
14554    }
14555    ss7_set_error(dahdi_ss7_error);
14556    ss7_set_message(dahdi_ss7_message);
14557 #endif   /* defined(HAVE_SS7) */
14558 
14559    if (setup_dahdi(2) != 0) {
14560       ast_log(LOG_WARNING, "Reload channels from dahdi config failed!\n");
14561       ast_mutex_unlock(&ss_thread_lock);
14562       return 1;
14563    }
14564    ast_mutex_unlock(&ss_thread_lock);
14565    ast_mutex_unlock(&restart_lock);
14566    return 0;
14567 }
14568 
14569 static char *dahdi_restart_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14570 {
14571    switch (cmd) {
14572    case CLI_INIT:
14573       e->command = "dahdi restart";
14574       e->usage =
14575          "Usage: dahdi restart\n"
14576          "  Restarts the DAHDI channels: destroys them all and then\n"
14577          "  re-reads them from chan_dahdi.conf.\n"
14578          "  Note that this will STOP any running CALL on DAHDI channels.\n"
14579          "";
14580       return NULL;
14581    case CLI_GENERATE:
14582       return NULL;
14583    }
14584    if (a->argc != 2)
14585       return CLI_SHOWUSAGE;
14586 
14587    if (dahdi_restart() != 0)
14588       return CLI_FAILURE;
14589    return CLI_SUCCESS;
14590 }
14591 
14592 static int action_dahdirestart(struct mansession *s, const struct message *m)
14593 {
14594    if (dahdi_restart() != 0) {
14595       astman_send_error(s, m, "Failed rereading DAHDI configuration");
14596       return 1;
14597    }
14598    astman_send_ack(s, m, "DAHDIRestart: Success");
14599    return 0;
14600 }
14601 
14602 static char *dahdi_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14603 {
14604 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
14605 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
14606    unsigned int targetnum = 0;
14607    int filtertype = 0;
14608    struct dahdi_pvt *tmp = NULL;
14609    char tmps[20] = "";
14610    char statestr[20] = "";
14611    char blockstr[20] = "";
14612 
14613    switch (cmd) {
14614    case CLI_INIT:
14615       e->command = "dahdi show channels [group|context]";
14616       e->usage =
14617          "Usage: dahdi show channels [ group <group> | context <context> ]\n"
14618          "  Shows a list of available channels with optional filtering\n"
14619          "  <group> must be a number between 0 and 63\n";
14620       return NULL;
14621    case CLI_GENERATE:
14622       return NULL;
14623    }
14624 
14625    /* syntax: dahdi show channels [ group <group> | context <context> ] */
14626 
14627    if (!((a->argc == 3) || (a->argc == 5)))
14628       return CLI_SHOWUSAGE;
14629 
14630    if (a->argc == 5) {
14631       if (!strcasecmp(a->argv[3], "group")) {
14632          targetnum = atoi(a->argv[4]);
14633          if ((targetnum < 0) || (targetnum > 63))
14634             return CLI_SHOWUSAGE;
14635          targetnum = 1 << targetnum;
14636          filtertype = 1;
14637       } else if (!strcasecmp(a->argv[3], "context")) {
14638          filtertype = 2;
14639       }
14640    }
14641 
14642    ast_cli(a->fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret", "Blocked", "State");
14643    ast_mutex_lock(&iflock);
14644    for (tmp = iflist; tmp; tmp = tmp->next) {
14645       if (filtertype) {
14646          switch(filtertype) {
14647          case 1: /* dahdi show channels group <group> */
14648             if (!(tmp->group & targetnum)) {
14649                continue;
14650             }
14651             break;
14652          case 2: /* dahdi show channels context <context> */
14653             if (strcasecmp(tmp->context, a->argv[4])) {
14654                continue;
14655             }
14656             break;
14657          default:
14658             ;
14659          }
14660       }
14661       if (tmp->channel > 0) {
14662          snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
14663       } else
14664          ast_copy_string(tmps, "pseudo", sizeof(tmps));
14665 
14666       if (tmp->locallyblocked)
14667          blockstr[0] = 'L';
14668       else
14669          blockstr[0] = ' ';
14670 
14671       if (tmp->remotelyblocked)
14672          blockstr[1] = 'R';
14673       else
14674          blockstr[1] = ' ';
14675 
14676       blockstr[2] = '\0';
14677 
14678       snprintf(statestr, sizeof(statestr), "%s", "In Service");
14679 
14680       ast_cli(a->fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret, blockstr, statestr);
14681    }
14682    ast_mutex_unlock(&iflock);
14683    return CLI_SUCCESS;
14684 #undef FORMAT
14685 #undef FORMAT2
14686 }
14687 
14688 static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14689 {
14690    int channel;
14691    struct dahdi_pvt *tmp = NULL;
14692    struct dahdi_confinfo ci;
14693    struct dahdi_params ps;
14694    int x;
14695 
14696    switch (cmd) {
14697    case CLI_INIT:
14698       e->command = "dahdi show channel";
14699       e->usage =
14700          "Usage: dahdi show channel <chan num>\n"
14701          "  Detailed information about a given channel\n";
14702       return NULL;
14703    case CLI_GENERATE:
14704       return NULL;
14705    }
14706 
14707    if (a->argc != 4)
14708       return CLI_SHOWUSAGE;
14709 
14710    channel = atoi(a->argv[3]);
14711 
14712    ast_mutex_lock(&iflock);
14713    for (tmp = iflist; tmp; tmp = tmp->next) {
14714       if (tmp->channel == channel) {
14715          ast_cli(a->fd, "Channel: %d\n", tmp->channel);
14716          ast_cli(a->fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].dfd);
14717          ast_cli(a->fd, "Span: %d\n", tmp->span);
14718          ast_cli(a->fd, "Extension: %s\n", tmp->exten);
14719          ast_cli(a->fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
14720          ast_cli(a->fd, "Context: %s\n", tmp->context);
14721          ast_cli(a->fd, "Caller ID: %s\n", tmp->cid_num);
14722          ast_cli(a->fd, "Calling TON: %d\n", tmp->cid_ton);
14723 #if defined(HAVE_PRI)
14724 #if defined(HAVE_PRI_SUBADDR)
14725          ast_cli(a->fd, "Caller ID subaddress: %s\n", tmp->cid_subaddr);
14726 #endif   /* defined(HAVE_PRI_SUBADDR) */
14727 #endif   /* defined(HAVE_PRI) */
14728          ast_cli(a->fd, "Caller ID name: %s\n", tmp->cid_name);
14729          ast_cli(a->fd, "Mailbox: %s\n", S_OR(tmp->mailbox, "none"));
14730          if (tmp->vars) {
14731             struct ast_variable *v;
14732             ast_cli(a->fd, "Variables:\n");
14733             for (v = tmp->vars ; v ; v = v->next)
14734                ast_cli(a->fd, "       %s = %s\n", v->name, v->value);
14735          }
14736          ast_cli(a->fd, "Destroy: %d\n", tmp->destroy);
14737          ast_cli(a->fd, "InAlarm: %d\n", tmp->inalarm);
14738          ast_cli(a->fd, "Signalling Type: %s\n", sig2str(tmp->sig));
14739          ast_cli(a->fd, "Radio: %d\n", tmp->radio);
14740          ast_cli(a->fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
14741          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)" : "");
14742          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)" : "");
14743          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)" : "");
14744          ast_cli(a->fd, "Confno: %d\n", tmp->confno);
14745          ast_cli(a->fd, "Propagated Conference: %d\n", tmp->propconfno);
14746          ast_cli(a->fd, "Real in conference: %d\n", tmp->inconference);
14747          ast_cli(a->fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
14748          ast_cli(a->fd, "Busy Detection: %s\n", tmp->busydetect ? "yes" : "no");
14749          if (tmp->busydetect) {
14750 #if defined(BUSYDETECT_TONEONLY)
14751             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_TONEONLY\n");
14752 #elif defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
14753             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_COMPARE_TONE_AND_SILENCE\n");
14754 #endif
14755 #ifdef BUSYDETECT_DEBUG
14756             ast_cli(a->fd, "    Busy Detector Debug: Enabled\n");
14757 #endif
14758             ast_cli(a->fd, "    Busy Count: %d\n", tmp->busycount);
14759             ast_cli(a->fd, "    Busy Pattern: %d,%d\n", tmp->busy_tonelength, tmp->busy_quietlength);
14760          }
14761          ast_cli(a->fd, "TDD: %s\n", tmp->tdd ? "yes" : "no");
14762          ast_cli(a->fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
14763          ast_cli(a->fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
14764          ast_cli(a->fd, "Default law: %s\n", tmp->law_default == DAHDI_LAW_MULAW ? "ulaw" : tmp->law_default == DAHDI_LAW_ALAW ? "alaw" : "unknown");
14765          ast_cli(a->fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
14766          ast_cli(a->fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
14767          ast_cli(a->fd, "Gains (RX/TX): %.2f/%.2f\n", tmp->rxgain, tmp->txgain);
14768          ast_cli(a->fd, "Dynamic Range Compression (RX/TX): %.2f/%.2f\n", tmp->rxdrc, tmp->txdrc);
14769          ast_cli(a->fd, "DND: %s\n", dahdi_dnd(tmp, -1) ? "yes" : "no");
14770          ast_cli(a->fd, "Echo Cancellation:\n");
14771 
14772          if (tmp->echocancel.head.tap_length) {
14773             ast_cli(a->fd, "\t%d taps\n", tmp->echocancel.head.tap_length);
14774             for (x = 0; x < tmp->echocancel.head.param_count; x++) {
14775                ast_cli(a->fd, "\t\t%s: %ud\n", tmp->echocancel.params[x].name, tmp->echocancel.params[x].value);
14776             }
14777             ast_cli(a->fd, "\t%scurrently %s\n", tmp->echocanbridged ? "" : "(unless TDM bridged) ", tmp->echocanon ? "ON" : "OFF");
14778          } else {
14779             ast_cli(a->fd, "\tnone\n");
14780          }
14781          ast_cli(a->fd, "Wait for dialtone: %dms\n", tmp->waitfordialtone);
14782          if (tmp->master)
14783             ast_cli(a->fd, "Master Channel: %d\n", tmp->master->channel);
14784          for (x = 0; x < MAX_SLAVES; x++) {
14785             if (tmp->slaves[x])
14786                ast_cli(a->fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
14787          }
14788 #ifdef HAVE_OPENR2
14789          if (tmp->mfcr2) {
14790             char calldir[OR2_MAX_PATH];
14791             openr2_context_t *r2context = openr2_chan_get_context(tmp->r2chan);
14792             openr2_variant_t r2variant = openr2_context_get_variant(r2context);
14793             ast_cli(a->fd, "MFC/R2 MF State: %s\n", openr2_chan_get_mf_state_string(tmp->r2chan));
14794             ast_cli(a->fd, "MFC/R2 MF Group: %s\n", openr2_chan_get_mf_group_string(tmp->r2chan));
14795             ast_cli(a->fd, "MFC/R2 State: %s\n", openr2_chan_get_r2_state_string(tmp->r2chan));
14796             ast_cli(a->fd, "MFC/R2 Call State: %s\n", openr2_chan_get_call_state_string(tmp->r2chan));
14797             ast_cli(a->fd, "MFC/R2 Call Files Enabled: %s\n", openr2_chan_get_call_files_enabled(tmp->r2chan) ? "Yes" : "No");
14798             ast_cli(a->fd, "MFC/R2 Variant: %s\n", openr2_proto_get_variant_string(r2variant));
14799             ast_cli(a->fd, "MFC/R2 Max ANI: %d\n", openr2_context_get_max_ani(r2context));
14800             ast_cli(a->fd, "MFC/R2 Max DNIS: %d\n", openr2_context_get_max_dnis(r2context));
14801             ast_cli(a->fd, "MFC/R2 Get ANI First: %s\n", openr2_context_get_ani_first(r2context) ? "Yes" : "No");
14802 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
14803             ast_cli(a->fd, "MFC/R2 Skip Category Request: %s\n", openr2_context_get_skip_category_request(r2context) ? "Yes" : "No");
14804 #endif
14805             ast_cli(a->fd, "MFC/R2 Immediate Accept: %s\n", openr2_context_get_immediate_accept(r2context) ? "Yes" : "No");
14806             ast_cli(a->fd, "MFC/R2 Accept on Offer: %s\n", tmp->mfcr2_accept_on_offer ? "Yes" : "No");
14807             ast_cli(a->fd, "MFC/R2 Charge Calls: %s\n", tmp->mfcr2_charge_calls ? "Yes" : "No");
14808             ast_cli(a->fd, "MFC/R2 Allow Collect Calls: %s\n", tmp->mfcr2_allow_collect_calls ? "Yes" : "No");
14809             ast_cli(a->fd, "MFC/R2 Forced Release: %s\n", tmp->mfcr2_forced_release ? "Yes" : "No");
14810             ast_cli(a->fd, "MFC/R2 MF Back Timeout: %dms\n", openr2_context_get_mf_back_timeout(r2context));
14811             ast_cli(a->fd, "MFC/R2 R2 Metering Pulse Timeout: %dms\n", openr2_context_get_metering_pulse_timeout(r2context));
14812             ast_cli(a->fd, "MFC/R2 Rx CAS: %s\n", openr2_chan_get_rx_cas_string(tmp->r2chan));
14813             ast_cli(a->fd, "MFC/R2 Tx CAS: %s\n", openr2_chan_get_tx_cas_string(tmp->r2chan));
14814             ast_cli(a->fd, "MFC/R2 MF Tx Signal: %d\n", openr2_chan_get_tx_mf_signal(tmp->r2chan));
14815             ast_cli(a->fd, "MFC/R2 MF Rx Signal: %d\n", openr2_chan_get_rx_mf_signal(tmp->r2chan));
14816             ast_cli(a->fd, "MFC/R2 Call Files Directory: %s\n", openr2_context_get_log_directory(r2context, calldir, sizeof(calldir)));
14817          }
14818 #endif
14819 #if defined(HAVE_SS7)
14820          if (tmp->ss7) {
14821             struct sig_ss7_chan *chan = tmp->sig_pvt;
14822 
14823             ast_cli(a->fd, "CIC: %d\n", chan->cic);
14824          }
14825 #endif   /* defined(HAVE_SS7) */
14826 #ifdef HAVE_PRI
14827          if (tmp->pri) {
14828             struct sig_pri_chan *chan = tmp->sig_pvt;
14829 
14830             ast_cli(a->fd, "PRI Flags: ");
14831             if (chan->resetting)
14832                ast_cli(a->fd, "Resetting ");
14833             if (chan->call)
14834                ast_cli(a->fd, "Call ");
14835             ast_cli(a->fd, "\n");
14836             if (tmp->logicalspan)
14837                ast_cli(a->fd, "PRI Logical Span: %d\n", tmp->logicalspan);
14838             else
14839                ast_cli(a->fd, "PRI Logical Span: Implicit\n");
14840          }
14841 #endif
14842          memset(&ci, 0, sizeof(ci));
14843          ps.channo = tmp->channel;
14844          if (tmp->subs[SUB_REAL].dfd > -1) {
14845             memset(&ci, 0, sizeof(ci));
14846             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
14847                ast_cli(a->fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
14848             }
14849             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONFMUTE, &x)) {
14850                ast_cli(a->fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
14851             }
14852             memset(&ps, 0, sizeof(ps));
14853             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
14854                ast_log(LOG_WARNING, "Failed to get parameters on channel %d: %s\n", tmp->channel, strerror(errno));
14855             } else {
14856                ast_cli(a->fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
14857             }
14858          }
14859          ast_mutex_unlock(&iflock);
14860          return CLI_SUCCESS;
14861       }
14862    }
14863    ast_mutex_unlock(&iflock);
14864 
14865    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
14866    return CLI_FAILURE;
14867 }
14868 
14869 static char *handle_dahdi_show_cadences(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14870 {
14871    int i, j;
14872    switch (cmd) {
14873    case CLI_INIT:
14874       e->command = "dahdi show cadences";
14875       e->usage =
14876          "Usage: dahdi show cadences\n"
14877          "       Shows all cadences currently defined\n";
14878       return NULL;
14879    case CLI_GENERATE:
14880       return NULL;
14881    }
14882    for (i = 0; i < num_cadence; i++) {
14883       char output[1024];
14884       char tmp[16], tmp2[64];
14885       snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
14886       term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
14887 
14888       for (j = 0; j < 16; j++) {
14889          if (cadences[i].ringcadence[j] == 0)
14890             break;
14891          snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
14892          if (cidrings[i] * 2 - 1 == j)
14893             term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
14894          else
14895             term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
14896          if (j != 0)
14897             strncat(output, ",", sizeof(output) - strlen(output) - 1);
14898          strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
14899       }
14900       ast_cli(a->fd,"%s\n",output);
14901    }
14902    return CLI_SUCCESS;
14903 }
14904 
14905 /* Based on irqmiss.c */
14906 static char *dahdi_show_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14907 {
14908    #define FORMAT "%-40.40s %-7.7s %-6d %-6d %-6d %-3.3s %-4.4s %-8.8s %s\n"
14909    #define FORMAT2 "%-40.40s %-7.7s %-6.6s %-6.6s %-6.6s %-3.3s %-4.4s %-8.8s %s\n"
14910    int span;
14911    int res;
14912    char alarmstr[50];
14913 
14914    int ctl;
14915    struct dahdi_spaninfo s;
14916 
14917    switch (cmd) {
14918    case CLI_INIT:
14919       e->command = "dahdi show status";
14920       e->usage =
14921          "Usage: dahdi show status\n"
14922          "       Shows a list of DAHDI cards with status\n";
14923       return NULL;
14924    case CLI_GENERATE:
14925       return NULL;
14926    }
14927    ctl = open("/dev/dahdi/ctl", O_RDWR);
14928    if (ctl < 0) {
14929       ast_cli(a->fd, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
14930       return CLI_FAILURE;
14931    }
14932    ast_cli(a->fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC4", "Framing", "Coding", "Options", "LBO");
14933 
14934    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
14935       s.spanno = span;
14936       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
14937       if (res) {
14938          continue;
14939       }
14940       alarmstr[0] = '\0';
14941       if (s.alarms > 0) {
14942          if (s.alarms & DAHDI_ALARM_BLUE)
14943             strcat(alarmstr, "BLU/");
14944          if (s.alarms & DAHDI_ALARM_YELLOW)
14945             strcat(alarmstr, "YEL/");
14946          if (s.alarms & DAHDI_ALARM_RED)
14947             strcat(alarmstr, "RED/");
14948          if (s.alarms & DAHDI_ALARM_LOOPBACK)
14949             strcat(alarmstr, "LB/");
14950          if (s.alarms & DAHDI_ALARM_RECOVER)
14951             strcat(alarmstr, "REC/");
14952          if (s.alarms & DAHDI_ALARM_NOTOPEN)
14953             strcat(alarmstr, "NOP/");
14954          if (!strlen(alarmstr))
14955             strcat(alarmstr, "UUU/");
14956          if (strlen(alarmstr)) {
14957             /* Strip trailing / */
14958             alarmstr[strlen(alarmstr) - 1] = '\0';
14959          }
14960       } else {
14961          if (s.numchans)
14962             strcpy(alarmstr, "OK");
14963          else
14964             strcpy(alarmstr, "UNCONFIGURED");
14965       }
14966 
14967       ast_cli(a->fd, FORMAT, s.desc, alarmstr, s.irqmisses, s.bpvcount, s.crc4count,
14968          s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
14969          s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
14970          s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
14971          "CAS",
14972          s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
14973          s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
14974          s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
14975          "Unk",
14976          s.lineconfig & DAHDI_CONFIG_CRC4 ?
14977             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
14978             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "",
14979          lbostr[s.lbo]
14980          );
14981    }
14982    close(ctl);
14983 
14984    return CLI_SUCCESS;
14985 #undef FORMAT
14986 #undef FORMAT2
14987 }
14988 
14989 static char *dahdi_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14990 {
14991    int pseudo_fd = -1;
14992    struct dahdi_versioninfo vi;
14993 
14994    switch (cmd) {
14995    case CLI_INIT:
14996       e->command = "dahdi show version";
14997       e->usage =
14998          "Usage: dahdi show version\n"
14999          "       Shows the DAHDI version in use\n";
15000       return NULL;
15001    case CLI_GENERATE:
15002       return NULL;
15003    }
15004    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
15005       ast_cli(a->fd, "Failed to open control file to get version.\n");
15006       return CLI_SUCCESS;
15007    }
15008 
15009    strcpy(vi.version, "Unknown");
15010    strcpy(vi.echo_canceller, "Unknown");
15011 
15012    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi))
15013       ast_cli(a->fd, "Failed to get DAHDI version: %s\n", strerror(errno));
15014    else
15015       ast_cli(a->fd, "DAHDI Version: %s Echo Canceller: %s\n", vi.version, vi.echo_canceller);
15016 
15017    close(pseudo_fd);
15018 
15019    return CLI_SUCCESS;
15020 }
15021 
15022 static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15023 {
15024    int channel;
15025    int gain;
15026    int tx;
15027    struct dahdi_hwgain hwgain;
15028    struct dahdi_pvt *tmp = NULL;
15029 
15030    switch (cmd) {
15031    case CLI_INIT:
15032       e->command = "dahdi set hwgain";
15033       e->usage =
15034          "Usage: dahdi set hwgain <rx|tx> <chan#> <gain>\n"
15035          "  Sets the hardware gain on a a given channel, overriding the\n"
15036          "   value provided at module loadtime, whether the channel is in\n"
15037          "   use or not.  Changes take effect immediately.\n"
15038          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15039          "   <chan num> is the channel number relative to the device\n"
15040          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15041       return NULL;
15042    case CLI_GENERATE:
15043       return NULL;
15044    }
15045 
15046    if (a->argc != 6)
15047       return CLI_SHOWUSAGE;
15048 
15049    if (!strcasecmp("rx", a->argv[3]))
15050       tx = 0; /* rx */
15051    else if (!strcasecmp("tx", a->argv[3]))
15052       tx = 1; /* tx */
15053    else
15054       return CLI_SHOWUSAGE;
15055 
15056    channel = atoi(a->argv[4]);
15057    gain = atof(a->argv[5])*10.0;
15058 
15059    ast_mutex_lock(&iflock);
15060 
15061    for (tmp = iflist; tmp; tmp = tmp->next) {
15062 
15063       if (tmp->channel != channel)
15064          continue;
15065 
15066       if (tmp->subs[SUB_REAL].dfd == -1)
15067          break;
15068 
15069       hwgain.newgain = gain;
15070       hwgain.tx = tx;
15071       if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_HWGAIN, &hwgain) < 0) {
15072          ast_cli(a->fd, "Unable to set the hardware gain for channel %d: %s\n", channel, strerror(errno));
15073          ast_mutex_unlock(&iflock);
15074          return CLI_FAILURE;
15075       }
15076       ast_cli(a->fd, "hardware %s gain set to %d (%.1f dB) on channel %d\n",
15077          tx ? "tx" : "rx", gain, (float)gain/10.0, channel);
15078       break;
15079    }
15080 
15081    ast_mutex_unlock(&iflock);
15082 
15083    if (tmp)
15084       return CLI_SUCCESS;
15085 
15086    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15087    return CLI_FAILURE;
15088 
15089 }
15090 
15091 static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15092 {
15093    int channel;
15094    float gain;
15095    int tx;
15096    int res;
15097    struct dahdi_pvt *tmp = NULL;
15098 
15099    switch (cmd) {
15100    case CLI_INIT:
15101       e->command = "dahdi set swgain";
15102       e->usage =
15103          "Usage: dahdi set swgain <rx|tx> <chan#> <gain>\n"
15104          "  Sets the software gain on a a given channel, overriding the\n"
15105          "   value provided at module loadtime, whether the channel is in\n"
15106          "   use or not.  Changes take effect immediately.\n"
15107          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15108          "   <chan num> is the channel number relative to the device\n"
15109          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15110       return NULL;
15111    case CLI_GENERATE:
15112       return NULL;
15113    }
15114 
15115    if (a->argc != 6)
15116       return CLI_SHOWUSAGE;
15117 
15118    if (!strcasecmp("rx", a->argv[3]))
15119       tx = 0; /* rx */
15120    else if (!strcasecmp("tx", a->argv[3]))
15121       tx = 1; /* tx */
15122    else
15123       return CLI_SHOWUSAGE;
15124 
15125    channel = atoi(a->argv[4]);
15126    gain = atof(a->argv[5]);
15127 
15128    ast_mutex_lock(&iflock);
15129    for (tmp = iflist; tmp; tmp = tmp->next) {
15130 
15131       if (tmp->channel != channel)
15132          continue;
15133 
15134       if (tmp->subs[SUB_REAL].dfd == -1)
15135          break;
15136 
15137       if (tx)
15138          res = set_actual_txgain(tmp->subs[SUB_REAL].dfd, gain, tmp->txdrc, tmp->law);
15139       else
15140          res = set_actual_rxgain(tmp->subs[SUB_REAL].dfd, gain, tmp->rxdrc, tmp->law);
15141 
15142       if (res) {
15143          ast_cli(a->fd, "Unable to set the software gain for channel %d\n", channel);
15144          ast_mutex_unlock(&iflock);
15145          return CLI_FAILURE;
15146       }
15147 
15148       ast_cli(a->fd, "software %s gain set to %.1f on channel %d\n",
15149          tx ? "tx" : "rx", gain, channel);
15150       break;
15151    }
15152    ast_mutex_unlock(&iflock);
15153 
15154    if (tmp)
15155       return CLI_SUCCESS;
15156 
15157    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15158    return CLI_FAILURE;
15159 
15160 }
15161 
15162 static char *dahdi_set_dnd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15163 {
15164    int channel;
15165    int on;
15166    struct dahdi_pvt *dahdi_chan = NULL;
15167 
15168    switch (cmd) {
15169    case CLI_INIT:
15170       e->command = "dahdi set dnd";
15171       e->usage =
15172          "Usage: dahdi set dnd <chan#> <on|off>\n"
15173          "  Sets/resets DND (Do Not Disturb) mode on a channel.\n"
15174          "  Changes take effect immediately.\n"
15175          "  <chan num> is the channel number\n"
15176          "  <on|off> Enable or disable DND mode?\n"
15177          ;
15178       return NULL;
15179    case CLI_GENERATE:
15180       return NULL;
15181    }
15182 
15183    if (a->argc != 5)
15184       return CLI_SHOWUSAGE;
15185 
15186    if ((channel = atoi(a->argv[3])) <= 0) {
15187       ast_cli(a->fd, "Expected channel number, got '%s'\n", a->argv[3]);
15188       return CLI_SHOWUSAGE;
15189    }
15190 
15191    if (ast_true(a->argv[4]))
15192       on = 1;
15193    else if (ast_false(a->argv[4]))
15194       on = 0;
15195    else {
15196       ast_cli(a->fd, "Expected 'on' or 'off', got '%s'\n", a->argv[4]);
15197       return CLI_SHOWUSAGE;
15198    }
15199 
15200    ast_mutex_lock(&iflock);
15201    for (dahdi_chan = iflist; dahdi_chan; dahdi_chan = dahdi_chan->next) {
15202       if (dahdi_chan->channel != channel)
15203          continue;
15204 
15205       /* Found the channel. Actually set it */
15206       dahdi_dnd(dahdi_chan, on);
15207       break;
15208    }
15209    ast_mutex_unlock(&iflock);
15210 
15211    if (!dahdi_chan) {
15212       ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15213       return CLI_FAILURE;
15214    }
15215 
15216    return CLI_SUCCESS;
15217 }
15218 
15219 static struct ast_cli_entry dahdi_cli[] = {
15220    AST_CLI_DEFINE(handle_dahdi_show_cadences, "List cadences"),
15221    AST_CLI_DEFINE(dahdi_show_channels, "Show active DAHDI channels"),
15222    AST_CLI_DEFINE(dahdi_show_channel, "Show information on a channel"),
15223    AST_CLI_DEFINE(dahdi_destroy_channel, "Destroy a channel"),
15224    AST_CLI_DEFINE(dahdi_restart_cmd, "Fully restart DAHDI channels"),
15225    AST_CLI_DEFINE(dahdi_show_status, "Show all DAHDI cards status"),
15226    AST_CLI_DEFINE(dahdi_show_version, "Show the DAHDI version in use"),
15227    AST_CLI_DEFINE(dahdi_set_hwgain, "Set hardware gain on a channel"),
15228    AST_CLI_DEFINE(dahdi_set_swgain, "Set software gain on a channel"),
15229    AST_CLI_DEFINE(dahdi_set_dnd, "Sets/resets DND (Do Not Disturb) mode on a channel"),
15230 };
15231 
15232 #define TRANSFER  0
15233 #define HANGUP    1
15234 
15235 static int dahdi_fake_event(struct dahdi_pvt *p, int mode)
15236 {
15237    if (p) {
15238       switch (mode) {
15239       case TRANSFER:
15240          p->fake_event = DAHDI_EVENT_WINKFLASH;
15241          break;
15242       case HANGUP:
15243          p->fake_event = DAHDI_EVENT_ONHOOK;
15244          break;
15245       default:
15246          ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
15247       }
15248    }
15249    return 0;
15250 }
15251 static struct dahdi_pvt *find_channel(int channel)
15252 {
15253    struct dahdi_pvt *p;
15254 
15255    ast_mutex_lock(&iflock);
15256    for (p = iflist; p; p = p->next) {
15257       if (p->channel == channel) {
15258          break;
15259       }
15260    }
15261    ast_mutex_unlock(&iflock);
15262    return p;
15263 }
15264 
15265 static int action_dahdidndon(struct mansession *s, const struct message *m)
15266 {
15267    struct dahdi_pvt *p = NULL;
15268    const char *channel = astman_get_header(m, "DAHDIChannel");
15269 
15270    if (ast_strlen_zero(channel)) {
15271       astman_send_error(s, m, "No channel specified");
15272       return 0;
15273    }
15274    p = find_channel(atoi(channel));
15275    if (!p) {
15276       astman_send_error(s, m, "No such channel");
15277       return 0;
15278    }
15279    dahdi_dnd(p, 1);
15280    astman_send_ack(s, m, "DND Enabled");
15281    return 0;
15282 }
15283 
15284 static int action_dahdidndoff(struct mansession *s, const struct message *m)
15285 {
15286    struct dahdi_pvt *p = NULL;
15287    const char *channel = astman_get_header(m, "DAHDIChannel");
15288 
15289    if (ast_strlen_zero(channel)) {
15290       astman_send_error(s, m, "No channel specified");
15291       return 0;
15292    }
15293    p = find_channel(atoi(channel));
15294    if (!p) {
15295       astman_send_error(s, m, "No such channel");
15296       return 0;
15297    }
15298    dahdi_dnd(p, 0);
15299    astman_send_ack(s, m, "DND Disabled");
15300    return 0;
15301 }
15302 
15303 static int action_transfer(struct mansession *s, const struct message *m)
15304 {
15305    struct dahdi_pvt *p = NULL;
15306    const char *channel = astman_get_header(m, "DAHDIChannel");
15307 
15308    if (ast_strlen_zero(channel)) {
15309       astman_send_error(s, m, "No channel specified");
15310       return 0;
15311    }
15312    p = find_channel(atoi(channel));
15313    if (!p) {
15314       astman_send_error(s, m, "No such channel");
15315       return 0;
15316    }
15317    dahdi_fake_event(p,TRANSFER);
15318    astman_send_ack(s, m, "DAHDITransfer");
15319    return 0;
15320 }
15321 
15322 static int action_transferhangup(struct mansession *s, const struct message *m)
15323 {
15324    struct dahdi_pvt *p = NULL;
15325    const char *channel = astman_get_header(m, "DAHDIChannel");
15326 
15327    if (ast_strlen_zero(channel)) {
15328       astman_send_error(s, m, "No channel specified");
15329       return 0;
15330    }
15331    p = find_channel(atoi(channel));
15332    if (!p) {
15333       astman_send_error(s, m, "No such channel");
15334       return 0;
15335    }
15336    dahdi_fake_event(p,HANGUP);
15337    astman_send_ack(s, m, "DAHDIHangup");
15338    return 0;
15339 }
15340 
15341 static int action_dahdidialoffhook(struct mansession *s, const struct message *m)
15342 {
15343    struct dahdi_pvt *p = NULL;
15344    const char *channel = astman_get_header(m, "DAHDIChannel");
15345    const char *number = astman_get_header(m, "Number");
15346    int i;
15347 
15348    if (ast_strlen_zero(channel)) {
15349       astman_send_error(s, m, "No channel specified");
15350       return 0;
15351    }
15352    if (ast_strlen_zero(number)) {
15353       astman_send_error(s, m, "No number specified");
15354       return 0;
15355    }
15356    p = find_channel(atoi(channel));
15357    if (!p) {
15358       astman_send_error(s, m, "No such channel");
15359       return 0;
15360    }
15361    if (!p->owner) {
15362       astman_send_error(s, m, "Channel does not have it's owner");
15363       return 0;
15364    }
15365    for (i = 0; i < strlen(number); i++) {
15366       struct ast_frame f = { AST_FRAME_DTMF, .subclass.integer = number[i] };
15367       dahdi_queue_frame(p, &f);
15368    }
15369    astman_send_ack(s, m, "DAHDIDialOffhook");
15370    return 0;
15371 }
15372 
15373 static int action_dahdishowchannels(struct mansession *s, const struct message *m)
15374 {
15375    struct dahdi_pvt *tmp = NULL;
15376    const char *id = astman_get_header(m, "ActionID");
15377    const char *dahdichannel = astman_get_header(m, "DAHDIChannel");
15378    char idText[256] = "";
15379    int channels = 0;
15380    int dahdichanquery = -1;
15381    if (!ast_strlen_zero(dahdichannel)) {
15382       dahdichanquery = atoi(dahdichannel);
15383    }
15384 
15385    astman_send_ack(s, m, "DAHDI channel status will follow");
15386    if (!ast_strlen_zero(id))
15387       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
15388 
15389    ast_mutex_lock(&iflock);
15390 
15391    for (tmp = iflist; tmp; tmp = tmp->next) {
15392       if (tmp->channel > 0) {
15393          int alm;
15394 
15395          /* If a specific channel is queried for, only deliver status for that channel */
15396          if (dahdichanquery > 0 && tmp->channel != dahdichanquery)
15397             continue;
15398 
15399          alm = get_alarms(tmp);
15400          channels++;
15401          if (tmp->owner) {
15402             /* Add data if we have a current call */
15403             astman_append(s,
15404                "Event: DAHDIShowChannels\r\n"
15405                "DAHDIChannel: %d\r\n"
15406                "Channel: %s\r\n"
15407                "Uniqueid: %s\r\n"
15408                "AccountCode: %s\r\n"
15409                "Signalling: %s\r\n"
15410                "SignallingCode: %d\r\n"
15411                "Context: %s\r\n"
15412                "DND: %s\r\n"
15413                "Alarm: %s\r\n"
15414                "%s"
15415                "\r\n",
15416                tmp->channel,
15417                tmp->owner->name,
15418                tmp->owner->uniqueid,
15419                tmp->owner->accountcode,
15420                sig2str(tmp->sig),
15421                tmp->sig,
15422                tmp->context,
15423                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
15424                alarm2str(alm), idText);
15425          } else {
15426             astman_append(s,
15427                "Event: DAHDIShowChannels\r\n"
15428                "DAHDIChannel: %d\r\n"
15429                "Signalling: %s\r\n"
15430                "SignallingCode: %d\r\n"
15431                "Context: %s\r\n"
15432                "DND: %s\r\n"
15433                "Alarm: %s\r\n"
15434                "%s"
15435                "\r\n",
15436                tmp->channel, sig2str(tmp->sig), tmp->sig,
15437                tmp->context,
15438                dahdi_dnd(tmp, -1) ? "Enabled" : "Disabled",
15439                alarm2str(alm), idText);
15440          }
15441       }
15442    }
15443 
15444    ast_mutex_unlock(&iflock);
15445 
15446    astman_append(s,
15447       "Event: DAHDIShowChannelsComplete\r\n"
15448       "%s"
15449       "Items: %d\r\n"
15450       "\r\n",
15451       idText,
15452       channels);
15453    return 0;
15454 }
15455 
15456 #if defined(HAVE_SS7)
15457 static int linkset_addsigchan(int sigchan)
15458 {
15459    struct dahdi_ss7 *link;
15460    int res;
15461    int curfd;
15462    struct dahdi_params params;
15463    struct dahdi_bufferinfo bi;
15464    struct dahdi_spaninfo si;
15465 
15466    if (sigchan < 0) {
15467       ast_log(LOG_ERROR, "Invalid sigchan!\n");
15468       return -1;
15469    }
15470    if (cur_ss7type < 0) {
15471       ast_log(LOG_ERROR, "Unspecified or invalid ss7type\n");
15472       return -1;
15473    }
15474    if (cur_pointcode < 0) {
15475       ast_log(LOG_ERROR, "Unspecified pointcode!\n");
15476       return -1;
15477    }
15478    if (cur_adjpointcode < 0) {
15479       ast_log(LOG_ERROR, "Unspecified adjpointcode!\n");
15480       return -1;
15481    }
15482    if (cur_defaultdpc < 0) {
15483       ast_log(LOG_ERROR, "Unspecified defaultdpc!\n");
15484       return -1;
15485    }
15486    if (cur_networkindicator < 0) {
15487       ast_log(LOG_ERROR, "Invalid networkindicator!\n");
15488       return -1;
15489    }
15490    link = ss7_resolve_linkset(cur_linkset);
15491    if (!link) {
15492       ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
15493       return -1;
15494    }
15495    if (link->ss7.numsigchans >= SIG_SS7_NUM_DCHANS) {
15496       ast_log(LOG_ERROR, "Too many sigchans on linkset %d\n", cur_linkset);
15497       return -1;
15498    }
15499 
15500    curfd = link->ss7.numsigchans;
15501 
15502    /* Open signaling channel */
15503    link->ss7.fds[curfd] = open("/dev/dahdi/channel", O_RDWR, 0600);
15504    if (link->ss7.fds[curfd] < 0) {
15505       ast_log(LOG_ERROR, "Unable to open SS7 sigchan %d (%s)\n", sigchan,
15506          strerror(errno));
15507       return -1;
15508    }
15509    if (ioctl(link->ss7.fds[curfd], DAHDI_SPECIFY, &sigchan) == -1) {
15510       dahdi_close_ss7_fd(link, curfd);
15511       ast_log(LOG_ERROR, "Unable to specify SS7 sigchan %d (%s)\n", sigchan,
15512          strerror(errno));
15513       return -1;
15514    }
15515 
15516    /* Get signaling channel parameters */
15517    memset(&params, 0, sizeof(params));
15518    res = ioctl(link->ss7.fds[curfd], DAHDI_GET_PARAMS, &params);
15519    if (res) {
15520       dahdi_close_ss7_fd(link, curfd);
15521       ast_log(LOG_ERROR, "Unable to get parameters for sigchan %d (%s)\n", sigchan,
15522          strerror(errno));
15523       return -1;
15524    }
15525    if (params.sigtype != DAHDI_SIG_HDLCFCS
15526       && params.sigtype != DAHDI_SIG_HARDHDLC
15527       && params.sigtype != DAHDI_SIG_MTP2) {
15528       dahdi_close_ss7_fd(link, curfd);
15529       ast_log(LOG_ERROR, "sigchan %d is not in HDLC/FCS mode.\n", sigchan);
15530       return -1;
15531    }
15532 
15533    /* Set signaling channel buffer policy. */
15534    memset(&bi, 0, sizeof(bi));
15535    bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
15536    bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
15537    bi.numbufs = 32;
15538    bi.bufsize = 512;
15539    if (ioctl(link->ss7.fds[curfd], DAHDI_SET_BUFINFO, &bi)) {
15540       ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n",
15541          sigchan, strerror(errno));
15542       dahdi_close_ss7_fd(link, curfd);
15543       return -1;
15544    }
15545 
15546    /* Get current signaling channel alarm status. */
15547    memset(&si, 0, sizeof(si));
15548    res = ioctl(link->ss7.fds[curfd], DAHDI_SPANSTAT, &si);
15549    if (res) {
15550       dahdi_close_ss7_fd(link, curfd);
15551       ast_log(LOG_ERROR, "Unable to get span state for sigchan %d (%s)\n", sigchan,
15552          strerror(errno));
15553    }
15554 
15555    res = sig_ss7_add_sigchan(&link->ss7, curfd, cur_ss7type,
15556       (params.sigtype == DAHDI_SIG_MTP2)
15557          ? SS7_TRANSPORT_DAHDIMTP2
15558          : SS7_TRANSPORT_DAHDIDCHAN,
15559       si.alarms, cur_networkindicator, cur_pointcode, cur_adjpointcode);
15560    if (res) {
15561       dahdi_close_ss7_fd(link, curfd);
15562       return -1;
15563    }
15564 
15565    ++link->ss7.numsigchans;
15566 
15567    return 0;
15568 }
15569 #endif   /* defined(HAVE_SS7) */
15570 
15571 #if defined(HAVE_SS7)
15572 static char *handle_ss7_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15573 {
15574    int span;
15575    switch (cmd) {
15576    case CLI_INIT:
15577       e->command = "ss7 set debug {on|off} linkset";
15578       e->usage =
15579          "Usage: ss7 set debug {on|off} linkset <linkset>\n"
15580          "       Enables debugging on a given SS7 linkset\n";
15581       return NULL;
15582    case CLI_GENERATE:
15583       return NULL;
15584    }
15585    if (a->argc < 6)
15586       return CLI_SHOWUSAGE;
15587    span = atoi(a->argv[5]);
15588    if ((span < 1) || (span > NUM_SPANS)) {
15589       ast_cli(a->fd, "Invalid linkset %s.  Should be a number from %d to %d\n", a->argv[5], 1, NUM_SPANS);
15590       return CLI_SUCCESS;
15591    }
15592    if (!linksets[span-1].ss7.ss7) {
15593       ast_cli(a->fd, "No SS7 running on linkset %d\n", span);
15594    } else {
15595       if (!strcasecmp(a->argv[3], "on")) {
15596          ss7_set_debug(linksets[span-1].ss7.ss7, SIG_SS7_DEBUG);
15597          ast_cli(a->fd, "Enabled debugging on linkset %d\n", span);
15598       } else {
15599          ss7_set_debug(linksets[span-1].ss7.ss7, 0);
15600          ast_cli(a->fd, "Disabled debugging on linkset %d\n", span);
15601       }
15602    }
15603 
15604    return CLI_SUCCESS;
15605 }
15606 #endif   /* defined(HAVE_SS7) */
15607 
15608 #if defined(HAVE_SS7)
15609 static char *handle_ss7_block_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15610 {
15611    int linkset, cic;
15612    int blocked = -1, i;
15613    switch (cmd) {
15614    case CLI_INIT:
15615       e->command = "ss7 block cic";
15616       e->usage =
15617          "Usage: ss7 block cic <linkset> <CIC>\n"
15618          "       Sends a remote blocking request for the given CIC on the specified linkset\n";
15619       return NULL;
15620    case CLI_GENERATE:
15621       return NULL;
15622    }
15623    if (a->argc == 5)
15624       linkset = atoi(a->argv[3]);
15625    else
15626       return CLI_SHOWUSAGE;
15627 
15628    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15629       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15630       return CLI_SUCCESS;
15631    }
15632 
15633    if (!linksets[linkset-1].ss7.ss7) {
15634       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15635       return CLI_SUCCESS;
15636    }
15637 
15638    cic = atoi(a->argv[4]);
15639 
15640    if (cic < 1) {
15641       ast_cli(a->fd, "Invalid CIC specified!\n");
15642       return CLI_SUCCESS;
15643    }
15644 
15645    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
15646       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
15647          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
15648          if (!blocked) {
15649             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
15650             isup_blo(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
15651             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
15652          }
15653       }
15654    }
15655 
15656    if (blocked < 0) {
15657       ast_cli(a->fd, "Invalid CIC specified!\n");
15658       return CLI_SUCCESS;
15659    }
15660 
15661    if (!blocked)
15662       ast_cli(a->fd, "Sent blocking request for linkset %d on CIC %d\n", linkset, cic);
15663    else
15664       ast_cli(a->fd, "CIC %d already locally blocked\n", cic);
15665 
15666    /* Break poll on the linkset so it sends our messages */
15667    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
15668 
15669    return CLI_SUCCESS;
15670 }
15671 #endif   /* defined(HAVE_SS7) */
15672 
15673 #if defined(HAVE_SS7)
15674 static char *handle_ss7_block_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15675 {
15676    int linkset;
15677    int i;
15678    switch (cmd) {
15679    case CLI_INIT:
15680       e->command = "ss7 block linkset";
15681       e->usage =
15682          "Usage: ss7 block linkset <linkset number>\n"
15683          "       Sends a remote blocking request for all CICs on the given linkset\n";
15684       return NULL;
15685    case CLI_GENERATE:
15686       return NULL;
15687    }
15688    if (a->argc == 4)
15689       linkset = atoi(a->argv[3]);
15690    else
15691       return CLI_SHOWUSAGE;
15692 
15693    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15694       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15695       return CLI_SUCCESS;
15696    }
15697 
15698    if (!linksets[linkset-1].ss7.ss7) {
15699       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15700       return CLI_SUCCESS;
15701    }
15702 
15703    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
15704       ast_cli(a->fd, "Sending remote blocking request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
15705       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
15706       isup_blo(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
15707       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
15708    }
15709 
15710    /* Break poll on the linkset so it sends our messages */
15711    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
15712 
15713    return CLI_SUCCESS;
15714 }
15715 #endif   /* defined(HAVE_SS7) */
15716 
15717 #if defined(HAVE_SS7)
15718 static char *handle_ss7_unblock_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15719 {
15720    int linkset, cic;
15721    int i, blocked = -1;
15722    switch (cmd) {
15723    case CLI_INIT:
15724       e->command = "ss7 unblock cic";
15725       e->usage =
15726          "Usage: ss7 unblock cic <linkset> <CIC>\n"
15727          "       Sends a remote unblocking request for the given CIC on the specified linkset\n";
15728       return NULL;
15729    case CLI_GENERATE:
15730       return NULL;
15731    }
15732 
15733    if (a->argc == 5)
15734       linkset = atoi(a->argv[3]);
15735    else
15736       return CLI_SHOWUSAGE;
15737 
15738    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15739       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15740       return CLI_SUCCESS;
15741    }
15742 
15743    if (!linksets[linkset-1].ss7.ss7) {
15744       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15745       return CLI_SUCCESS;
15746    }
15747 
15748    cic = atoi(a->argv[4]);
15749 
15750    if (cic < 1) {
15751       ast_cli(a->fd, "Invalid CIC specified!\n");
15752       return CLI_SUCCESS;
15753    }
15754 
15755    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
15756       if (linksets[linkset-1].ss7.pvts[i]->cic == cic) {
15757          blocked = linksets[linkset-1].ss7.pvts[i]->locallyblocked;
15758          if (blocked) {
15759             ast_mutex_lock(&linksets[linkset-1].ss7.lock);
15760             isup_ubl(linksets[linkset-1].ss7.ss7, cic, linksets[linkset-1].ss7.pvts[i]->dpc);
15761             ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
15762          }
15763       }
15764    }
15765 
15766    if (blocked > 0)
15767       ast_cli(a->fd, "Sent unblocking request for linkset %d on CIC %d\n", linkset, cic);
15768 
15769    /* Break poll on the linkset so it sends our messages */
15770    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
15771 
15772    return CLI_SUCCESS;
15773 }
15774 #endif   /* defined(HAVE_SS7) */
15775 
15776 #if defined(HAVE_SS7)
15777 static char *handle_ss7_unblock_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15778 {
15779    int linkset;
15780    int i;
15781    switch (cmd) {
15782    case CLI_INIT:
15783       e->command = "ss7 unblock linkset";
15784       e->usage =
15785          "Usage: ss7 unblock linkset <linkset number>\n"
15786          "       Sends a remote unblocking request for all CICs on the specified linkset\n";
15787       return NULL;
15788    case CLI_GENERATE:
15789       return NULL;
15790    }
15791 
15792    if (a->argc == 4)
15793       linkset = atoi(a->argv[3]);
15794    else
15795       return CLI_SHOWUSAGE;
15796 
15797    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15798       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15799       return CLI_SUCCESS;
15800    }
15801 
15802    if (!linksets[linkset-1].ss7.ss7) {
15803       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15804       return CLI_SUCCESS;
15805    }
15806 
15807    for (i = 0; i < linksets[linkset-1].ss7.numchans; i++) {
15808       ast_cli(a->fd, "Sending remote unblock request on CIC %d\n", linksets[linkset-1].ss7.pvts[i]->cic);
15809       ast_mutex_lock(&linksets[linkset-1].ss7.lock);
15810       isup_ubl(linksets[linkset-1].ss7.ss7, linksets[linkset-1].ss7.pvts[i]->cic, linksets[linkset-1].ss7.pvts[i]->dpc);
15811       ast_mutex_unlock(&linksets[linkset-1].ss7.lock);
15812    }
15813 
15814    /* Break poll on the linkset so it sends our messages */
15815    pthread_kill(linksets[linkset-1].ss7.master, SIGURG);
15816 
15817    return CLI_SUCCESS;
15818 }
15819 #endif   /* defined(HAVE_SS7) */
15820 
15821 #if defined(HAVE_SS7)
15822 static char *handle_ss7_show_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15823 {
15824    int linkset;
15825    struct sig_ss7_linkset *ss7;
15826    switch (cmd) {
15827    case CLI_INIT:
15828       e->command = "ss7 show linkset";
15829       e->usage =
15830          "Usage: ss7 show linkset <span>\n"
15831          "       Shows the status of an SS7 linkset.\n";
15832       return NULL;
15833    case CLI_GENERATE:
15834       return NULL;
15835    }
15836 
15837    if (a->argc < 4)
15838       return CLI_SHOWUSAGE;
15839    linkset = atoi(a->argv[3]);
15840    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15841       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15842       return CLI_SUCCESS;
15843    }
15844    ss7 = &linksets[linkset - 1].ss7;
15845    if (!ss7->ss7) {
15846       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15847       return CLI_SUCCESS;
15848    }
15849 
15850    ast_cli(a->fd, "SS7 linkset %d status: %s\n", linkset, (ss7->state == LINKSET_STATE_UP) ? "Up" : "Down");
15851 
15852    return CLI_SUCCESS;
15853 }
15854 #endif   /* defined(HAVE_SS7) */
15855 
15856 #if defined(HAVE_SS7)
15857 static char *handle_ss7_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15858 {
15859    switch (cmd) {
15860    case CLI_INIT:
15861       e->command = "ss7 show version";
15862       e->usage =
15863          "Usage: ss7 show version\n"
15864          "  Show the libss7 version\n";
15865       return NULL;
15866    case CLI_GENERATE:
15867       return NULL;
15868    }
15869 
15870    ast_cli(a->fd, "libss7 version: %s\n", ss7_get_version());
15871 
15872    return CLI_SUCCESS;
15873 }
15874 #endif   /* defined(HAVE_SS7) */
15875 
15876 #if defined(HAVE_SS7)
15877 static struct ast_cli_entry dahdi_ss7_cli[] = {
15878    AST_CLI_DEFINE(handle_ss7_debug, "Enables SS7 debugging on a linkset"),
15879    AST_CLI_DEFINE(handle_ss7_block_cic, "Blocks the given CIC"),
15880    AST_CLI_DEFINE(handle_ss7_unblock_cic, "Unblocks the given CIC"),
15881    AST_CLI_DEFINE(handle_ss7_block_linkset, "Blocks all CICs on a linkset"),
15882    AST_CLI_DEFINE(handle_ss7_unblock_linkset, "Unblocks all CICs on a linkset"),
15883    AST_CLI_DEFINE(handle_ss7_show_linkset, "Shows the status of a linkset"),
15884    AST_CLI_DEFINE(handle_ss7_version, "Displays libss7 version"),
15885 };
15886 #endif   /* defined(HAVE_SS7) */
15887 
15888 #if defined(HAVE_PRI)
15889 #if defined(HAVE_PRI_CCSS)
15890 /*!
15891  * \internal
15892  * \brief CC agent initialization.
15893  * \since 1.8
15894  *
15895  * \param agent CC core agent control.
15896  * \param chan Original channel the agent will attempt to recall.
15897  *
15898  * \details
15899  * This callback is called when the CC core is initialized.  Agents should allocate
15900  * any private data necessary for the call and assign it to the private_data
15901  * on the agent.  Additionally, if any ast_cc_agent_flags are pertinent to the
15902  * specific agent type, they should be set in this function as well.
15903  *
15904  * \retval 0 on success.
15905  * \retval -1 on error.
15906  */
15907 static int dahdi_pri_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
15908 {
15909    struct dahdi_pvt *pvt;
15910    struct sig_pri_chan *pvt_chan;
15911    int res;
15912 
15913    ast_assert(!strcmp(chan->tech->type, "DAHDI"));
15914 
15915    pvt = chan->tech_pvt;
15916    if (dahdi_sig_pri_lib_handles(pvt->sig)) {
15917       pvt_chan = pvt->sig_pvt;
15918    } else {
15919       pvt_chan = NULL;
15920    }
15921    if (!pvt_chan) {
15922       return -1;
15923    }
15924 
15925    ast_module_ref(ast_module_info->self);
15926 
15927    res = sig_pri_cc_agent_init(agent, pvt_chan);
15928    if (res) {
15929       ast_module_unref(ast_module_info->self);
15930    }
15931    return res;
15932 }
15933 #endif   /* defined(HAVE_PRI_CCSS) */
15934 #endif   /* defined(HAVE_PRI) */
15935 
15936 #if defined(HAVE_PRI)
15937 #if defined(HAVE_PRI_CCSS)
15938 /*!
15939  * \internal
15940  * \brief Destroy private data on the agent.
15941  * \since 1.8
15942  *
15943  * \param agent CC core agent control.
15944  *
15945  * \details
15946  * The core will call this function upon completion
15947  * or failure of CC.
15948  *
15949  * \return Nothing
15950  */
15951 static void dahdi_pri_cc_agent_destructor(struct ast_cc_agent *agent)
15952 {
15953    sig_pri_cc_agent_destructor(agent);
15954 
15955    ast_module_unref(ast_module_info->self);
15956 }
15957 #endif   /* defined(HAVE_PRI_CCSS) */
15958 #endif   /* defined(HAVE_PRI) */
15959 
15960 #if defined(HAVE_PRI)
15961 #if defined(HAVE_PRI_CCSS)
15962 static struct ast_cc_agent_callbacks dahdi_pri_cc_agent_callbacks = {
15963    .type = dahdi_pri_cc_type,
15964    .init = dahdi_pri_cc_agent_init,
15965    .start_offer_timer = sig_pri_cc_agent_start_offer_timer,
15966    .stop_offer_timer = sig_pri_cc_agent_stop_offer_timer,
15967    .ack = sig_pri_cc_agent_req_ack,
15968    .status_request = sig_pri_cc_agent_status_req,
15969    .stop_ringing = sig_pri_cc_agent_stop_ringing,
15970    .party_b_free = sig_pri_cc_agent_party_b_free,
15971    .start_monitoring = sig_pri_cc_agent_start_monitoring,
15972    .callee_available = sig_pri_cc_agent_callee_available,
15973    .destructor = dahdi_pri_cc_agent_destructor,
15974 };
15975 #endif   /* defined(HAVE_PRI_CCSS) */
15976 #endif   /* defined(HAVE_PRI) */
15977 
15978 #if defined(HAVE_PRI)
15979 #if defined(HAVE_PRI_CCSS)
15980 static struct ast_cc_monitor_callbacks dahdi_pri_cc_monitor_callbacks = {
15981    .type = dahdi_pri_cc_type,
15982    .request_cc = sig_pri_cc_monitor_req_cc,
15983    .suspend = sig_pri_cc_monitor_suspend,
15984    .unsuspend = sig_pri_cc_monitor_unsuspend,
15985    .status_response = sig_pri_cc_monitor_status_rsp,
15986    .cancel_available_timer = sig_pri_cc_monitor_cancel_available_timer,
15987    .destructor = sig_pri_cc_monitor_destructor,
15988 };
15989 #endif   /* defined(HAVE_PRI_CCSS) */
15990 #endif   /* defined(HAVE_PRI) */
15991 
15992 static int __unload_module(void)
15993 {
15994    struct dahdi_pvt *p;
15995 #if defined(HAVE_PRI) || defined(HAVE_SS7)
15996    int i, j;
15997 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
15998 
15999 #ifdef HAVE_PRI
16000    for (i = 0; i < NUM_SPANS; i++) {
16001       if (pris[i].pri.master != AST_PTHREADT_NULL)
16002          pthread_cancel(pris[i].pri.master);
16003    }
16004    ast_cli_unregister_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
16005    ast_unregister_application(dahdi_send_keypad_facility_app);
16006 #ifdef HAVE_PRI_PROG_W_CAUSE
16007    ast_unregister_application(dahdi_send_callrerouting_facility_app);
16008 #endif
16009 #endif
16010 #if defined(HAVE_SS7)
16011    for (i = 0; i < NUM_SPANS; i++) {
16012       if (linksets[i].ss7.master != AST_PTHREADT_NULL)
16013          pthread_cancel(linksets[i].ss7.master);
16014       }
16015    ast_cli_unregister_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
16016 #endif   /* defined(HAVE_SS7) */
16017 #if defined(HAVE_OPENR2)
16018    dahdi_r2_destroy_links();
16019    ast_cli_unregister_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
16020    ast_unregister_application(dahdi_accept_r2_call_app);
16021 #endif
16022 
16023    ast_cli_unregister_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
16024    ast_manager_unregister("DAHDIDialOffhook");
16025    ast_manager_unregister("DAHDIHangup");
16026    ast_manager_unregister("DAHDITransfer");
16027    ast_manager_unregister("DAHDIDNDoff");
16028    ast_manager_unregister("DAHDIDNDon");
16029    ast_manager_unregister("DAHDIShowChannels");
16030    ast_manager_unregister("DAHDIRestart");
16031    ast_data_unregister(NULL);
16032    ast_channel_unregister(&dahdi_tech);
16033 
16034    /* Hangup all interfaces if they have an owner */
16035    ast_mutex_lock(&iflock);
16036    for (p = iflist; p; p = p->next) {
16037       if (p->owner)
16038          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16039    }
16040    ast_mutex_unlock(&iflock);
16041 
16042    ast_mutex_lock(&monlock);
16043    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
16044       pthread_cancel(monitor_thread);
16045       pthread_kill(monitor_thread, SIGURG);
16046       pthread_join(monitor_thread, NULL);
16047    }
16048    monitor_thread = AST_PTHREADT_STOP;
16049    ast_mutex_unlock(&monlock);
16050 
16051    destroy_all_channels();
16052 
16053 #if defined(HAVE_PRI)
16054    for (i = 0; i < NUM_SPANS; i++) {
16055       if (pris[i].pri.master && (pris[i].pri.master != AST_PTHREADT_NULL))
16056          pthread_join(pris[i].pri.master, NULL);
16057       for (j = 0; j < SIG_PRI_NUM_DCHANS; j++) {
16058          dahdi_close_pri_fd(&(pris[i]), j);
16059       }
16060       sig_pri_stop_pri(&pris[i].pri);
16061    }
16062 #if defined(HAVE_PRI_CCSS)
16063    ast_cc_agent_unregister(&dahdi_pri_cc_agent_callbacks);
16064    ast_cc_monitor_unregister(&dahdi_pri_cc_monitor_callbacks);
16065 #endif   /* defined(HAVE_PRI_CCSS) */
16066    sig_pri_unload();
16067 #endif
16068 
16069 #if defined(HAVE_SS7)
16070    for (i = 0; i < NUM_SPANS; i++) {
16071       if (linksets[i].ss7.master && (linksets[i].ss7.master != AST_PTHREADT_NULL))
16072          pthread_join(linksets[i].ss7.master, NULL);
16073       for (j = 0; j < SIG_SS7_NUM_DCHANS; j++) {
16074          dahdi_close_ss7_fd(&(linksets[i]), j);
16075       }
16076    }
16077 #endif   /* defined(HAVE_SS7) */
16078    ast_cond_destroy(&ss_thread_complete);
16079    return 0;
16080 }
16081 
16082 static int unload_module(void)
16083 {
16084 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16085    int y;
16086 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
16087 #ifdef HAVE_PRI
16088    for (y = 0; y < NUM_SPANS; y++)
16089       ast_mutex_destroy(&pris[y].pri.lock);
16090 #endif
16091 #if defined(HAVE_SS7)
16092    for (y = 0; y < NUM_SPANS; y++)
16093       ast_mutex_destroy(&linksets[y].ss7.lock);
16094 #endif   /* defined(HAVE_SS7) */
16095    return __unload_module();
16096 }
16097 
16098 static void string_replace(char *str, int char1, int char2)
16099 {
16100    for (; *str; str++) {
16101       if (*str == char1) {
16102          *str = char2;
16103       }
16104    }
16105 }
16106 
16107 static char *parse_spanchan(char *chanstr, char **subdir)
16108 {
16109    char *p;
16110 
16111    if ((p = strrchr(chanstr, '!')) == NULL) {
16112       *subdir = NULL;
16113       return chanstr;
16114    }
16115    *p++ = '\0';
16116    string_replace(chanstr, '!', '/');
16117    *subdir = chanstr;
16118    return p;
16119 }
16120 
16121 static int build_channels(struct dahdi_chan_conf *conf, const char *value, int reload, int lineno, int *found_pseudo)
16122 {
16123    char *c, *chan;
16124    char *subdir;
16125    int x, start, finish;
16126    struct dahdi_pvt *tmp;
16127 
16128    if ((reload == 0) && (conf->chan.sig < 0) && !conf->is_sig_auto) {
16129       ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
16130       return -1;
16131    }
16132 
16133    c = ast_strdupa(value);
16134    c = parse_spanchan(c, &subdir);
16135 
16136    while ((chan = strsep(&c, ","))) {
16137       if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
16138          /* Range */
16139       } else if (sscanf(chan, "%30d", &start)) {
16140          /* Just one */
16141          finish = start;
16142       } else if (!strcasecmp(chan, "pseudo")) {
16143          finish = start = CHAN_PSEUDO;
16144          if (found_pseudo)
16145             *found_pseudo = 1;
16146       } else {
16147          ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
16148          return -1;
16149       }
16150       if (finish < start) {
16151          ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
16152          x = finish;
16153          finish = start;
16154          start = x;
16155       }
16156 
16157       for (x = start; x <= finish; x++) {
16158          char fn[PATH_MAX];
16159          int real_channel = x;
16160 
16161          if (!ast_strlen_zero(subdir)) {
16162             real_channel = device2chan(subdir, x, fn, sizeof(fn));
16163             if (real_channel < 0) {
16164                if (conf->ignore_failed_channels) {
16165                   ast_log(LOG_WARNING, "Failed configuring %s!%d, (got %d). But moving on to others.\n",
16166                         subdir, x, real_channel);
16167                   continue;
16168                } else {
16169                   ast_log(LOG_ERROR, "Failed configuring %s!%d, (got %d).\n",
16170                         subdir, x, real_channel);
16171                   return -1;
16172                }
16173             }
16174          }
16175          tmp = mkintf(real_channel, conf, reload);
16176 
16177          if (tmp) {
16178             ast_verb(3, "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", real_channel, sig2str(tmp->sig));
16179          } else {
16180             ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
16181                   (reload == 1) ? "reconfigure" : "register", value);
16182             return -1;
16183          }
16184       }
16185    }
16186 
16187    return 0;
16188 }
16189 
16190 /** The length of the parameters list of 'dahdichan'.
16191  * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
16192 #define MAX_CHANLIST_LEN 80
16193 
16194 static void process_echocancel(struct dahdi_chan_conf *confp, const char *data, unsigned int line)
16195 {
16196    char *parse = ast_strdupa(data);
16197    char *params[DAHDI_MAX_ECHOCANPARAMS + 1];
16198    unsigned int param_count;
16199    unsigned int x;
16200 
16201    if (!(param_count = ast_app_separate_args(parse, ',', params, ARRAY_LEN(params))))
16202       return;
16203 
16204    memset(&confp->chan.echocancel, 0, sizeof(confp->chan.echocancel));
16205 
16206    /* first parameter is tap length, process it here */
16207 
16208    x = ast_strlen_zero(params[0]) ? 0 : atoi(params[0]);
16209 
16210    if ((x == 32) || (x == 64) || (x == 128) || (x == 256) || (x == 512) || (x == 1024))
16211       confp->chan.echocancel.head.tap_length = x;
16212    else if ((confp->chan.echocancel.head.tap_length = ast_true(params[0])))
16213       confp->chan.echocancel.head.tap_length = 128;
16214 
16215    /* now process any remaining parameters */
16216 
16217    for (x = 1; x < param_count; x++) {
16218       struct {
16219          char *name;
16220          char *value;
16221       } param;
16222 
16223       if (ast_app_separate_args(params[x], '=', (char **) &param, 2) < 1) {
16224          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, params[x]);
16225          continue;
16226       }
16227 
16228       if (ast_strlen_zero(param.name) || (strlen(param.name) > sizeof(confp->chan.echocancel.params[0].name)-1)) {
16229          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, param.name);
16230          continue;
16231       }
16232 
16233       strcpy(confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].name, param.name);
16234 
16235       if (param.value) {
16236          if (sscanf(param.value, "%30d", &confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].value) != 1) {
16237             ast_log(LOG_WARNING, "Invalid echocancel parameter value supplied at line %d: '%s'\n", line, param.value);
16238             continue;
16239          }
16240       }
16241       confp->chan.echocancel.head.param_count++;
16242    }
16243 }
16244 
16245 /*! process_dahdi() - ignore keyword 'channel' and similar */
16246 #define PROC_DAHDI_OPT_NOCHAN  (1 << 0)
16247 /*! process_dahdi() - No warnings on non-existing cofiguration keywords */
16248 #define PROC_DAHDI_OPT_NOWARN  (1 << 1)
16249 
16250 static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct ast_variable *v, int reload, int options)
16251 {
16252    struct dahdi_pvt *tmp;
16253    int y;
16254    int found_pseudo = 0;
16255    char dahdichan[MAX_CHANLIST_LEN] = {};
16256 
16257    for (; v; v = v->next) {
16258       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16259          continue;
16260 
16261       /* must have parkinglot in confp before build_channels is called */
16262       if (!strcasecmp(v->name, "parkinglot")) {
16263          ast_copy_string(confp->chan.parkinglot, v->value, sizeof(confp->chan.parkinglot));
16264       }
16265 
16266       /* Create the interface list */
16267       if (!strcasecmp(v->name, "channel") || !strcasecmp(v->name, "channels")) {
16268          if (options & PROC_DAHDI_OPT_NOCHAN) {
16269             ast_log(LOG_WARNING, "Channel '%s' ignored.\n", v->value);
16270             continue;
16271          }
16272          if (build_channels(confp, v->value, reload, v->lineno, &found_pseudo)) {
16273             if (confp->ignore_failed_channels) {
16274                ast_log(LOG_WARNING, "Channel '%s' failure ignored: ignore_failed_channels.\n", v->value);
16275                continue;
16276             } else {
16277                return -1;
16278             }
16279          }
16280          ast_log(LOG_DEBUG, "Channel '%s' configured.\n", v->value);
16281       } else if (!strcasecmp(v->name, "ignore_failed_channels")) {
16282          confp->ignore_failed_channels = ast_true(v->value);
16283       } else if (!strcasecmp(v->name, "buffers")) {
16284          if (parse_buffers_policy(v->value, &confp->chan.buf_no, &confp->chan.buf_policy)) {
16285             ast_log(LOG_WARNING, "Using default buffer policy.\n");
16286             confp->chan.buf_no = numbufs;
16287             confp->chan.buf_policy = DAHDI_POLICY_IMMEDIATE;
16288          }
16289       } else if (!strcasecmp(v->name, "faxbuffers")) {
16290          if (!parse_buffers_policy(v->value, &confp->chan.faxbuf_no, &confp->chan.faxbuf_policy)) {
16291             confp->chan.usefaxbuffers = 1;
16292          }
16293       } else if (!strcasecmp(v->name, "dahdichan")) {
16294          ast_copy_string(dahdichan, v->value, sizeof(dahdichan));
16295       } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
16296          usedistinctiveringdetection = ast_true(v->value);
16297       } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
16298          distinctiveringaftercid = ast_true(v->value);
16299       } else if (!strcasecmp(v->name, "dring1context")) {
16300          ast_copy_string(confp->chan.drings.ringContext[0].contextData,v->value,sizeof(confp->chan.drings.ringContext[0].contextData));
16301       } else if (!strcasecmp(v->name, "dring2context")) {
16302          ast_copy_string(confp->chan.drings.ringContext[1].contextData,v->value,sizeof(confp->chan.drings.ringContext[1].contextData));
16303       } else if (!strcasecmp(v->name, "dring3context")) {
16304          ast_copy_string(confp->chan.drings.ringContext[2].contextData,v->value,sizeof(confp->chan.drings.ringContext[2].contextData));
16305       } else if (!strcasecmp(v->name, "dring1range")) {
16306          confp->chan.drings.ringnum[0].range = atoi(v->value);
16307       } else if (!strcasecmp(v->name, "dring2range")) {
16308          confp->chan.drings.ringnum[1].range = atoi(v->value);
16309       } else if (!strcasecmp(v->name, "dring3range")) {
16310          confp->chan.drings.ringnum[2].range = atoi(v->value);
16311       } else if (!strcasecmp(v->name, "dring1")) {
16312          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]);
16313       } else if (!strcasecmp(v->name, "dring2")) {
16314          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]);
16315       } else if (!strcasecmp(v->name, "dring3")) {
16316          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]);
16317       } else if (!strcasecmp(v->name, "usecallerid")) {
16318          confp->chan.use_callerid = ast_true(v->value);
16319       } else if (!strcasecmp(v->name, "cidsignalling")) {
16320          if (!strcasecmp(v->value, "bell"))
16321             confp->chan.cid_signalling = CID_SIG_BELL;
16322          else if (!strcasecmp(v->value, "v23"))
16323             confp->chan.cid_signalling = CID_SIG_V23;
16324          else if (!strcasecmp(v->value, "dtmf"))
16325             confp->chan.cid_signalling = CID_SIG_DTMF;
16326          else if (!strcasecmp(v->value, "smdi"))
16327             confp->chan.cid_signalling = CID_SIG_SMDI;
16328          else if (!strcasecmp(v->value, "v23_jp"))
16329             confp->chan.cid_signalling = CID_SIG_V23_JP;
16330          else if (ast_true(v->value))
16331             confp->chan.cid_signalling = CID_SIG_BELL;
16332       } else if (!strcasecmp(v->name, "cidstart")) {
16333          if (!strcasecmp(v->value, "ring"))
16334             confp->chan.cid_start = CID_START_RING;
16335          else if (!strcasecmp(v->value, "polarity_in"))
16336             confp->chan.cid_start = CID_START_POLARITY_IN;
16337          else if (!strcasecmp(v->value, "polarity"))
16338             confp->chan.cid_start = CID_START_POLARITY;
16339          else if (!strcasecmp(v->value, "dtmf"))
16340             confp->chan.cid_start = CID_START_DTMF_NOALERT;
16341          else if (ast_true(v->value))
16342             confp->chan.cid_start = CID_START_RING;
16343       } else if (!strcasecmp(v->name, "threewaycalling")) {
16344          confp->chan.threewaycalling = ast_true(v->value);
16345       } else if (!strcasecmp(v->name, "cancallforward")) {
16346          confp->chan.cancallforward = ast_true(v->value);
16347       } else if (!strcasecmp(v->name, "relaxdtmf")) {
16348          if (ast_true(v->value))
16349             confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
16350          else
16351             confp->chan.dtmfrelax = 0;
16352       } else if (!strcasecmp(v->name, "mailbox")) {
16353          ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
16354       } else if (!strcasecmp(v->name, "hasvoicemail")) {
16355          if (ast_true(v->value) && ast_strlen_zero(confp->chan.mailbox)) {
16356             ast_copy_string(confp->chan.mailbox, cat, sizeof(confp->chan.mailbox));
16357          }
16358       } else if (!strcasecmp(v->name, "adsi")) {
16359          confp->chan.adsi = ast_true(v->value);
16360       } else if (!strcasecmp(v->name, "usesmdi")) {
16361          confp->chan.use_smdi = ast_true(v->value);
16362       } else if (!strcasecmp(v->name, "smdiport")) {
16363          ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
16364       } else if (!strcasecmp(v->name, "transfer")) {
16365          confp->chan.transfer = ast_true(v->value);
16366       } else if (!strcasecmp(v->name, "canpark")) {
16367          confp->chan.canpark = ast_true(v->value);
16368       } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
16369          confp->chan.echocanbridged = ast_true(v->value);
16370       } else if (!strcasecmp(v->name, "busydetect")) {
16371          confp->chan.busydetect = ast_true(v->value);
16372       } else if (!strcasecmp(v->name, "busycount")) {
16373          confp->chan.busycount = atoi(v->value);
16374       } else if (!strcasecmp(v->name, "busypattern")) {
16375          if (sscanf(v->value, "%30d,%30d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
16376             ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength at line %d.\n", v->lineno);
16377          }
16378       } else if (!strcasecmp(v->name, "callprogress")) {
16379          confp->chan.callprogress &= ~CALLPROGRESS_PROGRESS;
16380          if (ast_true(v->value))
16381             confp->chan.callprogress |= CALLPROGRESS_PROGRESS;
16382       } else if (!strcasecmp(v->name, "waitfordialtone")) {
16383          confp->chan.waitfordialtone = atoi(v->value);
16384       } else if (!strcasecmp(v->name, "faxdetect")) {
16385          confp->chan.callprogress &= ~CALLPROGRESS_FAX;
16386          if (!strcasecmp(v->value, "incoming")) {
16387             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING;
16388          } else if (!strcasecmp(v->value, "outgoing")) {
16389             confp->chan.callprogress |= CALLPROGRESS_FAX_OUTGOING;
16390          } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
16391             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING;
16392       } else if (!strcasecmp(v->name, "echocancel")) {
16393          process_echocancel(confp, v->value, v->lineno);
16394       } else if (!strcasecmp(v->name, "echotraining")) {
16395          if (sscanf(v->value, "%30d", &y) == 1) {
16396             if ((y < 10) || (y > 4000)) {
16397                ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d.\n", v->lineno);
16398             } else {
16399                confp->chan.echotraining = y;
16400             }
16401          } else if (ast_true(v->value)) {
16402             confp->chan.echotraining = 400;
16403          } else
16404             confp->chan.echotraining = 0;
16405       } else if (!strcasecmp(v->name, "hidecallerid")) {
16406          confp->chan.hidecallerid = ast_true(v->value);
16407       } else if (!strcasecmp(v->name, "hidecalleridname")) {
16408          confp->chan.hidecalleridname = ast_true(v->value);
16409       } else if (!strcasecmp(v->name, "pulsedial")) {
16410          confp->chan.pulse = ast_true(v->value);
16411       } else if (!strcasecmp(v->name, "callreturn")) {
16412          confp->chan.callreturn = ast_true(v->value);
16413       } else if (!strcasecmp(v->name, "callwaiting")) {
16414          confp->chan.callwaiting = ast_true(v->value);
16415       } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
16416          confp->chan.callwaitingcallerid = ast_true(v->value);
16417       } else if (!strcasecmp(v->name, "context")) {
16418          ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
16419       } else if (!strcasecmp(v->name, "language")) {
16420          ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
16421       } else if (!strcasecmp(v->name, "progzone")) {
16422          ast_copy_string(progzone, v->value, sizeof(progzone));
16423       } else if (!strcasecmp(v->name, "mohinterpret")
16424          ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
16425          ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
16426       } else if (!strcasecmp(v->name, "mohsuggest")) {
16427          ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
16428       } else if (!strcasecmp(v->name, "parkinglot")) {
16429          ast_copy_string(parkinglot, v->value, sizeof(parkinglot));
16430       } else if (!strcasecmp(v->name, "stripmsd")) {
16431          ast_log(LOG_NOTICE, "Configuration option \"%s\" has been deprecated. Please use dialplan instead\n", v->name);
16432          confp->chan.stripmsd = atoi(v->value);
16433       } else if (!strcasecmp(v->name, "jitterbuffers")) {
16434          numbufs = atoi(v->value);
16435       } else if (!strcasecmp(v->name, "group")) {
16436          confp->chan.group = ast_get_group(v->value);
16437       } else if (!strcasecmp(v->name, "callgroup")) {
16438          if (!strcasecmp(v->value, "none"))
16439             confp->chan.callgroup = 0;
16440          else
16441             confp->chan.callgroup = ast_get_group(v->value);
16442       } else if (!strcasecmp(v->name, "pickupgroup")) {
16443          if (!strcasecmp(v->value, "none"))
16444             confp->chan.pickupgroup = 0;
16445          else
16446             confp->chan.pickupgroup = ast_get_group(v->value);
16447       } else if (!strcasecmp(v->name, "setvar")) {
16448          char *varname = ast_strdupa(v->value), *varval = NULL;
16449          struct ast_variable *tmpvar;
16450          if (varname && (varval = strchr(varname, '='))) {
16451             *varval++ = '\0';
16452             if ((tmpvar = ast_variable_new(varname, varval, ""))) {
16453                tmpvar->next = confp->chan.vars;
16454                confp->chan.vars = tmpvar;
16455             }
16456          }
16457       } else if (!strcasecmp(v->name, "immediate")) {
16458          confp->chan.immediate = ast_true(v->value);
16459       } else if (!strcasecmp(v->name, "transfertobusy")) {
16460          confp->chan.transfertobusy = ast_true(v->value);
16461       } else if (!strcasecmp(v->name, "mwimonitor")) {
16462          confp->chan.mwimonitor_neon = 0;
16463          confp->chan.mwimonitor_fsk = 0;
16464          confp->chan.mwimonitor_rpas = 0;
16465          if (strcasestr(v->value, "fsk")) {
16466             confp->chan.mwimonitor_fsk = 1;
16467          }
16468          if (strcasestr(v->value, "rpas")) {
16469             confp->chan.mwimonitor_rpas = 1;
16470          }
16471          if (strcasestr(v->value, "neon")) {
16472             confp->chan.mwimonitor_neon = 1;
16473          }
16474          /* If set to true or yes, assume that simple fsk is desired */
16475          if (ast_true(v->value)) {
16476             confp->chan.mwimonitor_fsk = 1;
16477          }
16478       } else if (!strcasecmp(v->name, "cid_rxgain")) {
16479          if (sscanf(v->value, "%30f", &confp->chan.cid_rxgain) != 1) {
16480             ast_log(LOG_WARNING, "Invalid cid_rxgain: %s at line %d.\n", v->value, v->lineno);
16481          }
16482       } else if (!strcasecmp(v->name, "rxgain")) {
16483          if (sscanf(v->value, "%30f", &confp->chan.rxgain) != 1) {
16484             ast_log(LOG_WARNING, "Invalid rxgain: %s at line %d.\n", v->value, v->lineno);
16485          }
16486       } else if (!strcasecmp(v->name, "txgain")) {
16487          if (sscanf(v->value, "%30f", &confp->chan.txgain) != 1) {
16488             ast_log(LOG_WARNING, "Invalid txgain: %s at line %d.\n", v->value, v->lineno);
16489          }
16490       } else if (!strcasecmp(v->name, "txdrc")) {
16491          if (sscanf(v->value, "%f", &confp->chan.txdrc) != 1) {
16492             ast_log(LOG_WARNING, "Invalid txdrc: %s\n", v->value);
16493          }
16494       } else if (!strcasecmp(v->name, "rxdrc")) {
16495          if (sscanf(v->value, "%f", &confp->chan.rxdrc) != 1) {
16496             ast_log(LOG_WARNING, "Invalid rxdrc: %s\n", v->value);
16497          }
16498       } else if (!strcasecmp(v->name, "tonezone")) {
16499          if (sscanf(v->value, "%30d", &confp->chan.tonezone) != 1) {
16500             ast_log(LOG_WARNING, "Invalid tonezone: %s at line %d.\n", v->value, v->lineno);
16501          }
16502       } else if (!strcasecmp(v->name, "callerid")) {
16503          if (!strcasecmp(v->value, "asreceived")) {
16504             confp->chan.cid_num[0] = '\0';
16505             confp->chan.cid_name[0] = '\0';
16506          } else {
16507             ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
16508          }
16509       } else if (!strcasecmp(v->name, "fullname")) {
16510          ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
16511       } else if (!strcasecmp(v->name, "cid_number")) {
16512          ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
16513       } else if (!strcasecmp(v->name, "cid_tag")) {
16514          ast_copy_string(confp->chan.cid_tag, v->value, sizeof(confp->chan.cid_tag));
16515       } else if (!strcasecmp(v->name, "useincomingcalleridondahditransfer")) {
16516          confp->chan.dahditrcallerid = ast_true(v->value);
16517       } else if (!strcasecmp(v->name, "restrictcid")) {
16518          confp->chan.restrictcid = ast_true(v->value);
16519       } else if (!strcasecmp(v->name, "usecallingpres")) {
16520          confp->chan.use_callingpres = ast_true(v->value);
16521       } else if (!strcasecmp(v->name, "accountcode")) {
16522          ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
16523       } else if (!strcasecmp(v->name, "amaflags")) {
16524          y = ast_cdr_amaflags2int(v->value);
16525          if (y < 0)
16526             ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d.\n", v->value, v->lineno);
16527          else
16528             confp->chan.amaflags = y;
16529       } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
16530          confp->chan.polarityonanswerdelay = atoi(v->value);
16531       } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
16532          confp->chan.answeronpolarityswitch = ast_true(v->value);
16533       } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
16534          confp->chan.hanguponpolarityswitch = ast_true(v->value);
16535       } else if (!strcasecmp(v->name, "sendcalleridafter")) {
16536          confp->chan.sendcalleridafter = atoi(v->value);
16537       } else if (!strcasecmp(v->name, "mwimonitornotify")) {
16538          ast_copy_string(mwimonitornotify, v->value, sizeof(mwimonitornotify));
16539       } else if (ast_cc_is_config_param(v->name)) {
16540          ast_cc_set_param(confp->chan.cc_params, v->name, v->value);
16541       } else if (!strcasecmp(v->name, "mwisendtype")) {
16542 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI  /* backward compatibility for older dahdi VMWI implementation */
16543          if (!strcasecmp(v->value, "rpas")) { /* Ring Pulse Alert Signal */
16544             mwisend_rpas = 1;
16545          } else {
16546             mwisend_rpas = 0;
16547          }
16548 #else
16549          /* Default is fsk, to turn it off you must specify nofsk */
16550          memset(&confp->chan.mwisend_setting, 0, sizeof(confp->chan.mwisend_setting));
16551          if (strcasestr(v->value, "nofsk")) {      /* NoFSK */
16552             confp->chan.mwisend_fsk = 0;
16553          } else {             /* Default FSK */
16554             confp->chan.mwisend_fsk = 1;
16555          }
16556          if (strcasestr(v->value, "rpas")) {       /* Ring Pulse Alert Signal, normally followed by FSK */
16557             confp->chan.mwisend_rpas = 1;
16558          } else {
16559             confp->chan.mwisend_rpas = 0;
16560          }
16561          if (strcasestr(v->value, "lrev")) {       /* Line Reversal */
16562             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_LREV;
16563          }
16564          if (strcasestr(v->value, "hvdc")) {       /* HV 90VDC */
16565             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVDC;
16566          }
16567          if ( (strcasestr(v->value, "neon")) || (strcasestr(v->value, "hvac")) ){   /* 90V DC pulses */
16568             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVAC;
16569          }
16570 #endif
16571       } else if (reload != 1) {
16572           if (!strcasecmp(v->name, "signalling") || !strcasecmp(v->name, "signaling")) {
16573             int orig_radio = confp->chan.radio;
16574             int orig_outsigmod = confp->chan.outsigmod;
16575             int orig_auto = confp->is_sig_auto;
16576 
16577             confp->chan.radio = 0;
16578             confp->chan.outsigmod = -1;
16579             confp->is_sig_auto = 0;
16580             if (!strcasecmp(v->value, "em")) {
16581                confp->chan.sig = SIG_EM;
16582             } else if (!strcasecmp(v->value, "em_e1")) {
16583                confp->chan.sig = SIG_EM_E1;
16584             } else if (!strcasecmp(v->value, "em_w")) {
16585                confp->chan.sig = SIG_EMWINK;
16586             } else if (!strcasecmp(v->value, "fxs_ls")) {
16587                confp->chan.sig = SIG_FXSLS;
16588             } else if (!strcasecmp(v->value, "fxs_gs")) {
16589                confp->chan.sig = SIG_FXSGS;
16590             } else if (!strcasecmp(v->value, "fxs_ks")) {
16591                confp->chan.sig = SIG_FXSKS;
16592             } else if (!strcasecmp(v->value, "fxo_ls")) {
16593                confp->chan.sig = SIG_FXOLS;
16594             } else if (!strcasecmp(v->value, "fxo_gs")) {
16595                confp->chan.sig = SIG_FXOGS;
16596             } else if (!strcasecmp(v->value, "fxo_ks")) {
16597                confp->chan.sig = SIG_FXOKS;
16598             } else if (!strcasecmp(v->value, "fxs_rx")) {
16599                confp->chan.sig = SIG_FXSKS;
16600                confp->chan.radio = 1;
16601             } else if (!strcasecmp(v->value, "fxo_rx")) {
16602                confp->chan.sig = SIG_FXOLS;
16603                confp->chan.radio = 1;
16604             } else if (!strcasecmp(v->value, "fxs_tx")) {
16605                confp->chan.sig = SIG_FXSLS;
16606                confp->chan.radio = 1;
16607             } else if (!strcasecmp(v->value, "fxo_tx")) {
16608                confp->chan.sig = SIG_FXOGS;
16609                confp->chan.radio = 1;
16610             } else if (!strcasecmp(v->value, "em_rx")) {
16611                confp->chan.sig = SIG_EM;
16612                confp->chan.radio = 1;
16613             } else if (!strcasecmp(v->value, "em_tx")) {
16614                confp->chan.sig = SIG_EM;
16615                confp->chan.radio = 1;
16616             } else if (!strcasecmp(v->value, "em_rxtx")) {
16617                confp->chan.sig = SIG_EM;
16618                confp->chan.radio = 2;
16619             } else if (!strcasecmp(v->value, "em_txrx")) {
16620                confp->chan.sig = SIG_EM;
16621                confp->chan.radio = 2;
16622             } else if (!strcasecmp(v->value, "sf")) {
16623                confp->chan.sig = SIG_SF;
16624             } else if (!strcasecmp(v->value, "sf_w")) {
16625                confp->chan.sig = SIG_SFWINK;
16626             } else if (!strcasecmp(v->value, "sf_featd")) {
16627                confp->chan.sig = SIG_FEATD;
16628             } else if (!strcasecmp(v->value, "sf_featdmf")) {
16629                confp->chan.sig = SIG_FEATDMF;
16630             } else if (!strcasecmp(v->value, "sf_featb")) {
16631                confp->chan.sig = SIG_SF_FEATB;
16632             } else if (!strcasecmp(v->value, "sf")) {
16633                confp->chan.sig = SIG_SF;
16634             } else if (!strcasecmp(v->value, "sf_rx")) {
16635                confp->chan.sig = SIG_SF;
16636                confp->chan.radio = 1;
16637             } else if (!strcasecmp(v->value, "sf_tx")) {
16638                confp->chan.sig = SIG_SF;
16639                confp->chan.radio = 1;
16640             } else if (!strcasecmp(v->value, "sf_rxtx")) {
16641                confp->chan.sig = SIG_SF;
16642                confp->chan.radio = 2;
16643             } else if (!strcasecmp(v->value, "sf_txrx")) {
16644                confp->chan.sig = SIG_SF;
16645                confp->chan.radio = 2;
16646             } else if (!strcasecmp(v->value, "featd")) {
16647                confp->chan.sig = SIG_FEATD;
16648             } else if (!strcasecmp(v->value, "featdmf")) {
16649                confp->chan.sig = SIG_FEATDMF;
16650             } else if (!strcasecmp(v->value, "featdmf_ta")) {
16651                confp->chan.sig = SIG_FEATDMF_TA;
16652             } else if (!strcasecmp(v->value, "e911")) {
16653                confp->chan.sig = SIG_E911;
16654             } else if (!strcasecmp(v->value, "fgccama")) {
16655                confp->chan.sig = SIG_FGC_CAMA;
16656             } else if (!strcasecmp(v->value, "fgccamamf")) {
16657                confp->chan.sig = SIG_FGC_CAMAMF;
16658             } else if (!strcasecmp(v->value, "featb")) {
16659                confp->chan.sig = SIG_FEATB;
16660 #ifdef HAVE_PRI
16661             } else if (!strcasecmp(v->value, "pri_net")) {
16662                confp->chan.sig = SIG_PRI;
16663                confp->pri.pri.nodetype = PRI_NETWORK;
16664             } else if (!strcasecmp(v->value, "pri_cpe")) {
16665                confp->chan.sig = SIG_PRI;
16666                confp->pri.pri.nodetype = PRI_CPE;
16667             } else if (!strcasecmp(v->value, "bri_cpe")) {
16668                confp->chan.sig = SIG_BRI;
16669                confp->pri.pri.nodetype = PRI_CPE;
16670             } else if (!strcasecmp(v->value, "bri_net")) {
16671                confp->chan.sig = SIG_BRI;
16672                confp->pri.pri.nodetype = PRI_NETWORK;
16673             } else if (!strcasecmp(v->value, "bri_cpe_ptmp")) {
16674                confp->chan.sig = SIG_BRI_PTMP;
16675                confp->pri.pri.nodetype = PRI_CPE;
16676             } else if (!strcasecmp(v->value, "bri_net_ptmp")) {
16677 #if defined(HAVE_PRI_CALL_HOLD)
16678                confp->chan.sig = SIG_BRI_PTMP;
16679                confp->pri.pri.nodetype = PRI_NETWORK;
16680 #else
16681                ast_log(LOG_WARNING, "How cool would it be if someone implemented this mode!  For now, sucks for you. (line %d)\n", v->lineno);
16682 #endif   /* !defined(HAVE_PRI_CALL_HOLD) */
16683 #endif
16684 #if defined(HAVE_SS7)
16685             } else if (!strcasecmp(v->value, "ss7")) {
16686                confp->chan.sig = SIG_SS7;
16687 #endif   /* defined(HAVE_SS7) */
16688 #ifdef HAVE_OPENR2
16689             } else if (!strcasecmp(v->value, "mfcr2")) {
16690                confp->chan.sig = SIG_MFCR2;
16691 #endif
16692             } else if (!strcasecmp(v->value, "auto")) {
16693                confp->is_sig_auto = 1;
16694             } else {
16695                confp->chan.outsigmod = orig_outsigmod;
16696                confp->chan.radio = orig_radio;
16697                confp->is_sig_auto = orig_auto;
16698                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
16699             }
16700           } else if (!strcasecmp(v->name, "outsignalling") || !strcasecmp(v->name, "outsignaling")) {
16701             if (!strcasecmp(v->value, "em")) {
16702                confp->chan.outsigmod = SIG_EM;
16703             } else if (!strcasecmp(v->value, "em_e1")) {
16704                confp->chan.outsigmod = SIG_EM_E1;
16705             } else if (!strcasecmp(v->value, "em_w")) {
16706                confp->chan.outsigmod = SIG_EMWINK;
16707             } else if (!strcasecmp(v->value, "sf")) {
16708                confp->chan.outsigmod = SIG_SF;
16709             } else if (!strcasecmp(v->value, "sf_w")) {
16710                confp->chan.outsigmod = SIG_SFWINK;
16711             } else if (!strcasecmp(v->value, "sf_featd")) {
16712                confp->chan.outsigmod = SIG_FEATD;
16713             } else if (!strcasecmp(v->value, "sf_featdmf")) {
16714                confp->chan.outsigmod = SIG_FEATDMF;
16715             } else if (!strcasecmp(v->value, "sf_featb")) {
16716                confp->chan.outsigmod = SIG_SF_FEATB;
16717             } else if (!strcasecmp(v->value, "sf")) {
16718                confp->chan.outsigmod = SIG_SF;
16719             } else if (!strcasecmp(v->value, "featd")) {
16720                confp->chan.outsigmod = SIG_FEATD;
16721             } else if (!strcasecmp(v->value, "featdmf")) {
16722                confp->chan.outsigmod = SIG_FEATDMF;
16723             } else if (!strcasecmp(v->value, "featdmf_ta")) {
16724                confp->chan.outsigmod = SIG_FEATDMF_TA;
16725             } else if (!strcasecmp(v->value, "e911")) {
16726                confp->chan.outsigmod = SIG_E911;
16727             } else if (!strcasecmp(v->value, "fgccama")) {
16728                confp->chan.outsigmod = SIG_FGC_CAMA;
16729             } else if (!strcasecmp(v->value, "fgccamamf")) {
16730                confp->chan.outsigmod = SIG_FGC_CAMAMF;
16731             } else if (!strcasecmp(v->value, "featb")) {
16732                confp->chan.outsigmod = SIG_FEATB;
16733             } else {
16734                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
16735             }
16736 #ifdef HAVE_PRI
16737          } else if (!strcasecmp(v->name, "pridialplan")) {
16738             if (!strcasecmp(v->value, "national")) {
16739                confp->pri.pri.dialplan = PRI_NATIONAL_ISDN + 1;
16740             } else if (!strcasecmp(v->value, "unknown")) {
16741                confp->pri.pri.dialplan = PRI_UNKNOWN + 1;
16742             } else if (!strcasecmp(v->value, "private")) {
16743                confp->pri.pri.dialplan = PRI_PRIVATE + 1;
16744             } else if (!strcasecmp(v->value, "international")) {
16745                confp->pri.pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
16746             } else if (!strcasecmp(v->value, "local")) {
16747                confp->pri.pri.dialplan = PRI_LOCAL_ISDN + 1;
16748             } else if (!strcasecmp(v->value, "dynamic")) {
16749                confp->pri.pri.dialplan = -1;
16750             } else if (!strcasecmp(v->value, "redundant")) {
16751                confp->pri.pri.dialplan = -2;
16752             } else {
16753                ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
16754             }
16755          } else if (!strcasecmp(v->name, "prilocaldialplan")) {
16756             if (!strcasecmp(v->value, "national")) {
16757                confp->pri.pri.localdialplan = PRI_NATIONAL_ISDN + 1;
16758             } else if (!strcasecmp(v->value, "unknown")) {
16759                confp->pri.pri.localdialplan = PRI_UNKNOWN + 1;
16760             } else if (!strcasecmp(v->value, "private")) {
16761                confp->pri.pri.localdialplan = PRI_PRIVATE + 1;
16762             } else if (!strcasecmp(v->value, "international")) {
16763                confp->pri.pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
16764             } else if (!strcasecmp(v->value, "local")) {
16765                confp->pri.pri.localdialplan = PRI_LOCAL_ISDN + 1;
16766             } else if (!strcasecmp(v->value, "dynamic")) {
16767                confp->pri.pri.localdialplan = -1;
16768             } else if (!strcasecmp(v->value, "redundant")) {
16769                confp->pri.pri.localdialplan = -2;
16770             } else {
16771                ast_log(LOG_WARNING, "Unknown PRI localdialplan '%s' at line %d.\n", v->value, v->lineno);
16772             }
16773          } else if (!strcasecmp(v->name, "switchtype")) {
16774             if (!strcasecmp(v->value, "national"))
16775                confp->pri.pri.switchtype = PRI_SWITCH_NI2;
16776             else if (!strcasecmp(v->value, "ni1"))
16777                confp->pri.pri.switchtype = PRI_SWITCH_NI1;
16778             else if (!strcasecmp(v->value, "dms100"))
16779                confp->pri.pri.switchtype = PRI_SWITCH_DMS100;
16780             else if (!strcasecmp(v->value, "4ess"))
16781                confp->pri.pri.switchtype = PRI_SWITCH_ATT4ESS;
16782             else if (!strcasecmp(v->value, "5ess"))
16783                confp->pri.pri.switchtype = PRI_SWITCH_LUCENT5E;
16784             else if (!strcasecmp(v->value, "euroisdn"))
16785                confp->pri.pri.switchtype = PRI_SWITCH_EUROISDN_E1;
16786             else if (!strcasecmp(v->value, "qsig"))
16787                confp->pri.pri.switchtype = PRI_SWITCH_QSIG;
16788             else {
16789                ast_log(LOG_ERROR, "Unknown switchtype '%s' at line %d.\n", v->value, v->lineno);
16790                return -1;
16791             }
16792          } else if (!strcasecmp(v->name, "msn")) {
16793             ast_copy_string(confp->pri.pri.msn_list, v->value,
16794                sizeof(confp->pri.pri.msn_list));
16795          } else if (!strcasecmp(v->name, "nsf")) {
16796             if (!strcasecmp(v->value, "sdn"))
16797                confp->pri.pri.nsf = PRI_NSF_SDN;
16798             else if (!strcasecmp(v->value, "megacom"))
16799                confp->pri.pri.nsf = PRI_NSF_MEGACOM;
16800             else if (!strcasecmp(v->value, "tollfreemegacom"))
16801                confp->pri.pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
16802             else if (!strcasecmp(v->value, "accunet"))
16803                confp->pri.pri.nsf = PRI_NSF_ACCUNET;
16804             else if (!strcasecmp(v->value, "none"))
16805                confp->pri.pri.nsf = PRI_NSF_NONE;
16806             else {
16807                ast_log(LOG_WARNING, "Unknown network-specific facility '%s' at line %d.\n", v->value, v->lineno);
16808                confp->pri.pri.nsf = PRI_NSF_NONE;
16809             }
16810          } else if (!strcasecmp(v->name, "priindication")) {
16811             if (!strcasecmp(v->value, "outofband"))
16812                confp->chan.priindication_oob = 1;
16813             else if (!strcasecmp(v->value, "inband"))
16814                confp->chan.priindication_oob = 0;
16815             else
16816                ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d.\n",
16817                   v->value, v->lineno);
16818          } else if (!strcasecmp(v->name, "priexclusive")) {
16819             confp->chan.priexclusive = ast_true(v->value);
16820          } else if (!strcasecmp(v->name, "internationalprefix")) {
16821             ast_copy_string(confp->pri.pri.internationalprefix, v->value, sizeof(confp->pri.pri.internationalprefix));
16822          } else if (!strcasecmp(v->name, "nationalprefix")) {
16823             ast_copy_string(confp->pri.pri.nationalprefix, v->value, sizeof(confp->pri.pri.nationalprefix));
16824          } else if (!strcasecmp(v->name, "localprefix")) {
16825             ast_copy_string(confp->pri.pri.localprefix, v->value, sizeof(confp->pri.pri.localprefix));
16826          } else if (!strcasecmp(v->name, "privateprefix")) {
16827             ast_copy_string(confp->pri.pri.privateprefix, v->value, sizeof(confp->pri.pri.privateprefix));
16828          } else if (!strcasecmp(v->name, "unknownprefix")) {
16829             ast_copy_string(confp->pri.pri.unknownprefix, v->value, sizeof(confp->pri.pri.unknownprefix));
16830          } else if (!strcasecmp(v->name, "resetinterval")) {
16831             if (!strcasecmp(v->value, "never"))
16832                confp->pri.pri.resetinterval = -1;
16833             else if (atoi(v->value) >= 60)
16834                confp->pri.pri.resetinterval = atoi(v->value);
16835             else
16836                ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d.\n",
16837                   v->value, v->lineno);
16838          } else if (!strcasecmp(v->name, "minunused")) {
16839             confp->pri.pri.minunused = atoi(v->value);
16840          } else if (!strcasecmp(v->name, "minidle")) {
16841             confp->pri.pri.minidle = atoi(v->value);
16842          } else if (!strcasecmp(v->name, "idleext")) {
16843             ast_copy_string(confp->pri.pri.idleext, v->value, sizeof(confp->pri.pri.idleext));
16844          } else if (!strcasecmp(v->name, "idledial")) {
16845             ast_copy_string(confp->pri.pri.idledial, v->value, sizeof(confp->pri.pri.idledial));
16846          } else if (!strcasecmp(v->name, "overlapdial")) {
16847             if (ast_true(v->value)) {
16848                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
16849             } else if (!strcasecmp(v->value, "incoming")) {
16850                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_INCOMING;
16851             } else if (!strcasecmp(v->value, "outgoing")) {
16852                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_OUTGOING;
16853             } else if (!strcasecmp(v->value, "both") || ast_true(v->value)) {
16854                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
16855             } else {
16856                confp->pri.pri.overlapdial = DAHDI_OVERLAPDIAL_NONE;
16857             }
16858 #ifdef HAVE_PRI_PROG_W_CAUSE
16859          } else if (!strcasecmp(v->name, "qsigchannelmapping")) {
16860             if (!strcasecmp(v->value, "logical")) {
16861                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_LOGICAL;
16862             } else if (!strcasecmp(v->value, "physical")) {
16863                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
16864             } else {
16865                confp->pri.pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
16866             }
16867 #endif
16868          } else if (!strcasecmp(v->name, "discardremoteholdretrieval")) {
16869             confp->pri.pri.discardremoteholdretrieval = ast_true(v->value);
16870 #if defined(HAVE_PRI_SERVICE_MESSAGES)
16871          } else if (!strcasecmp(v->name, "service_message_support")) {
16872             /* assuming switchtype for this channel group has been configured already */
16873             if ((confp->pri.pri.switchtype == PRI_SWITCH_ATT4ESS 
16874                || confp->pri.pri.switchtype == PRI_SWITCH_LUCENT5E
16875                || confp->pri.pri.switchtype == PRI_SWITCH_NI2) && ast_true(v->value)) {
16876                confp->pri.pri.enable_service_message_support = 1;
16877             } else {
16878                confp->pri.pri.enable_service_message_support = 0;
16879             }
16880 #endif   /* defined(HAVE_PRI_SERVICE_MESSAGES) */
16881 #ifdef HAVE_PRI_INBANDDISCONNECT
16882          } else if (!strcasecmp(v->name, "inbanddisconnect")) {
16883             confp->pri.pri.inbanddisconnect = ast_true(v->value);
16884 #endif
16885          } else if (!strcasecmp(v->name, "pritimer")) {
16886 #ifdef PRI_GETSET_TIMERS
16887             char tmp[20];
16888             char *timerc;
16889             char *c;
16890             int timer;
16891             int timeridx;
16892 
16893             ast_copy_string(tmp, v->value, sizeof(tmp));
16894             c = tmp;
16895             timerc = strsep(&c, ",");
16896             if (!ast_strlen_zero(timerc) && !ast_strlen_zero(c)) {
16897                timeridx = pri_timer2idx(timerc);
16898                timer = atoi(c);
16899                if (timeridx < 0 || PRI_MAX_TIMERS <= timeridx) {
16900                   ast_log(LOG_WARNING,
16901                      "'%s' is not a valid ISDN timer at line %d.\n", timerc,
16902                      v->lineno);
16903                } else if (!timer) {
16904                   ast_log(LOG_WARNING,
16905                      "'%s' is not a valid value for ISDN timer '%s' at line %d.\n",
16906                      c, timerc, v->lineno);
16907                } else {
16908                   confp->pri.pri.pritimers[timeridx] = timer;
16909                }
16910             } else {
16911                ast_log(LOG_WARNING,
16912                   "'%s' is not a valid ISDN timer configuration string at line %d.\n",
16913                   v->value, v->lineno);
16914             }
16915 #endif /* PRI_GETSET_TIMERS */
16916          } else if (!strcasecmp(v->name, "facilityenable")) {
16917             confp->pri.pri.facilityenable = ast_true(v->value);
16918 #if defined(HAVE_PRI_AOC_EVENTS)
16919          } else if (!strcasecmp(v->name, "aoc_enable")) {
16920             confp->pri.pri.aoc_passthrough_flag = 0;
16921             if (strchr(v->value, 's') || strchr(v->value, 'S')) {
16922                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_S;
16923             }
16924             if (strchr(v->value, 'd') || strchr(v->value, 'D')) {
16925                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_D;
16926             }
16927             if (strchr(v->value, 'e') || strchr(v->value, 'E')) {
16928                confp->pri.pri.aoc_passthrough_flag |= SIG_PRI_AOC_GRANT_E;
16929             }
16930          } else if (!strcasecmp(v->name, "aoce_delayhangup")) {
16931             confp->pri.pri.aoce_delayhangup = ast_true(v->value);
16932 #endif   /* defined(HAVE_PRI_AOC_EVENTS) */
16933 #if defined(HAVE_PRI_CALL_HOLD)
16934          } else if (!strcasecmp(v->name, "hold_disconnect_transfer")) {
16935             confp->pri.pri.hold_disconnect_transfer = ast_true(v->value);
16936 #endif   /* defined(HAVE_PRI_CALL_HOLD) */
16937 #if defined(HAVE_PRI_CCSS)
16938          } else if (!strcasecmp(v->name, "cc_ptmp_recall_mode")) {
16939             if (!strcasecmp(v->value, "global")) {
16940                confp->pri.pri.cc_ptmp_recall_mode = 0;/* globalRecall */
16941             } else if (!strcasecmp(v->value, "specific")) {
16942                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
16943             } else {
16944                confp->pri.pri.cc_ptmp_recall_mode = 1;/* specificRecall */
16945             }
16946          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_req")) {
16947             if (!strcasecmp(v->value, "release")) {
16948                confp->pri.pri.cc_qsig_signaling_link_req = 0;/* release */
16949             } else if (!strcasecmp(v->value, "retain")) {
16950                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
16951             } else if (!strcasecmp(v->value, "do_not_care")) {
16952                confp->pri.pri.cc_qsig_signaling_link_req = 2;/* do-not-care */
16953             } else {
16954                confp->pri.pri.cc_qsig_signaling_link_req = 1;/* retain */
16955             }
16956          } else if (!strcasecmp(v->name, "cc_qsig_signaling_link_rsp")) {
16957             if (!strcasecmp(v->value, "release")) {
16958                confp->pri.pri.cc_qsig_signaling_link_rsp = 0;/* release */
16959             } else if (!strcasecmp(v->value, "retain")) {
16960                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
16961             } else {
16962                confp->pri.pri.cc_qsig_signaling_link_rsp = 1;/* retain */
16963             }
16964 #endif   /* defined(HAVE_PRI_CCSS) */
16965 #if defined(HAVE_PRI_CALL_WAITING)
16966          } else if (!strcasecmp(v->name, "max_call_waiting_calls")) {
16967             confp->pri.pri.max_call_waiting_calls = atoi(v->value);
16968             if (confp->pri.pri.max_call_waiting_calls < 0) {
16969                /* Negative values are not allowed. */
16970                confp->pri.pri.max_call_waiting_calls = 0;
16971             }
16972          } else if (!strcasecmp(v->name, "allow_call_waiting_calls")) {
16973             confp->pri.pri.allow_call_waiting_calls = ast_true(v->value);
16974 #endif   /* defined(HAVE_PRI_CALL_WAITING) */
16975 #if defined(HAVE_PRI_MWI)
16976          } else if (!strcasecmp(v->name, "mwi_mailboxes")) {
16977             ast_copy_string(confp->pri.pri.mwi_mailboxes, v->value,
16978                sizeof(confp->pri.pri.mwi_mailboxes));
16979 #endif   /* defined(HAVE_PRI_MWI) */
16980          } else if (!strcasecmp(v->name, "append_msn_to_cid_tag")) {
16981             confp->pri.pri.append_msn_to_user_tag = ast_true(v->value);
16982 #endif /* HAVE_PRI */
16983 #if defined(HAVE_SS7)
16984          } else if (!strcasecmp(v->name, "ss7type")) {
16985             if (!strcasecmp(v->value, "itu")) {
16986                cur_ss7type = SS7_ITU;
16987             } else if (!strcasecmp(v->value, "ansi")) {
16988                cur_ss7type = SS7_ANSI;
16989             } else
16990                ast_log(LOG_WARNING, "'%s' is an unknown ss7 switch type at line %d.!\n", v->value, v->lineno);
16991          } else if (!strcasecmp(v->name, "linkset")) {
16992             cur_linkset = atoi(v->value);
16993          } else if (!strcasecmp(v->name, "pointcode")) {
16994             cur_pointcode = parse_pointcode(v->value);
16995          } else if (!strcasecmp(v->name, "adjpointcode")) {
16996             cur_adjpointcode = parse_pointcode(v->value);
16997          } else if (!strcasecmp(v->name, "defaultdpc")) {
16998             cur_defaultdpc = parse_pointcode(v->value);
16999          } else if (!strcasecmp(v->name, "cicbeginswith")) {
17000             cur_cicbeginswith = atoi(v->value);
17001          } else if (!strcasecmp(v->name, "networkindicator")) {
17002             if (!strcasecmp(v->value, "national"))
17003                cur_networkindicator = SS7_NI_NAT;
17004             else if (!strcasecmp(v->value, "national_spare"))
17005                cur_networkindicator = SS7_NI_NAT_SPARE;
17006             else if (!strcasecmp(v->value, "international"))
17007                cur_networkindicator = SS7_NI_INT;
17008             else if (!strcasecmp(v->value, "international_spare"))
17009                cur_networkindicator = SS7_NI_INT_SPARE;
17010             else
17011                cur_networkindicator = -1;
17012          } else if (!strcasecmp(v->name, "ss7_internationalprefix")) {
17013             ast_copy_string(confp->ss7.ss7.internationalprefix, v->value, sizeof(confp->ss7.ss7.internationalprefix));
17014          } else if (!strcasecmp(v->name, "ss7_nationalprefix")) {
17015             ast_copy_string(confp->ss7.ss7.nationalprefix, v->value, sizeof(confp->ss7.ss7.nationalprefix));
17016          } else if (!strcasecmp(v->name, "ss7_subscriberprefix")) {
17017             ast_copy_string(confp->ss7.ss7.subscriberprefix, v->value, sizeof(confp->ss7.ss7.subscriberprefix));
17018          } else if (!strcasecmp(v->name, "ss7_unknownprefix")) {
17019             ast_copy_string(confp->ss7.ss7.unknownprefix, v->value, sizeof(confp->ss7.ss7.unknownprefix));
17020          } else if (!strcasecmp(v->name, "ss7_called_nai")) {
17021             if (!strcasecmp(v->value, "national")) {
17022                confp->ss7.ss7.called_nai = SS7_NAI_NATIONAL;
17023             } else if (!strcasecmp(v->value, "international")) {
17024                confp->ss7.ss7.called_nai = SS7_NAI_INTERNATIONAL;
17025             } else if (!strcasecmp(v->value, "subscriber")) {
17026                confp->ss7.ss7.called_nai = SS7_NAI_SUBSCRIBER;
17027             } else if (!strcasecmp(v->value, "unknown")) {
17028                confp->ss7.ss7.called_nai = SS7_NAI_UNKNOWN;
17029             } else if (!strcasecmp(v->value, "dynamic")) {
17030                confp->ss7.ss7.called_nai = SS7_NAI_DYNAMIC;
17031             } else {
17032                ast_log(LOG_WARNING, "Unknown SS7 called_nai '%s' at line %d.\n", v->value, v->lineno);
17033             }
17034          } else if (!strcasecmp(v->name, "ss7_calling_nai")) {
17035             if (!strcasecmp(v->value, "national")) {
17036                confp->ss7.ss7.calling_nai = SS7_NAI_NATIONAL;
17037             } else if (!strcasecmp(v->value, "international")) {
17038                confp->ss7.ss7.calling_nai = SS7_NAI_INTERNATIONAL;
17039             } else if (!strcasecmp(v->value, "subscriber")) {
17040                confp->ss7.ss7.calling_nai = SS7_NAI_SUBSCRIBER;
17041             } else if (!strcasecmp(v->value, "unknown")) {
17042                confp->ss7.ss7.calling_nai = SS7_NAI_UNKNOWN;
17043             } else if (!strcasecmp(v->value, "dynamic")) {
17044                confp->ss7.ss7.calling_nai = SS7_NAI_DYNAMIC;
17045             } else {
17046                ast_log(LOG_WARNING, "Unknown SS7 calling_nai '%s' at line %d.\n", v->value, v->lineno);
17047             }
17048          } else if (!strcasecmp(v->name, "sigchan")) {
17049             int sigchan, res;
17050             sigchan = atoi(v->value);
17051             res = linkset_addsigchan(sigchan);
17052             if (res < 0)
17053                return -1;
17054 
17055          } else if (!strcasecmp(v->name, "ss7_explicitacm")) {
17056             struct dahdi_ss7 *link;
17057             link = ss7_resolve_linkset(cur_linkset);
17058             if (!link) {
17059                ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
17060                return -1;
17061             }
17062             if (ast_true(v->value))
17063                link->ss7.flags |= LINKSET_FLAG_EXPLICITACM;
17064 #endif   /* defined(HAVE_SS7) */
17065 #ifdef HAVE_OPENR2
17066          } else if (!strcasecmp(v->name, "mfcr2_advanced_protocol_file")) {
17067             ast_copy_string(confp->mfcr2.r2proto_file, v->value, sizeof(confp->mfcr2.r2proto_file));
17068             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);
17069          } else if (!strcasecmp(v->name, "mfcr2_logdir")) {
17070             ast_copy_string(confp->mfcr2.logdir, v->value, sizeof(confp->mfcr2.logdir));
17071          } else if (!strcasecmp(v->name, "mfcr2_variant")) {
17072             confp->mfcr2.variant = openr2_proto_get_variant(v->value);
17073             if (OR2_VAR_UNKNOWN == confp->mfcr2.variant) {
17074                ast_log(LOG_WARNING, "Unknown MFC/R2 variant '%s' at line %d, defaulting to ITU.\n", v->value, v->lineno);
17075                confp->mfcr2.variant = OR2_VAR_ITU;
17076             }
17077          } else if (!strcasecmp(v->name, "mfcr2_mfback_timeout")) {
17078             confp->mfcr2.mfback_timeout = atoi(v->value);
17079             if (!confp->mfcr2.mfback_timeout) {
17080                ast_log(LOG_WARNING, "MF timeout of 0? hum, I will protect you from your ignorance. Setting default.\n");
17081                confp->mfcr2.mfback_timeout = -1;
17082             } else if (confp->mfcr2.mfback_timeout > 0 && confp->mfcr2.mfback_timeout < 500) {
17083                ast_log(LOG_WARNING, "MF timeout less than 500ms is not recommended, you have been warned!\n");
17084             }
17085          } else if (!strcasecmp(v->name, "mfcr2_metering_pulse_timeout")) {
17086             confp->mfcr2.metering_pulse_timeout = atoi(v->value);
17087             if (confp->mfcr2.metering_pulse_timeout > 500) {
17088                ast_log(LOG_WARNING, "Metering pulse timeout greater than 500ms is not recommended, you have been warned!\n");
17089             }
17090          } else if (!strcasecmp(v->name, "mfcr2_get_ani_first")) {
17091             confp->mfcr2.get_ani_first = ast_true(v->value) ? 1 : 0;
17092          } else if (!strcasecmp(v->name, "mfcr2_double_answer")) {
17093             confp->mfcr2.double_answer = ast_true(v->value) ? 1 : 0;
17094          } else if (!strcasecmp(v->name, "mfcr2_charge_calls")) {
17095             confp->mfcr2.charge_calls = ast_true(v->value) ? 1 : 0;
17096          } else if (!strcasecmp(v->name, "mfcr2_accept_on_offer")) {
17097             confp->mfcr2.accept_on_offer = ast_true(v->value) ? 1 : 0;
17098          } else if (!strcasecmp(v->name, "mfcr2_allow_collect_calls")) {
17099             confp->mfcr2.allow_collect_calls = ast_true(v->value) ? 1 : 0;
17100          } else if (!strcasecmp(v->name, "mfcr2_forced_release")) {
17101             confp->mfcr2.forced_release = ast_true(v->value) ? 1 : 0;
17102          } else if (!strcasecmp(v->name, "mfcr2_immediate_accept")) {
17103             confp->mfcr2.immediate_accept = ast_true(v->value) ? 1 : 0;
17104 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
17105          } else if (!strcasecmp(v->name, "mfcr2_skip_category")) {
17106             confp->mfcr2.skip_category_request = ast_true(v->value) ? 1 : 0;
17107 #endif
17108          } else if (!strcasecmp(v->name, "mfcr2_call_files")) {
17109             confp->mfcr2.call_files = ast_true(v->value) ? 1 : 0;
17110          } else if (!strcasecmp(v->name, "mfcr2_max_ani")) {
17111             confp->mfcr2.max_ani = atoi(v->value);
17112             if (confp->mfcr2.max_ani >= AST_MAX_EXTENSION){
17113                confp->mfcr2.max_ani = AST_MAX_EXTENSION - 1;
17114             }
17115          } else if (!strcasecmp(v->name, "mfcr2_max_dnis")) {
17116             confp->mfcr2.max_dnis = atoi(v->value);
17117             if (confp->mfcr2.max_dnis >= AST_MAX_EXTENSION){
17118                confp->mfcr2.max_dnis = AST_MAX_EXTENSION - 1;
17119             }
17120          } else if (!strcasecmp(v->name, "mfcr2_category")) {
17121             confp->mfcr2.category = openr2_proto_get_category(v->value);
17122             if (OR2_CALLING_PARTY_CATEGORY_UNKNOWN == confp->mfcr2.category) {
17123                confp->mfcr2.category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER;
17124                ast_log(LOG_WARNING, "Invalid MFC/R2 caller category '%s' at line %d. Using national subscriber as default.\n",
17125                      v->value, v->lineno);
17126             }
17127          } else if (!strcasecmp(v->name, "mfcr2_logging")) {
17128             openr2_log_level_t tmplevel;
17129             char *clevel;
17130             char *logval = ast_strdupa(v->value);
17131             while (logval) {
17132                clevel = strsep(&logval,",");
17133                if (-1 == (tmplevel = openr2_log_get_level(clevel))) {
17134                   ast_log(LOG_WARNING, "Ignoring invalid logging level: '%s' at line %d.\n", clevel, v->lineno);
17135                   continue;
17136                }
17137                confp->mfcr2.loglevel |= tmplevel;
17138             }
17139 #endif /* HAVE_OPENR2 */
17140          } else if (!strcasecmp(v->name, "cadence")) {
17141             /* setup to scan our argument */
17142             int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
17143             int i;
17144             struct dahdi_ring_cadence new_cadence;
17145             int cid_location = -1;
17146             int firstcadencepos = 0;
17147             char original_args[80];
17148             int cadence_is_ok = 1;
17149 
17150             ast_copy_string(original_args, v->value, sizeof(original_args));
17151             /* 16 cadences allowed (8 pairs) */
17152             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]);
17153 
17154             /* Cadence must be even (on/off) */
17155             if (element_count % 2 == 1) {
17156                ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s at line %d.\n", original_args, v->lineno);
17157                cadence_is_ok = 0;
17158             }
17159 
17160             /* Ring cadences cannot be negative */
17161             for (i = 0; i < element_count; i++) {
17162                if (c[i] == 0) {
17163                   ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s at line %d.\n", original_args, v->lineno);
17164                   cadence_is_ok = 0;
17165                   break;
17166                } else if (c[i] < 0) {
17167                   if (i % 2 == 1) {
17168                      /* Silence duration, negative possibly okay */
17169                      if (cid_location == -1) {
17170                         cid_location = i;
17171                         c[i] *= -1;
17172                      } else {
17173                         ast_log(LOG_ERROR, "CID location specified twice: %s at line %d.\n", original_args, v->lineno);
17174                         cadence_is_ok = 0;
17175                         break;
17176                      }
17177                   } else {
17178                      if (firstcadencepos == 0) {
17179                         firstcadencepos = i; /* only recorded to avoid duplicate specification */
17180                                  /* duration will be passed negative to the DAHDI driver */
17181                      } else {
17182                          ast_log(LOG_ERROR, "First cadence position specified twice: %s at line %d.\n", original_args, v->lineno);
17183                         cadence_is_ok = 0;
17184                         break;
17185                      }
17186                   }
17187                }
17188             }
17189 
17190             /* Substitute our scanned cadence */
17191             for (i = 0; i < 16; i++) {
17192                new_cadence.ringcadence[i] = c[i];
17193             }
17194 
17195             if (cadence_is_ok) {
17196                /* ---we scanned it without getting annoyed; now some sanity checks--- */
17197                if (element_count < 2) {
17198                   ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s at line %d.\n", original_args, v->lineno);
17199                } else {
17200                   if (cid_location == -1) {
17201                      /* user didn't say; default to first pause */
17202                      cid_location = 1;
17203                   } else {
17204                      /* convert element_index to cidrings value */
17205                      cid_location = (cid_location + 1) / 2;
17206                   }
17207                   /* ---we like their cadence; try to install it--- */
17208                   if (!user_has_defined_cadences++)
17209                      /* this is the first user-defined cadence; clear the default user cadences */
17210                      num_cadence = 0;
17211                   if ((num_cadence+1) >= NUM_CADENCE_MAX)
17212                      ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s at line %d.\n", NUM_CADENCE_MAX, original_args, v->lineno);
17213                   else {
17214                      cadences[num_cadence] = new_cadence;
17215                      cidrings[num_cadence++] = cid_location;
17216                      ast_verb(3, "cadence 'r%d' added: %s\n",num_cadence,original_args);
17217                   }
17218                }
17219             }
17220          } else if (!strcasecmp(v->name, "ringtimeout")) {
17221             ringt_base = (atoi(v->value) * 8) / READ_SIZE;
17222          } else if (!strcasecmp(v->name, "prewink")) {
17223             confp->timing.prewinktime = atoi(v->value);
17224          } else if (!strcasecmp(v->name, "preflash")) {
17225             confp->timing.preflashtime = atoi(v->value);
17226          } else if (!strcasecmp(v->name, "wink")) {
17227             confp->timing.winktime = atoi(v->value);
17228          } else if (!strcasecmp(v->name, "flash")) {
17229             confp->timing.flashtime = atoi(v->value);
17230          } else if (!strcasecmp(v->name, "start")) {
17231             confp->timing.starttime = atoi(v->value);
17232          } else if (!strcasecmp(v->name, "rxwink")) {
17233             confp->timing.rxwinktime = atoi(v->value);
17234          } else if (!strcasecmp(v->name, "rxflash")) {
17235             confp->timing.rxflashtime = atoi(v->value);
17236          } else if (!strcasecmp(v->name, "debounce")) {
17237             confp->timing.debouncetime = atoi(v->value);
17238          } else if (!strcasecmp(v->name, "toneduration")) {
17239             int toneduration;
17240             int ctlfd;
17241             int res;
17242             struct dahdi_dialparams dps;
17243 
17244             ctlfd = open("/dev/dahdi/ctl", O_RDWR);
17245             if (ctlfd == -1) {
17246                ast_log(LOG_ERROR, "Unable to open /dev/dahdi/ctl to set toneduration at line %d.\n", v->lineno);
17247                return -1;
17248             }
17249 
17250             toneduration = atoi(v->value);
17251             if (toneduration > -1) {
17252                memset(&dps, 0, sizeof(dps));
17253 
17254                dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
17255                res = ioctl(ctlfd, DAHDI_SET_DIALPARAMS, &dps);
17256                if (res < 0) {
17257                   ast_log(LOG_ERROR, "Invalid tone duration: %d ms at line %d: %s\n", toneduration, v->lineno, strerror(errno));
17258                   close(ctlfd);
17259                   return -1;
17260                }
17261             }
17262             close(ctlfd);
17263          } else if (!strcasecmp(v->name, "defaultcic")) {
17264             ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
17265          } else if (!strcasecmp(v->name, "defaultozz")) {
17266             ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
17267          } else if (!strcasecmp(v->name, "mwilevel")) {
17268             mwilevel = atoi(v->value);
17269          } else if (!strcasecmp(v->name, "dtmfcidlevel")) {
17270             dtmfcid_level = atoi(v->value);
17271          } else if (!strcasecmp(v->name, "reportalarms")) {
17272             if (!strcasecmp(v->value, "all"))
17273                report_alarms = REPORT_CHANNEL_ALARMS | REPORT_SPAN_ALARMS;
17274             if (!strcasecmp(v->value, "none"))
17275                report_alarms = 0;
17276             else if (!strcasecmp(v->value, "channels"))
17277                report_alarms = REPORT_CHANNEL_ALARMS;
17278             else if (!strcasecmp(v->value, "spans"))
17279                report_alarms = REPORT_SPAN_ALARMS;
17280           }
17281       } else if (!(options & PROC_DAHDI_OPT_NOWARN) )
17282          ast_log(LOG_WARNING, "Ignoring any changes to '%s' (on reload) at line %d.\n", v->name, v->lineno);
17283    }
17284    if (dahdichan[0]) {
17285       /* The user has set 'dahdichan' */
17286       /*< \todo pass proper line number instead of 0 */
17287       if (build_channels(confp, dahdichan, reload, 0, &found_pseudo)) {
17288          return -1;
17289       }
17290    }
17291 
17292    /* mark the first channels of each DAHDI span to watch for their span alarms */
17293    for (tmp = iflist, y=-1; tmp; tmp = tmp->next) {
17294       if (!tmp->destroy && tmp->span != y) {
17295          tmp->manages_span_alarms = 1;
17296          y = tmp->span; 
17297       } else {
17298          tmp->manages_span_alarms = 0;
17299       }
17300    }
17301 
17302    /*< \todo why check for the pseudo in the per-channel section.
17303     * Any actual use for manual setup of the pseudo channel? */
17304    if (!found_pseudo && reload != 1) {
17305       /* use the default configuration for a channel, so
17306          that any settings from real configured channels
17307          don't "leak" into the pseudo channel config
17308       */
17309       struct dahdi_chan_conf conf = dahdi_chan_conf_default();
17310 
17311       if (conf.chan.cc_params) {
17312          tmp = mkintf(CHAN_PSEUDO, &conf, reload);
17313       } else {
17314          tmp = NULL;
17315       }
17316       if (tmp) {
17317          ast_verb(3, "Automatically generated pseudo channel\n");
17318       } else {
17319          ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
17320       }
17321       ast_cc_config_params_destroy(conf.chan.cc_params);
17322    }
17323    return 0;
17324 }
17325 
17326 /*!
17327  * \internal
17328  * \brief Deep copy struct dahdi_chan_conf.
17329  * \since 1.8
17330  *
17331  * \param dest Destination.
17332  * \param src Source.
17333  *
17334  * \return Nothing
17335  */
17336 static void deep_copy_dahdi_chan_conf(struct dahdi_chan_conf *dest, const struct dahdi_chan_conf *src)
17337 {
17338    struct ast_cc_config_params *cc_params;
17339 
17340    cc_params = dest->chan.cc_params;
17341    *dest = *src;
17342    dest->chan.cc_params = cc_params;
17343    ast_cc_copy_config_params(dest->chan.cc_params, src->chan.cc_params);
17344 }
17345 
17346 /*!
17347  * \internal
17348  * \brief Setup DAHDI channel driver.
17349  *
17350  * \param reload enum: load_module(0), reload(1), restart(2).
17351  * \param base_conf Default config parameters.  So cc_params can be properly destroyed.
17352  * \param conf Local config parameters.  So cc_params can be properly destroyed.
17353  *
17354  * \retval 0 on success.
17355  * \retval -1 on error.
17356  */
17357 static int setup_dahdi_int(int reload, struct dahdi_chan_conf *base_conf, struct dahdi_chan_conf *conf)
17358 {
17359    struct ast_config *cfg;
17360    struct ast_config *ucfg;
17361    struct ast_variable *v;
17362    struct ast_flags config_flags = { reload == 1 ? CONFIG_FLAG_FILEUNCHANGED : 0 };
17363    const char *cat;
17364    int res;
17365 
17366 #ifdef HAVE_PRI
17367    char *c;
17368    int spanno;
17369    int i;
17370    int logicalspan;
17371    int trunkgroup;
17372    int dchannels[SIG_PRI_NUM_DCHANS];
17373 #endif
17374 
17375    cfg = ast_config_load(config, config_flags);
17376 
17377    /* Error if we have no config file */
17378    if (!cfg) {
17379       ast_log(LOG_ERROR, "Unable to load config %s\n", config);
17380       return 0;
17381    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
17382       ucfg = ast_config_load("users.conf", config_flags);
17383       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
17384          return 0;
17385       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
17386          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
17387          return 0;
17388       }
17389       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
17390       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
17391          ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
17392          ast_config_destroy(ucfg);
17393          return 0;
17394       }
17395    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
17396       ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
17397       return 0;
17398    } else {
17399       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
17400       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
17401          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
17402          ast_config_destroy(cfg);
17403          return 0;
17404       }
17405    }
17406 
17407    /* It's a little silly to lock it, but we might as well just to be sure */
17408    ast_mutex_lock(&iflock);
17409 #ifdef HAVE_PRI
17410    if (reload != 1) {
17411       /* Process trunkgroups first */
17412       v = ast_variable_browse(cfg, "trunkgroups");
17413       while (v) {
17414          if (!strcasecmp(v->name, "trunkgroup")) {
17415             trunkgroup = atoi(v->value);
17416             if (trunkgroup > 0) {
17417                if ((c = strchr(v->value, ','))) {
17418                   i = 0;
17419                   memset(dchannels, 0, sizeof(dchannels));
17420                   while (c && (i < SIG_PRI_NUM_DCHANS)) {
17421                      dchannels[i] = atoi(c + 1);
17422                      if (dchannels[i] < 0) {
17423                         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);
17424                      } else
17425                         i++;
17426                      c = strchr(c + 1, ',');
17427                   }
17428                   if (i) {
17429                      if (pri_create_trunkgroup(trunkgroup, dchannels)) {
17430                         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);
17431                   } else
17432                         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");
17433                   } else
17434                      ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
17435                } else
17436                   ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
17437             } else
17438                ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of chan_dahdi.conf\n", v->lineno);
17439          } else if (!strcasecmp(v->name, "spanmap")) {
17440             spanno = atoi(v->value);
17441             if (spanno > 0) {
17442                if ((c = strchr(v->value, ','))) {
17443                   trunkgroup = atoi(c + 1);
17444                   if (trunkgroup > 0) {
17445                      if ((c = strchr(c + 1, ',')))
17446                         logicalspan = atoi(c + 1);
17447                      else
17448                         logicalspan = 0;
17449                      if (logicalspan >= 0) {
17450                         if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
17451                            ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
17452                      } else
17453                            ast_verb(2, "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
17454                      } else
17455                         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);
17456                   } else
17457                      ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of chan_dahdi.conf\n", v->lineno);
17458                } else
17459                   ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of chan_dahdi.conf\n", v->lineno);
17460             } else
17461                ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of chan_dahdi.conf\n", v->lineno);
17462          } else {
17463             ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
17464          }
17465          v = v->next;
17466       }
17467    }
17468 #endif
17469 
17470    /* Copy the default jb config over global_jbconf */
17471    memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
17472 
17473    mwimonitornotify[0] = '\0';
17474 
17475    v = ast_variable_browse(cfg, "channels");
17476    if ((res = process_dahdi(base_conf, "", v, reload, 0))) {
17477       ast_mutex_unlock(&iflock);
17478       ast_config_destroy(cfg);
17479       if (ucfg) {
17480          ast_config_destroy(ucfg);
17481       }
17482       return res;
17483    }
17484 
17485    /* Now get configuration from all normal sections in chan_dahdi.conf: */
17486    for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
17487       /* [channels] and [trunkgroups] are used. Let's also reserve
17488        * [globals] and [general] for future use
17489        */
17490       if (!strcasecmp(cat, "general") ||
17491          !strcasecmp(cat, "trunkgroups") ||
17492          !strcasecmp(cat, "globals") ||
17493          !strcasecmp(cat, "channels")) {
17494          continue;
17495       }
17496 
17497       /* Copy base_conf to conf. */
17498       deep_copy_dahdi_chan_conf(conf, base_conf);
17499 
17500       if ((res = process_dahdi(conf, cat, ast_variable_browse(cfg, cat), reload, PROC_DAHDI_OPT_NOCHAN))) {
17501          ast_mutex_unlock(&iflock);
17502          ast_config_destroy(cfg);
17503          if (ucfg) {
17504             ast_config_destroy(ucfg);
17505          }
17506          return res;
17507       }
17508    }
17509 
17510    ast_config_destroy(cfg);
17511 
17512    if (ucfg) {
17513       const char *chans;
17514 
17515       process_dahdi(base_conf, "", ast_variable_browse(ucfg, "general"), 1, 0);
17516 
17517       for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
17518          if (!strcasecmp(cat, "general")) {
17519             continue;
17520          }
17521 
17522          chans = ast_variable_retrieve(ucfg, cat, "dahdichan");
17523 
17524          if (ast_strlen_zero(chans)) {
17525             continue;
17526          }
17527 
17528          /* Copy base_conf to conf. */
17529          deep_copy_dahdi_chan_conf(conf, base_conf);
17530 
17531          if ((res = process_dahdi(conf, cat, ast_variable_browse(ucfg, cat), reload, PROC_DAHDI_OPT_NOCHAN | PROC_DAHDI_OPT_NOWARN))) {
17532             ast_config_destroy(ucfg);
17533             ast_mutex_unlock(&iflock);
17534             return res;
17535          }
17536       }
17537       ast_config_destroy(ucfg);
17538    }
17539    ast_mutex_unlock(&iflock);
17540 
17541 #ifdef HAVE_PRI
17542    if (reload != 1) {
17543       int x;
17544       for (x = 0; x < NUM_SPANS; x++) {
17545          if (pris[x].pri.pvts[0]) {
17546             prepare_pri(pris + x);
17547             if (sig_pri_start_pri(&pris[x].pri)) {
17548                ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
17549                return -1;
17550             } else
17551                ast_verb(2, "Starting D-Channel on span %d\n", x + 1);
17552          }
17553       }
17554    }
17555 #endif
17556 #if defined(HAVE_SS7)
17557    if (reload != 1) {
17558       int x;
17559       for (x = 0; x < NUM_SPANS; x++) {
17560          if (linksets[x].ss7.ss7) {
17561             linksets[x].ss7.calls = &dahdi_ss7_callbacks;
17562             if (ast_pthread_create(&linksets[x].ss7.master, NULL, ss7_linkset, &linksets[x].ss7)) {
17563                ast_log(LOG_ERROR, "Unable to start SS7 linkset on span %d\n", x + 1);
17564                return -1;
17565             } else
17566                ast_verb(2, "Starting SS7 linkset on span %d\n", x + 1);
17567          }
17568       }
17569    }
17570 #endif   /* defined(HAVE_SS7) */
17571 #ifdef HAVE_OPENR2
17572    if (reload != 1) {
17573       int x;
17574       for (x = 0; x < r2links_count; x++) {
17575          if (ast_pthread_create(&r2links[x]->r2master, NULL, mfcr2_monitor, r2links[x])) {
17576             ast_log(LOG_ERROR, "Unable to start R2 monitor on channel group %d\n", x + 1);
17577             return -1;
17578          } else {
17579             ast_verb(2, "Starting R2 monitor on channel group %d\n", x + 1);
17580          }
17581       }
17582    }
17583 #endif
17584    /* And start the monitor for the first time */
17585    restart_monitor();
17586    return 0;
17587 }
17588 
17589 /*!
17590  * \internal
17591  * \brief Setup DAHDI channel driver.
17592  *
17593  * \param reload enum: load_module(0), reload(1), restart(2).
17594  *
17595  * \retval 0 on success.
17596  * \retval -1 on error.
17597  */
17598 static int setup_dahdi(int reload)
17599 {
17600    int res;
17601    struct dahdi_chan_conf base_conf = dahdi_chan_conf_default();
17602    struct dahdi_chan_conf conf = dahdi_chan_conf_default();
17603 
17604    if (base_conf.chan.cc_params && conf.chan.cc_params) {
17605       res = setup_dahdi_int(reload, &base_conf, &conf);
17606    } else {
17607       res = -1;
17608    }
17609    ast_cc_config_params_destroy(base_conf.chan.cc_params);
17610    ast_cc_config_params_destroy(conf.chan.cc_params);
17611 
17612    return res;
17613 }
17614 
17615 /*!
17616  * \internal
17617  * \brief Callback used to generate the dahdi status tree.
17618  * \param[in] search The search pattern tree.
17619  * \retval NULL on error.
17620  * \retval non-NULL The generated tree.
17621  */
17622 static int dahdi_status_data_provider_get(const struct ast_data_search *search,
17623       struct ast_data *data_root)
17624 {
17625    int ctl, res, span;
17626    struct ast_data *data_span, *data_alarms;
17627    struct dahdi_spaninfo s;
17628 
17629    ctl = open("/dev/dahdi/ctl", O_RDWR);
17630    if (ctl < 0) {
17631       ast_log(LOG_ERROR, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
17632       return -1;
17633    }
17634    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
17635       s.spanno = span;
17636       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
17637       if (res) {
17638          continue;
17639       }
17640 
17641       data_span = ast_data_add_node(data_root, "span");
17642       if (!data_span) {
17643          continue;
17644       }
17645       ast_data_add_str(data_span, "description", s.desc);
17646 
17647       /* insert the alarms status */
17648       data_alarms = ast_data_add_node(data_span, "alarms");
17649       if (!data_alarms) {
17650          continue;
17651       }
17652 
17653       ast_data_add_bool(data_alarms, "BLUE", s.alarms & DAHDI_ALARM_BLUE);
17654       ast_data_add_bool(data_alarms, "YELLOW", s.alarms & DAHDI_ALARM_YELLOW);
17655       ast_data_add_bool(data_alarms, "RED", s.alarms & DAHDI_ALARM_RED);
17656       ast_data_add_bool(data_alarms, "LOOPBACK", s.alarms & DAHDI_ALARM_LOOPBACK);
17657       ast_data_add_bool(data_alarms, "RECOVER", s.alarms & DAHDI_ALARM_RECOVER);
17658       ast_data_add_bool(data_alarms, "NOTOPEN", s.alarms & DAHDI_ALARM_NOTOPEN);
17659 
17660       ast_data_add_int(data_span, "irqmisses", s.irqmisses);
17661       ast_data_add_int(data_span, "bpviol", s.bpvcount);
17662       ast_data_add_int(data_span, "crc4", s.crc4count);
17663       ast_data_add_str(data_span, "framing", s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
17664                      s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
17665                      s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
17666                      "CAS");
17667       ast_data_add_str(data_span, "coding",  s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
17668                      s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
17669                      s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
17670                      "Unknown");
17671       ast_data_add_str(data_span, "options", s.lineconfig & DAHDI_CONFIG_CRC4 ?
17672                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
17673                      s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "");
17674       ast_data_add_str(data_span, "lbo", lbostr[s.lbo]);
17675 
17676       /* if this span doesn't match remove it. */
17677       if (!ast_data_search_match(search, data_span)) {
17678          ast_data_remove_node(data_root, data_span);
17679       }
17680    }
17681    close(ctl);
17682 
17683    return 0;
17684 }
17685 
17686 /*!
17687  * \internal
17688  * \brief Callback used to generate the dahdi channels tree.
17689  * \param[in] search The search pattern tree.
17690  * \retval NULL on error.
17691  * \retval non-NULL The generated tree.
17692  */
17693 static int dahdi_channels_data_provider_get(const struct ast_data_search *search,
17694       struct ast_data *data_root)
17695 {
17696    struct dahdi_pvt *tmp;
17697    struct ast_data *data_channel;
17698 
17699    ast_mutex_lock(&iflock);
17700    for (tmp = iflist; tmp; tmp = tmp->next) {
17701       data_channel = ast_data_add_node(data_root, "channel");
17702       if (!data_channel) {
17703          continue;
17704       }
17705 
17706       ast_data_add_structure(dahdi_pvt, data_channel, tmp);
17707 
17708       /* if this channel doesn't match remove it. */
17709       if (!ast_data_search_match(search, data_channel)) {
17710          ast_data_remove_node(data_root, data_channel);
17711       }
17712    }
17713    ast_mutex_unlock(&iflock);
17714 
17715    return 0;
17716 }
17717 
17718 /*!
17719  * \internal
17720  * \brief Callback used to generate the dahdi channels tree.
17721  * \param[in] search The search pattern tree.
17722  * \retval NULL on error.
17723  * \retval non-NULL The generated tree.
17724  */
17725 static int dahdi_version_data_provider_get(const struct ast_data_search *search,
17726       struct ast_data *data_root)
17727 {
17728    int pseudo_fd = -1;
17729    struct dahdi_versioninfo vi = {
17730       .version = "Unknown",
17731       .echo_canceller = "Unknown"
17732    };
17733 
17734    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
17735       ast_log(LOG_ERROR, "Failed to open control file to get version.\n");
17736       return -1;
17737    }
17738 
17739    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi)) {
17740       ast_log(LOG_ERROR, "Failed to get DAHDI version: %s\n", strerror(errno));
17741    }
17742 
17743    close(pseudo_fd);
17744 
17745    ast_data_add_str(data_root, "value", vi.version);
17746    ast_data_add_str(data_root, "echocanceller", vi.echo_canceller);
17747 
17748    return 0;
17749 }
17750 
17751 static const struct ast_data_handler dahdi_status_data_provider = {
17752    .version = AST_DATA_HANDLER_VERSION,
17753    .get = dahdi_status_data_provider_get
17754 };
17755 
17756 static const struct ast_data_handler dahdi_channels_data_provider = {
17757    .version = AST_DATA_HANDLER_VERSION,
17758    .get = dahdi_channels_data_provider_get
17759 };
17760 
17761 static const struct ast_data_handler dahdi_version_data_provider = {
17762    .version = AST_DATA_HANDLER_VERSION,
17763    .get = dahdi_version_data_provider_get
17764 };
17765 
17766 static const struct ast_data_entry dahdi_data_providers[] = {
17767    AST_DATA_ENTRY("asterisk/channel/dahdi/status", &dahdi_status_data_provider),
17768    AST_DATA_ENTRY("asterisk/channel/dahdi/channels", &dahdi_channels_data_provider),
17769    AST_DATA_ENTRY("asterisk/channel/dahdi/version", &dahdi_version_data_provider)
17770 };
17771 
17772 static int load_module(void)
17773 {
17774    int res;
17775 #if defined(HAVE_PRI) || defined(HAVE_SS7)
17776    int y;
17777 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
17778 
17779 #ifdef HAVE_PRI
17780    memset(pris, 0, sizeof(pris));
17781    for (y = 0; y < NUM_SPANS; y++) {
17782       sig_pri_init_pri(&pris[y].pri);
17783    }
17784    pri_set_error(dahdi_pri_error);
17785    pri_set_message(dahdi_pri_message);
17786    ast_register_application_xml(dahdi_send_keypad_facility_app, dahdi_send_keypad_facility_exec);
17787 #ifdef HAVE_PRI_PROG_W_CAUSE
17788    ast_register_application_xml(dahdi_send_callrerouting_facility_app, dahdi_send_callrerouting_facility_exec);
17789 #endif
17790 #if defined(HAVE_PRI_CCSS)
17791    if (ast_cc_agent_register(&dahdi_pri_cc_agent_callbacks)
17792       || ast_cc_monitor_register(&dahdi_pri_cc_monitor_callbacks)) {
17793       __unload_module();
17794       return AST_MODULE_LOAD_FAILURE;
17795    }
17796 #endif   /* defined(HAVE_PRI_CCSS) */
17797    if (sig_pri_load(
17798 #if defined(HAVE_PRI_CCSS)
17799       dahdi_pri_cc_type
17800 #else
17801       NULL
17802 #endif   /* defined(HAVE_PRI_CCSS) */
17803       )) {
17804       __unload_module();
17805       return AST_MODULE_LOAD_FAILURE;
17806    }
17807 #endif
17808 #if defined(HAVE_SS7)
17809    memset(linksets, 0, sizeof(linksets));
17810    for (y = 0; y < NUM_SPANS; y++) {
17811       sig_ss7_init_linkset(&linksets[y].ss7);
17812    }
17813    ss7_set_error(dahdi_ss7_error);
17814    ss7_set_message(dahdi_ss7_message);
17815 #endif   /* defined(HAVE_SS7) */
17816    res = setup_dahdi(0);
17817    /* Make sure we can register our DAHDI channel type */
17818    if (res)
17819       return AST_MODULE_LOAD_DECLINE;
17820    if (ast_channel_register(&dahdi_tech)) {
17821       ast_log(LOG_ERROR, "Unable to register channel class 'DAHDI'\n");
17822       __unload_module();
17823       return AST_MODULE_LOAD_FAILURE;
17824    }
17825 #ifdef HAVE_PRI
17826    ast_cli_register_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
17827 #endif
17828 #if defined(HAVE_SS7)
17829    ast_cli_register_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
17830 #endif   /* defined(HAVE_SS7) */
17831 #ifdef HAVE_OPENR2
17832    ast_cli_register_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
17833    ast_register_application_xml(dahdi_accept_r2_call_app, dahdi_accept_r2_call_exec);
17834 #endif
17835 
17836    ast_cli_register_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
17837    /* register all the data providers */
17838    ast_data_register_multiple(dahdi_data_providers, ARRAY_LEN(dahdi_data_providers));
17839    memset(round_robin, 0, sizeof(round_robin));
17840    ast_manager_register_xml("DAHDITransfer", 0, action_transfer);
17841    ast_manager_register_xml("DAHDIHangup", 0, action_transferhangup);
17842    ast_manager_register_xml("DAHDIDialOffhook", 0, action_dahdidialoffhook);
17843    ast_manager_register_xml("DAHDIDNDon", 0, action_dahdidndon);
17844    ast_manager_register_xml("DAHDIDNDoff", 0, action_dahdidndoff);
17845    ast_manager_register_xml("DAHDIShowChannels", 0, action_dahdishowchannels);
17846    ast_manager_register_xml("DAHDIRestart", 0, action_dahdirestart);
17847 
17848    ast_cond_init(&ss_thread_complete, NULL);
17849 
17850    return res;
17851 }
17852 
17853 static int dahdi_sendtext(struct ast_channel *c, const char *text)
17854 {
17855 #define  END_SILENCE_LEN 400
17856 #define  HEADER_MS 50
17857 #define  TRAILER_MS 5
17858 #define  HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
17859 #define  ASCII_BYTES_PER_CHAR 80
17860 
17861    unsigned char *buf,*mybuf;
17862    struct dahdi_pvt *p = c->tech_pvt;
17863    struct pollfd fds[1];
17864    int size,res,fd,len,x;
17865    int bytes=0;
17866    /* Initial carrier (imaginary) */
17867    float cr = 1.0;
17868    float ci = 0.0;
17869    float scont = 0.0;
17870    int idx;
17871 
17872    idx = dahdi_get_index(c, p, 0);
17873    if (idx < 0) {
17874       ast_log(LOG_WARNING, "Huh?  I don't exist?\n");
17875       return -1;
17876    }
17877    if (!text[0]) return(0); /* if nothing to send, don't */
17878    if ((!p->tdd) && (!p->mate)) return(0);  /* if not in TDD mode, just return */
17879    if (p->mate)
17880       buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
17881    else
17882       buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
17883    if (!buf)
17884       return -1;
17885    mybuf = buf;
17886    if (p->mate) {
17887       int codec = AST_LAW(p);
17888       for (x = 0; x < HEADER_MS; x++) {   /* 50 ms of Mark */
17889          PUT_CLID_MARKMS;
17890       }
17891       /* Put actual message */
17892       for (x = 0; text[x]; x++) {
17893          PUT_CLID(text[x]);
17894       }
17895       for (x = 0; x < TRAILER_MS; x++) {  /* 5 ms of Mark */
17896          PUT_CLID_MARKMS;
17897       }
17898       len = bytes;
17899       buf = mybuf;
17900    } else {
17901       len = tdd_generate(p->tdd, buf, text);
17902       if (len < 1) {
17903          ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
17904          ast_free(mybuf);
17905          return -1;
17906       }
17907    }
17908    memset(buf + len, 0x7f, END_SILENCE_LEN);
17909    len += END_SILENCE_LEN;
17910    fd = p->subs[idx].dfd;
17911    while (len) {
17912       if (ast_check_hangup(c)) {
17913          ast_free(mybuf);
17914          return -1;
17915       }
17916       size = len;
17917       if (size > READ_SIZE)
17918          size = READ_SIZE;
17919       fds[0].fd = fd;
17920       fds[0].events = POLLOUT | POLLPRI;
17921       fds[0].revents = 0;
17922       res = poll(fds, 1, -1);
17923       if (!res) {
17924          ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
17925          continue;
17926       }
17927       /* if got exception */
17928       if (fds[0].revents & POLLPRI) {
17929          ast_free(mybuf);
17930          return -1;
17931       }
17932       if (!(fds[0].revents & POLLOUT)) {
17933          ast_debug(1, "write fd not ready on channel %d\n", p->channel);
17934          continue;
17935       }
17936       res = write(fd, buf, size);
17937       if (res != size) {
17938          if (res == -1) {
17939             ast_free(mybuf);
17940             return -1;
17941          }
17942          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
17943          break;
17944       }
17945       len -= size;
17946       buf += size;
17947    }
17948    ast_free(mybuf);
17949    return(0);
17950 }
17951 
17952 
17953 static int reload(void)
17954 {
17955    int res = 0;
17956 
17957    res = setup_dahdi(1);
17958    if (res) {
17959       ast_log(LOG_WARNING, "Reload of chan_dahdi.so is unsuccessful!\n");
17960       return -1;
17961    }
17962    return 0;
17963 }
17964 
17965 /* This is a workaround so that menuselect displays a proper description
17966  * AST_MODULE_INFO(, , "DAHDI Telephony"
17967  */
17968 
17969 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, tdesc,
17970    .load = load_module,
17971    .unload = unload_module,
17972    .reload = reload,
17973    .load_pri = AST_MODPRI_CHANNEL_DRIVER,
17974       .nonoptreq = "res_smdi",
17975    );

Generated on Sat Mar 26 11:06:57 2011 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.9