Sat Mar 26 11:07:43 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 - 2006, 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    <depend>res_smdi</depend>
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: 294822 $")
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 <math.h>
00061 #include <ctype.h>
00062 
00063 #include <dahdi/user.h>
00064 #include <dahdi/tonezone.h>
00065 
00066 #ifdef HAVE_PRI
00067 #include <libpri.h>
00068 #endif
00069 
00070 #ifdef HAVE_SS7
00071 #include <libss7.h>
00072 #endif
00073 
00074 #ifdef HAVE_OPENR2
00075 #include <openr2.h>
00076 #endif
00077 
00078 #include "asterisk/lock.h"
00079 #include "asterisk/channel.h"
00080 #include "asterisk/config.h"
00081 #include "asterisk/module.h"
00082 #include "asterisk/pbx.h"
00083 #include "asterisk/file.h"
00084 #include "asterisk/ulaw.h"
00085 #include "asterisk/alaw.h"
00086 #include "asterisk/callerid.h"
00087 #include "asterisk/adsi.h"
00088 #include "asterisk/cli.h"
00089 #include "asterisk/cdr.h"
00090 #include "asterisk/features.h"
00091 #include "asterisk/musiconhold.h"
00092 #include "asterisk/say.h"
00093 #include "asterisk/tdd.h"
00094 #include "asterisk/app.h"
00095 #include "asterisk/dsp.h"
00096 #include "asterisk/astdb.h"
00097 #include "asterisk/manager.h"
00098 #include "asterisk/causes.h"
00099 #include "asterisk/term.h"
00100 #include "asterisk/utils.h"
00101 #include "asterisk/transcap.h"
00102 #include "asterisk/stringfields.h"
00103 #include "asterisk/abstract_jb.h"
00104 #include "asterisk/smdi.h"
00105 #include "asterisk/astobj.h"
00106 #include "asterisk/event.h"
00107 #include "asterisk/devicestate.h"
00108 #include "asterisk/paths.h"
00109 
00110 /*** DOCUMENTATION
00111    <application name="DAHDISendKeypadFacility" language="en_US">
00112       <synopsis>
00113          Send digits out of band over a PRI.
00114       </synopsis>
00115       <syntax>
00116          <parameter name="digits" required="true" />
00117       </syntax>
00118       <description>
00119          <para>This application will send the given string of digits in a Keypad
00120          Facility IE over the current channel.</para>
00121       </description>
00122    </application>
00123    <application name="DAHDISendCallreroutingFacility" language="en_US">
00124       <synopsis>
00125          Send QSIG call rerouting facility over a PRI.
00126       </synopsis>
00127       <syntax argsep=",">
00128          <parameter name="destination" required="true">
00129             <para>Destination number.</para>
00130          </parameter>
00131          <parameter name="original">
00132             <para>Original called number.</para>
00133          </parameter>
00134          <parameter name="reason">
00135             <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
00136          </parameter>
00137       </syntax>
00138       <description>
00139          <para>This application will send a Callrerouting Facility IE over the
00140          current channel.</para>
00141       </description>
00142    </application>
00143    <application name="DAHDIAcceptR2Call" language="en_US">
00144       <synopsis>
00145          Accept an R2 call if its not already accepted (you still need to answer it)
00146       </synopsis>
00147       <syntax>
00148          <parameter name="charge" required="true">
00149             <para>Yes or No.</para>
00150             <para>Whether you want to accept the call with charge or without charge.</para>
00151          </parameter>
00152       </syntax>
00153       <description>
00154          <para>This application will Accept the R2 call either with charge or no charge.</para>
00155       </description>
00156    </application>
00157  ***/
00158 
00159 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
00160 
00161 static const char *lbostr[] = {
00162 "0 db (CSU)/0-133 feet (DSX-1)",
00163 "133-266 feet (DSX-1)",
00164 "266-399 feet (DSX-1)",
00165 "399-533 feet (DSX-1)",
00166 "533-655 feet (DSX-1)",
00167 "-7.5db (CSU)",
00168 "-15db (CSU)",
00169 "-22.5db (CSU)"
00170 };
00171 
00172 /*! Global jitterbuffer configuration - by default, jb is disabled */
00173 static struct ast_jb_conf default_jbconf =
00174 {
00175    .flags = 0,
00176    .max_size = -1,
00177    .resync_threshold = -1,
00178    .impl = "",
00179    .target_extra = -1,
00180 };
00181 static struct ast_jb_conf global_jbconf;
00182 
00183 /* define this to send PRI user-user information elements */
00184 #undef SUPPORT_USERUSER
00185 
00186 /*!
00187  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
00188  * the user hangs up to reset the state machine so ring works properly.
00189  * This is used to be able to support kewlstart by putting the zhone in
00190  * groundstart mode since their forward disconnect supervision is entirely
00191  * broken even though their documentation says it isn't and their support
00192  * is entirely unwilling to provide any assistance with their channel banks
00193  * even though their web site says they support their products for life.
00194  */
00195 /* #define ZHONE_HACK */
00196 
00197 /*! \note
00198  * Define if you want to check the hook state for an FXO (FXS signalled) interface
00199  * before dialing on it.  Certain FXO interfaces always think they're out of
00200  * service with this method however.
00201  */
00202 /* #define DAHDI_CHECK_HOOKSTATE */
00203 
00204 /*! \brief Typically, how many rings before we should send Caller*ID */
00205 #define DEFAULT_CIDRINGS 1
00206 
00207 #define CHANNEL_PSEUDO -12
00208 
00209 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
00210 
00211 
00212 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
00213 #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))
00214 
00215 static const char tdesc[] = "DAHDI Telephony Driver"
00216 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
00217    " w/"
00218 #endif
00219 #ifdef HAVE_PRI
00220    "PRI"
00221 #endif
00222 #ifdef HAVE_SS7
00223    #ifdef HAVE_PRI
00224    " & SS7"
00225    #else
00226    "SS7"
00227    #endif
00228 #endif
00229 #ifdef HAVE_OPENR2
00230    #if defined(HAVE_PRI) || defined(HAVE_SS7)
00231    " & MFC/R2"
00232    #else
00233    "MFC/R2"
00234    #endif
00235 #endif
00236 ;
00237 
00238 static const char config[] = "chan_dahdi.conf";
00239 
00240 #define SIG_EM    DAHDI_SIG_EM
00241 #define SIG_EMWINK   (0x0100000 | DAHDI_SIG_EM)
00242 #define SIG_FEATD (0x0200000 | DAHDI_SIG_EM)
00243 #define  SIG_FEATDMF (0x0400000 | DAHDI_SIG_EM)
00244 #define  SIG_FEATB   (0x0800000 | DAHDI_SIG_EM)
00245 #define  SIG_E911 (0x1000000 | DAHDI_SIG_EM)
00246 #define  SIG_FEATDMF_TA (0x2000000 | DAHDI_SIG_EM)
00247 #define  SIG_FGC_CAMA   (0x4000000 | DAHDI_SIG_EM)
00248 #define  SIG_FGC_CAMAMF (0x8000000 | DAHDI_SIG_EM)
00249 #define SIG_FXSLS DAHDI_SIG_FXSLS
00250 #define SIG_FXSGS DAHDI_SIG_FXSGS
00251 #define SIG_FXSKS DAHDI_SIG_FXSKS
00252 #define SIG_FXOLS DAHDI_SIG_FXOLS
00253 #define SIG_FXOGS DAHDI_SIG_FXOGS
00254 #define SIG_FXOKS DAHDI_SIG_FXOKS
00255 #define SIG_PRI      DAHDI_SIG_CLEAR
00256 #define SIG_BRI      (0x2000000 | DAHDI_SIG_CLEAR)
00257 #define SIG_BRI_PTMP (0X4000000 | DAHDI_SIG_CLEAR)
00258 #define SIG_SS7      (0x1000000 | DAHDI_SIG_CLEAR)
00259 #define SIG_MFCR2    DAHDI_SIG_CAS
00260 #define  SIG_SF      DAHDI_SIG_SF
00261 #define SIG_SFWINK   (0x0100000 | DAHDI_SIG_SF)
00262 #define SIG_SF_FEATD (0x0200000 | DAHDI_SIG_SF)
00263 #define  SIG_SF_FEATDMF (0x0400000 | DAHDI_SIG_SF)
00264 #define  SIG_SF_FEATB   (0x0800000 | DAHDI_SIG_SF)
00265 #define SIG_EM_E1 DAHDI_SIG_EM_E1
00266 #define SIG_GR303FXOKS  (0x0100000 | DAHDI_SIG_FXOKS)
00267 #define SIG_GR303FXSKS  (0x0100000 | DAHDI_SIG_FXSKS)
00268 
00269 #ifdef LOTS_OF_SPANS
00270 #define NUM_SPANS DAHDI_MAX_SPANS
00271 #else
00272 #define NUM_SPANS       32
00273 #endif
00274 #define NUM_DCHANS      4  /*!< No more than 4 d-channels */
00275 #define MAX_CHANNELS 672      /*!< No more than a DS3 per trunk group */
00276 
00277 #define CHAN_PSEUDO  -2
00278 
00279 #define DCHAN_PROVISIONED (1 << 0)
00280 #define DCHAN_NOTINALARM  (1 << 1)
00281 #define DCHAN_UP          (1 << 2)
00282 
00283 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
00284 
00285 /* Overlap dialing option types */
00286 #define DAHDI_OVERLAPDIAL_NONE 0
00287 #define DAHDI_OVERLAPDIAL_OUTGOING 1
00288 #define DAHDI_OVERLAPDIAL_INCOMING 2
00289 #define DAHDI_OVERLAPDIAL_BOTH (DAHDI_OVERLAPDIAL_INCOMING|DAHDI_OVERLAPDIAL_OUTGOING)
00290 
00291 #define CALLPROGRESS_PROGRESS    1
00292 #define CALLPROGRESS_FAX_OUTGOING   2
00293 #define CALLPROGRESS_FAX_INCOMING   4
00294 #define CALLPROGRESS_FAX      (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
00295 
00296 static char defaultcic[64] = "";
00297 static char defaultozz[64] = "";
00298 
00299 static char parkinglot[AST_MAX_EXTENSION] = "";    /*!< Default parking lot for this channel */
00300 
00301 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
00302 static char mwimonitornotify[PATH_MAX] = "";
00303 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
00304 static int  mwisend_rpas = 0;
00305 #endif
00306 
00307 static char progzone[10] = "";
00308 
00309 static int usedistinctiveringdetection = 0;
00310 static int distinctiveringaftercid = 0;
00311 
00312 static int numbufs = 4;
00313 
00314 static int mwilevel = 512;
00315 
00316 #ifdef HAVE_PRI
00317 static struct ast_channel inuse;
00318 #ifdef PRI_GETSET_TIMERS
00319 static int pritimers[PRI_MAX_TIMERS];
00320 #endif
00321 static int pridebugfd = -1;
00322 static char pridebugfilename[1024] = "";
00323 #endif
00324 
00325 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
00326 static int firstdigittimeout = 16000;
00327 
00328 /*! \brief How long to wait for following digits (FXO logic) */
00329 static int gendigittimeout = 8000;
00330 
00331 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
00332 static int matchdigittimeout = 3000;
00333 
00334 /*! \brief Protect the interface list (of dahdi_pvt's) */
00335 AST_MUTEX_DEFINE_STATIC(iflock);
00336 
00337 /* QSIG channel mapping option types */
00338 #define DAHDI_CHAN_MAPPING_PHYSICAL 0
00339 #define DAHDI_CHAN_MAPPING_LOGICAL  1
00340 
00341 
00342 static int ifcount = 0;
00343 
00344 #ifdef HAVE_PRI
00345 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
00346 #endif
00347 
00348 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00349    when it's doing something critical. */
00350 AST_MUTEX_DEFINE_STATIC(monlock);
00351 
00352 /*! \brief This is the thread for the monitor which checks for input on the channels
00353    which are not currently in use. */
00354 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00355 static ast_cond_t ss_thread_complete;
00356 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
00357 AST_MUTEX_DEFINE_STATIC(restart_lock);
00358 static int ss_thread_count = 0;
00359 static int num_restart_pending = 0;
00360 
00361 static int restart_monitor(void);
00362 
00363 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);
00364 
00365 static int dahdi_sendtext(struct ast_channel *c, const char *text);
00366 
00367 static void mwi_event_cb(const struct ast_event *event, void *userdata)
00368 {
00369    /* This module does not handle MWI in an event-based manner.  However, it
00370     * subscribes to MWI for each mailbox that is configured so that the core
00371     * knows that we care about it.  Then, chan_dahdi will get the MWI from the
00372     * event cache instead of checking the mailbox directly. */
00373 }
00374 
00375 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
00376 static inline int dahdi_get_event(int fd)
00377 {
00378    int j;
00379    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00380       return -1;
00381    return j;
00382 }
00383 
00384 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
00385 static inline int dahdi_wait_event(int fd)
00386 {
00387    int i, j = 0;
00388    i = DAHDI_IOMUX_SIGEVENT;
00389    if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
00390       return -1;
00391    if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
00392       return -1;
00393    return j;
00394 }
00395 
00396 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
00397 #define READ_SIZE 160
00398 
00399 #define MASK_AVAIL      (1 << 0) /*!< Channel available for PRI use */
00400 #define MASK_INUSE      (1 << 1) /*!< Channel currently in use */
00401 
00402 #define CALLWAITING_SILENT_SAMPLES  ( (300 * 8) / READ_SIZE) /*!< 300 ms */
00403 #define CALLWAITING_REPEAT_SAMPLES  ( (10000 * 8) / READ_SIZE) /*!< 10,000 ms */
00404 #define CIDCW_EXPIRE_SAMPLES     ( (500 * 8) / READ_SIZE) /*!< 500 ms */
00405 #define MIN_MS_SINCE_FLASH       ( (2000) )  /*!< 2000 ms */
00406 #define DEFAULT_RINGT            ( (8000 * 8) / READ_SIZE) /*!< 8,000 ms */
00407 
00408 struct dahdi_pvt;
00409 
00410 /*!
00411  * \brief Configured ring timeout base.
00412  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
00413  */
00414 static int ringt_base = DEFAULT_RINGT;
00415 
00416 #ifdef HAVE_SS7
00417 
00418 #define LINKSTATE_INALARM  (1 << 0)
00419 #define LINKSTATE_STARTING (1 << 1)
00420 #define LINKSTATE_UP    (1 << 2)
00421 #define LINKSTATE_DOWN     (1 << 3)
00422 
00423 #define SS7_NAI_DYNAMIC    -1
00424 
00425 #define LINKSET_FLAG_EXPLICITACM (1 << 0)
00426 
00427 struct dahdi_ss7 {
00428    pthread_t master;                /*!< Thread of master */
00429    ast_mutex_t lock;
00430    int fds[NUM_DCHANS];
00431    int numsigchans;
00432    int linkstate[NUM_DCHANS];
00433    int numchans;
00434    int type;
00435    enum {
00436       LINKSET_STATE_DOWN = 0,
00437       LINKSET_STATE_UP
00438    } state;
00439    char called_nai;                 /*!< Called Nature of Address Indicator */
00440    char calling_nai;                /*!< Calling Nature of Address Indicator */
00441    char internationalprefix[10];             /*!< country access code ('00' for european dialplans) */
00442    char nationalprefix[10];               /*!< area access code ('0' for european dialplans) */
00443    char subscriberprefix[20];             /*!< area access code + area code ('0'+area code for european dialplans) */
00444    char unknownprefix[20];                /*!< for unknown dialplans */
00445    struct ss7 *ss7;
00446    struct dahdi_pvt *pvts[MAX_CHANNELS];           /*!< Member channel pvt structs */
00447    int flags;                    /*!< Linkset flags */
00448 };
00449 
00450 static struct dahdi_ss7 linksets[NUM_SPANS];
00451 
00452 static int cur_ss7type = -1;
00453 static int cur_linkset = -1;
00454 static int cur_pointcode = -1;
00455 static int cur_cicbeginswith = -1;
00456 static int cur_adjpointcode = -1;
00457 static int cur_networkindicator = -1;
00458 static int cur_defaultdpc = -1;
00459 #endif /* HAVE_SS7 */
00460 
00461 #ifdef HAVE_OPENR2
00462 struct dahdi_mfcr2 {
00463    pthread_t r2master;            /*!< Thread of master */
00464    openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
00465    struct dahdi_pvt *pvts[MAX_CHANNELS];     /*!< Member channel pvt structs */
00466    int numchans;                          /*!< Number of channels in this R2 block */
00467    int monitored_count;                   /*!< Number of channels being monitored */
00468 };
00469 
00470 struct dahdi_mfcr2_conf {
00471    openr2_variant_t variant;
00472    int mfback_timeout;
00473    int metering_pulse_timeout;
00474    int max_ani;
00475    int max_dnis;
00476    signed int get_ani_first:2;
00477 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
00478    signed int skip_category_request:2;
00479 #endif
00480    unsigned int call_files:1;
00481    unsigned int allow_collect_calls:1;
00482    unsigned int charge_calls:1;
00483    unsigned int accept_on_offer:1;
00484    unsigned int forced_release:1;
00485    unsigned int double_answer:1;
00486    signed int immediate_accept:2;
00487    char logdir[OR2_MAX_PATH];
00488    char r2proto_file[OR2_MAX_PATH];
00489    openr2_log_level_t loglevel;
00490    openr2_calling_party_category_t category;
00491 };
00492 
00493 /* malloc'd array of malloc'd r2links */
00494 static struct dahdi_mfcr2 **r2links;
00495 /* how many r2links have been malloc'd */
00496 static int r2links_count = 0;
00497 
00498 #endif /* HAVE_OPENR2 */
00499 
00500 #ifdef HAVE_PRI
00501 
00502 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
00503 #define PRI_CHANNEL(p) ((p) & 0xff)
00504 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
00505 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
00506 
00507 struct dahdi_pri {
00508    pthread_t master;                /*!< Thread of master */
00509    ast_mutex_t lock;                /*!< Mutex */
00510    char idleext[AST_MAX_EXTENSION];          /*!< Where to idle extra calls */
00511    char idlecontext[AST_MAX_CONTEXT];           /*!< What context to use for idle */
00512    char idledial[AST_MAX_EXTENSION];            /*!< What to dial before dumping */
00513    int minunused;                   /*!< Min # of channels to keep empty */
00514    int minidle;                     /*!< Min # of "idling" calls to keep active */
00515    int nodetype;                    /*!< Node type */
00516    int switchtype;                     /*!< Type of switch to emulate */
00517    int nsf;                   /*!< Network-Specific Facilities */
00518    int dialplan;                    /*!< Dialing plan */
00519    int localdialplan;                  /*!< Local dialing plan */
00520    char internationalprefix[10];             /*!< country access code ('00' for european dialplans) */
00521    char nationalprefix[10];               /*!< area access code ('0' for european dialplans) */
00522    char localprefix[20];                  /*!< area access code + area code ('0'+area code for european dialplans) */
00523    char privateprefix[20];                /*!< for private dialplans */
00524    char unknownprefix[20];                /*!< for unknown dialplans */
00525    int dchannels[NUM_DCHANS];             /*!< What channel are the dchannels on */
00526    int trunkgroup;                     /*!< What our trunkgroup is */
00527    int mastertrunkgroup;                  /*!< What trunk group is our master */
00528    int prilogicalspan;                 /*!< Logical span number within trunk group */
00529    int numchans;                    /*!< Num of channels we represent */
00530    int overlapdial;                 /*!< In overlap dialing mode */
00531    int qsigchannelmapping;                /*!< QSIG channel mapping type */
00532    int discardremoteholdretrieval;              /*!< shall remote hold or remote retrieval notifications be discarded? */
00533    int facilityenable;                 /*!< Enable facility IEs */
00534    struct pri *dchans[NUM_DCHANS];              /*!< Actual d-channels */
00535    int dchanavail[NUM_DCHANS];               /*!< Whether each channel is available */
00536    struct pri *pri;                 /*!< Currently active D-channel */
00537    /*! \brief TRUE if to dump PRI event info (Tested but never set) */
00538    int debug;
00539    int fds[NUM_DCHANS];                /*!< FD's for d-channels */
00540    /*! \brief Value set but not used */
00541    int offset;
00542    /*! \brief Span number put into user output messages */
00543    int span;
00544    /*! \brief TRUE if span is being reset/restarted */
00545    int resetting;
00546    /*! \brief Current position during a reset (-1 if not started) */
00547    int resetpos;
00548 #ifdef HAVE_PRI_INBANDDISCONNECT
00549    unsigned int inbanddisconnect:1;          /*!< Should we support inband audio after receiving DISCONNECT? */
00550 #endif
00551    /*! TRUE if we have already whined about no D channels available. */
00552    unsigned int no_d_channels:1;
00553    time_t lastreset;                /*!< time when unused channels were last reset */
00554    long resetinterval;                 /*!< Interval (in seconds) for resetting unused channels */
00555    /*! \brief ISDN signalling type (SIG_PRI, SIG_BRI, SIG_BRI_PTMP, etc...) */
00556    int sig;
00557    struct dahdi_pvt *pvts[MAX_CHANNELS];           /*!< Member channel pvt structs */
00558    struct dahdi_pvt *crvs;                /*!< Member CRV structs */
00559    struct dahdi_pvt *crvend;                 /*!< Pointer to end of CRV structs */
00560 };
00561 
00562 
00563 static struct dahdi_pri pris[NUM_SPANS];
00564 
00565 #if 0
00566 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
00567 #else
00568 #define DEFAULT_PRI_DEBUG 0
00569 #endif
00570 
00571 static inline void pri_rel(struct dahdi_pri *pri)
00572 {
00573    ast_mutex_unlock(&pri->lock);
00574 }
00575 
00576 #else
00577 /*! Shut up the compiler */
00578 struct dahdi_pri;
00579 #endif
00580 
00581 #define SUB_REAL  0        /*!< Active call */
00582 #define SUB_CALLWAIT 1        /*!< Call-Waiting call on hold */
00583 #define SUB_THREEWAY 2        /*!< Three-way call */
00584 
00585 /* Polarity states */
00586 #define POLARITY_IDLE   0
00587 #define POLARITY_REV    1
00588 
00589 
00590 struct distRingData {
00591    int ring[3];
00592    int range;
00593 };
00594 struct ringContextData {
00595    char contextData[AST_MAX_CONTEXT];
00596 };
00597 struct dahdi_distRings {
00598    struct distRingData ringnum[3];
00599    struct ringContextData ringContext[3];
00600 };
00601 
00602 static char *subnames[] = {
00603    "Real",
00604    "Callwait",
00605    "Threeway"
00606 };
00607 
00608 struct dahdi_subchannel {
00609    int dfd;
00610    struct ast_channel *owner;
00611    int chan;
00612    short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
00613    struct ast_frame f;     /*!< One frame for each channel.  How did this ever work before? */
00614    unsigned int needringing:1;
00615    unsigned int needbusy:1;
00616    unsigned int needcongestion:1;
00617    unsigned int needcallerid:1;
00618    unsigned int needanswer:1;
00619    unsigned int needflash:1;
00620    unsigned int needhold:1;
00621    unsigned int needunhold:1;
00622    unsigned int linear:1;
00623    unsigned int inthreeway:1;
00624    struct dahdi_confinfo curconf;
00625 };
00626 
00627 #define CONF_USER_REAL     (1 << 0)
00628 #define CONF_USER_THIRDCALL   (1 << 1)
00629 
00630 #define MAX_SLAVES   4
00631 
00632 /* States for sending MWI message
00633  * First three states are required for send Ring Pulse Alert Signal
00634  */
00635 typedef enum {
00636    MWI_SEND_NULL = 0,
00637    MWI_SEND_SA,
00638    MWI_SEND_SA_WAIT,
00639    MWI_SEND_PAUSE,
00640    MWI_SEND_SPILL,
00641    MWI_SEND_CLEANUP,
00642    MWI_SEND_DONE,
00643 } mwisend_states;
00644 
00645 struct mwisend_info {
00646    struct   timeval  pause;
00647    mwisend_states    mwisend_current;
00648 };
00649 
00650 static struct dahdi_pvt {
00651    ast_mutex_t lock;             /*!< Channel private lock. */
00652    struct ast_channel *owner;       /*!< Our current active owner (if applicable) */
00653                      /*!< Up to three channels can be associated with this call */
00654 
00655    struct dahdi_subchannel sub_unused;    /*!< Just a safety precaution */
00656    struct dahdi_subchannel subs[3];       /*!< Sub-channels */
00657    struct dahdi_confinfo saveconf;        /*!< Saved conference info */
00658 
00659    struct dahdi_pvt *slaves[MAX_SLAVES];     /*!< Slave to us (follows our conferencing) */
00660    struct dahdi_pvt *master;           /*!< Master to us (we follow their conferencing) */
00661    int inconference;          /*!< If our real should be in the conference */
00662 
00663    int bufsize;                /*!< Size of the buffers */
00664    int buf_no;             /*!< Number of buffers */
00665    int buf_policy;            /*!< Buffer policy */
00666    int faxbuf_no;              /*!< Number of Fax buffers */
00667    int faxbuf_policy;          /*!< Fax buffer policy */
00668    int sig;             /*!< Signalling style */
00669    /*!
00670     * \brief Nonzero if the signaling type is sent over a radio.
00671     * \note Set to a couple of nonzero values but it is only tested like a boolean.
00672     */
00673    int radio;
00674    int outsigmod;             /*!< Outbound Signalling style (modifier) */
00675    int oprmode;               /*!< "Operator Services" mode */
00676    struct dahdi_pvt *oprpeer;          /*!< "Operator Services" peer tech_pvt ptr */
00677    /*! \brief Amount of gain to increase during caller id */
00678    float cid_rxgain;
00679    /*! \brief Rx gain set by chan_dahdi.conf */
00680    float rxgain;
00681    /*! \brief Tx gain set by chan_dahdi.conf */
00682    float txgain;
00683    int tonezone;              /*!< tone zone for this chan, or -1 for default */
00684    struct dahdi_pvt *next;          /*!< Next channel in list */
00685    struct dahdi_pvt *prev;          /*!< Prev channel in list */
00686 
00687    /* flags */
00688 
00689    /*!
00690     * \brief TRUE if ADSI (Analog Display Services Interface) available
00691     * \note Set from the "adsi" value read in from chan_dahdi.conf
00692     */
00693    unsigned int adsi:1;
00694    /*!
00695     * \brief TRUE if we can use a polarity reversal to mark when an outgoing
00696     * call is answered by the remote party.
00697     * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
00698     */
00699    unsigned int answeronpolarityswitch:1;
00700    /*!
00701     * \brief TRUE if busy detection is enabled.
00702     * (Listens for the beep-beep busy pattern.)
00703     * \note Set from the "busydetect" value read in from chan_dahdi.conf
00704     */
00705    unsigned int busydetect:1;
00706    /*!
00707     * \brief TRUE if call return is enabled.
00708     * (*69, if your dialplan doesn't catch this first)
00709     * \note Set from the "callreturn" value read in from chan_dahdi.conf
00710     */
00711    unsigned int callreturn:1;
00712    /*!
00713     * \brief TRUE if busy extensions will hear the call-waiting tone
00714     * and can use hook-flash to switch between callers.
00715     * \note Can be disabled by dialing *70.
00716     * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
00717     */
00718    unsigned int callwaiting:1;
00719    /*!
00720     * \brief TRUE if send caller ID for Call Waiting
00721     * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
00722     */
00723    unsigned int callwaitingcallerid:1;
00724    /*!
00725     * \brief TRUE if support for call forwarding enabled.
00726     * Dial *72 to enable call forwarding.
00727     * Dial *73 to disable call forwarding.
00728     * \note Set from the "cancallforward" value read in from chan_dahdi.conf
00729     */
00730    unsigned int cancallforward:1;
00731    /*!
00732     * \brief TRUE if support for call parking is enabled.
00733     * \note Set from the "canpark" value read in from chan_dahdi.conf
00734     */
00735    unsigned int canpark:1;
00736    /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
00737    unsigned int confirmanswer:1;
00738    /*!
00739     * \brief TRUE if the channel is to be destroyed on hangup.
00740     * (Used by pseudo channels.)
00741     */
00742    unsigned int destroy:1;
00743    unsigned int didtdd:1;           /*!< flag to say its done it once */
00744    /*! \brief TRUE if analog type line dialed no digits in Dial() */
00745    unsigned int dialednone:1;
00746    /*! \brief TRUE if in the process of dialing digits or sending something. */
00747    unsigned int dialing:1;
00748    /*! \brief TRUE if the transfer capability of the call is digital. */
00749    unsigned int digital:1;
00750    /*! \brief TRUE if Do-Not-Disturb is enabled. */
00751    unsigned int dnd:1;
00752    /*! \brief XXX BOOLEAN Purpose??? */
00753    unsigned int echobreak:1;
00754    /*!
00755     * \brief TRUE if echo cancellation enabled when bridged.
00756     * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
00757     * \note Disabled if the echo canceller is not setup.
00758     */
00759    unsigned int echocanbridged:1;
00760    /*! \brief TRUE if echo cancellation is turned on. */
00761    unsigned int echocanon:1;
00762    /*! \brief TRUE if a fax tone has already been handled. */
00763    unsigned int faxhandled:1;
00764    /*! \brief TRUE if dynamic faxbuffers are configured for use, default is OFF */
00765    unsigned int usefaxbuffers:1;
00766    /*! \brief TRUE while dynamic faxbuffers are in use */
00767    unsigned int bufferoverrideinuse:1;
00768    /*! \brief TRUE if over a radio and dahdi_read() has been called. */
00769    unsigned int firstradio:1;
00770    /*!
00771     * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
00772     * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
00773     */
00774    unsigned int hanguponpolarityswitch:1;
00775    /*! \brief TRUE if DTMF detection needs to be done by hardware. */
00776    unsigned int hardwaredtmf:1;
00777    /*!
00778     * \brief TRUE if the outgoing caller ID is blocked/hidden.
00779     * \note Caller ID can be disabled by dialing *67.
00780     * \note Caller ID can be enabled by dialing *82.
00781     * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
00782     */
00783    unsigned int hidecallerid:1;
00784    /*!
00785     * \brief TRUE if hide just the name not the number for legacy PBX use.
00786     * \note Only applies to PRI channels.
00787     * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
00788     */
00789    unsigned int hidecalleridname:1;
00790    /*! \brief TRUE if DTMF detection is disabled. */
00791    unsigned int ignoredtmf:1;
00792    /*!
00793     * \brief TRUE if the channel should be answered immediately
00794     * without attempting to gather any digits.
00795     * \note Set from the "immediate" value read in from chan_dahdi.conf
00796     */
00797    unsigned int immediate:1;
00798    /*! \brief TRUE if in an alarm condition. */
00799    unsigned int inalarm:1;
00800    /*! \brief TRUE if TDD in MATE mode */
00801    unsigned int mate:1;
00802    /*! \brief TRUE if we originated the call leg. */
00803    unsigned int outgoing:1;
00804    /* unsigned int overlapdial:1;         unused and potentially confusing */
00805    /*!
00806     * \brief TRUE if busy extensions will hear the call-waiting tone
00807     * and can use hook-flash to switch between callers.
00808     * \note Set from the "callwaiting" value read in from chan_dahdi.conf
00809     */
00810    unsigned int permcallwaiting:1;
00811    /*!
00812     * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
00813     * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
00814     */
00815    unsigned int permhidecallerid:1;
00816    /*!
00817     * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
00818     * \note Set from the "priindication" value read in from chan_dahdi.conf
00819     */
00820    unsigned int priindication_oob:1;
00821    /*!
00822     * \brief TRUE if PRI B channels are always exclusively selected.
00823     * \note Set from the "priexclusive" value read in from chan_dahdi.conf
00824     */
00825    unsigned int priexclusive:1;
00826    /*!
00827     * \brief TRUE if we will pulse dial.
00828     * \note Set from the "pulsedial" value read in from chan_dahdi.conf
00829     */
00830    unsigned int pulse:1;
00831    /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
00832    unsigned int pulsedial:1;
00833    unsigned int restartpending:1;      /*!< flag to ensure counted only once for restart */
00834    /*!
00835     * \brief TRUE if caller ID is restricted.
00836     * \note Set but not used.  Should be deleted.  Redundant with permhidecallerid.
00837     * \note Set from the "restrictcid" value read in from chan_dahdi.conf
00838     */
00839    unsigned int restrictcid:1;
00840    /*!
00841     * \brief TRUE if three way calling is enabled
00842     * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
00843     */
00844    unsigned int threewaycalling:1;
00845    /*!
00846     * \brief TRUE if call transfer is enabled
00847     * \note For FXS ports (either direct analog or over T1/E1):
00848     *   Support flash-hook call transfer
00849     * \note For digital ports using ISDN PRI protocols:
00850     *   Support switch-side transfer (called 2BCT, RLT or other names)
00851     * \note Set from the "transfer" value read in from chan_dahdi.conf
00852     */
00853    unsigned int transfer:1;
00854    /*!
00855     * \brief TRUE if caller ID is used on this channel.
00856     * \note PRI and SS7 spans will save caller ID from the networking peer.
00857     * \note FXS ports will generate the caller ID spill.
00858     * \note FXO ports will listen for the caller ID spill.
00859     * \note Set from the "usecallerid" value read in from chan_dahdi.conf
00860     */
00861    unsigned int use_callerid:1;
00862    /*!
00863     * \brief TRUE if we will use the calling presentation setting
00864     * from the Asterisk channel for outgoing calls.
00865     * \note Only applies to PRI and SS7 channels.
00866     * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
00867     */
00868    unsigned int use_callingpres:1;
00869    /*!
00870     * \brief TRUE if distinctive rings are to be detected.
00871     * \note For FXO lines
00872     * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
00873     */
00874    unsigned int usedistinctiveringdetection:1;
00875    /*!
00876     * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
00877     * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
00878     */
00879    unsigned int dahditrcallerid:1;
00880    /*!
00881     * \brief TRUE if allowed to flash-transfer to busy channels.
00882     * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
00883     */
00884    unsigned int transfertobusy:1;
00885    /*!
00886     * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
00887     * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
00888     */
00889    unsigned int mwimonitor_neon:1;
00890    /*!
00891     * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
00892     * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
00893     */
00894    unsigned int mwimonitor_fsk:1;
00895    /*!
00896     * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
00897     * \note RPAS - Ring Pulse Alert Signal
00898     * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
00899     */
00900    unsigned int mwimonitor_rpas:1;
00901    /*! \brief TRUE if an MWI monitor thread is currently active */
00902    unsigned int mwimonitoractive:1;
00903    /*! \brief TRUE if a MWI message sending thread is active */
00904    unsigned int mwisendactive:1;
00905    /*!
00906     * \brief TRUE if channel is out of reset and ready
00907     * \note Set but not used.
00908     */
00909    unsigned int inservice:1;
00910    /*!
00911     * \brief TRUE if the channel is locally blocked.
00912     * \note Applies to SS7 channels.
00913     */
00914    unsigned int locallyblocked:1;
00915    /*!
00916     * \brief TRUE if the channel is remotely blocked.
00917     * \note Applies to SS7 channels.
00918     */
00919    unsigned int remotelyblocked:1;
00920 #if defined(HAVE_PRI) || defined(HAVE_SS7)
00921    /*!
00922     * \brief XXX BOOLEAN Purpose???
00923     * \note Applies to SS7 channels.
00924     */
00925    unsigned int rlt:1;
00926    /*! \brief TRUE if channel is alerting/ringing */
00927    unsigned int alerting:1;
00928    /*! \brief TRUE if the call has already gone/hungup */
00929    unsigned int alreadyhungup:1;
00930    /*!
00931     * \brief TRUE if this is an idle call
00932     * \note Applies to PRI channels.
00933     */
00934    unsigned int isidlecall:1;
00935    /*!
00936     * \brief TRUE if call is in a proceeding state.
00937     * The call has started working its way through the network.
00938     */
00939    unsigned int proceeding:1;
00940    /*! \brief TRUE if the call has seen progress through the network. */
00941    unsigned int progress:1;
00942    /*!
00943     * \brief TRUE if this channel is being reset/restarted
00944     * \note Applies to PRI channels.
00945     */
00946    unsigned int resetting:1;
00947    /*!
00948     * \brief TRUE if this channel has received a SETUP_ACKNOWLEDGE
00949     * \note Applies to PRI channels.
00950     */
00951    unsigned int setup_ack:1;
00952 #endif
00953    /*!
00954     * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
00955     * \note Set from the "usesmdi" value read in from chan_dahdi.conf
00956     */
00957    unsigned int use_smdi:1;
00958    struct mwisend_info mwisend_data;
00959    /*! \brief The serial port to listen for SMDI data on */
00960    struct ast_smdi_interface *smdi_iface;
00961 
00962    /*! \brief Distinctive Ring data */
00963    struct dahdi_distRings drings;
00964 
00965    /*!
00966     * \brief The configured context for incoming calls.
00967     * \note The "context" string read in from chan_dahdi.conf
00968     */
00969    char context[AST_MAX_CONTEXT];
00970    /*!
00971     * \brief Saved context string.
00972     */
00973    char defcontext[AST_MAX_CONTEXT];
00974    /*! \brief Extension to use in the dialplan. */
00975    char exten[AST_MAX_EXTENSION];
00976    /*!
00977     * \brief Language configured for calls.
00978     * \note The "language" string read in from chan_dahdi.conf
00979     */
00980    char language[MAX_LANGUAGE];
00981    /*!
00982     * \brief The configured music-on-hold class to use for calls.
00983     * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
00984     */
00985    char mohinterpret[MAX_MUSICCLASS];
00986    /*!
00987     * \brief Suggested music-on-hold class for peer channel to use for calls.
00988     * \note The "mohsuggest" string read in from chan_dahdi.conf
00989     */
00990    char mohsuggest[MAX_MUSICCLASS];
00991    char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
00992 #if defined(PRI_ANI) || defined(HAVE_SS7)
00993    /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
00994    char cid_ani[AST_MAX_EXTENSION];
00995 #endif
00996    /*! \brief Automatic Number Identification code from PRI */
00997    int cid_ani2;
00998    /*! \brief Caller ID number from an incoming call. */
00999    char cid_num[AST_MAX_EXTENSION];
01000    /*! \brief Caller ID Q.931 TON/NPI field values.  Set by PRI. Zero otherwise. */
01001    int cid_ton;
01002    /*! \brief Caller ID name from an incoming call. */
01003    char cid_name[AST_MAX_EXTENSION];
01004    /*! \brief Last Caller ID number from an incoming call. */
01005    char lastcid_num[AST_MAX_EXTENSION];
01006    /*! \brief Last Caller ID name from an incoming call. */
01007    char lastcid_name[AST_MAX_EXTENSION];
01008    char *origcid_num;            /*!< malloced original callerid */
01009    char *origcid_name;           /*!< malloced original callerid */
01010    /*! \brief Call waiting number. */
01011    char callwait_num[AST_MAX_EXTENSION];
01012    /*! \brief Call waiting name. */
01013    char callwait_name[AST_MAX_EXTENSION];
01014    /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
01015    char rdnis[AST_MAX_EXTENSION];
01016    /*! \brief Dialed Number Identifier */
01017    char dnid[AST_MAX_EXTENSION];
01018    /*!
01019     * \brief Bitmapped groups this belongs to.
01020     * \note The "group" bitmapped group string read in from chan_dahdi.conf
01021     */
01022    ast_group_t group;
01023    /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
01024    int law;
01025    int confno;             /*!< Our conference */
01026    int confusers;             /*!< Who is using our conference */
01027    int propconfno;               /*!< Propagated conference number */
01028    /*!
01029     * \brief Bitmapped call groups this belongs to.
01030     * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
01031     */
01032    ast_group_t callgroup;
01033    /*!
01034     * \brief Bitmapped pickup groups this belongs to.
01035     * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
01036     */
01037    ast_group_t pickupgroup;
01038    /*!
01039     * \brief Channel variable list with associated values to set when a channel is created.
01040     * \note The "setvar" strings read in from chan_dahdi.conf
01041     */
01042    struct ast_variable *vars;
01043    int channel;               /*!< Channel Number or CRV */
01044    int span;               /*!< Span number */
01045    time_t guardtime;          /*!< Must wait this much time before using for new call */
01046    int cid_signalling;           /*!< CID signalling type bell202 or v23 */
01047    int cid_start;             /*!< CID start indicator, polarity or ring */
01048    int callingpres;           /*!< The value of calling presentation that we're going to use when placing a PRI call */
01049    int callwaitingrepeat;           /*!< How many samples to wait before repeating call waiting */
01050    int cidcwexpire;           /*!< When to expire our muting for CID/CW */
01051    /*! \brief Analog caller ID waveform sample buffer */
01052    unsigned char *cidspill;
01053    /*! \brief Position in the cidspill buffer to send out next. */
01054    int cidpos;
01055    /*! \brief Length of the cidspill buffer containing samples. */
01056    int cidlen;
01057    /*! \brief Ring timeout timer?? */
01058    int ringt;
01059    /*!
01060     * \brief Ring timeout base.
01061     * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
01062     */
01063    int ringt_base;
01064    /*!
01065     * \brief Number of most significant digits/characters to strip from the dialed number.
01066     * \note Feature is deprecated.  Use dialplan logic.
01067     * \note The characters are stripped before the PRI TON/NPI prefix
01068     * characters are processed.
01069     */
01070    int stripmsd;
01071    /*! \brief BOOLEAN. XXX Meaning what?? */
01072    int callwaitcas;
01073    /*! \brief Number of call waiting rings. */
01074    int callwaitrings;
01075    /*! \brief Echo cancel parameters. */
01076    struct {
01077       struct dahdi_echocanparams head;
01078       struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
01079    } echocancel;
01080    /*!
01081     * \brief Echo training time. 0 = disabled
01082     * \note Set from the "echotraining" value read in from chan_dahdi.conf
01083     */
01084    int echotraining;
01085    /*! \brief Filled with 'w'.  XXX Purpose?? */
01086    char echorest[20];
01087    /*!
01088     * \brief Number of times to see "busy" tone before hanging up.
01089     * \note Set from the "busycount" value read in from chan_dahdi.conf
01090     */
01091    int busycount;
01092    /*!
01093     * \brief Length of "busy" tone on time.
01094     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01095     */
01096    int busy_tonelength;
01097    /*!
01098     * \brief Length of "busy" tone off time.
01099     * \note Set from the "busypattern" value read in from chan_dahdi.conf
01100     */
01101    int busy_quietlength;
01102    /*!
01103     * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
01104     * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
01105     */
01106    int callprogress;
01107    /*!
01108     * \brief Number of milliseconds to wait for dialtone.
01109     * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
01110     */
01111    int waitfordialtone;
01112    struct timeval waitingfordt;        /*!< Time we started waiting for dialtone */
01113    struct timeval flashtime;        /*!< Last flash-hook time */
01114    /*! \brief Opaque DSP configuration structure. */
01115    struct ast_dsp *dsp;
01116    //int cref;             /*!< Call reference number (Not used) */
01117    /*! \brief DAHDI dial operation command struct for ioctl() call. */
01118    struct dahdi_dialoperation dop;
01119    int whichwink;             /*!< SIG_FEATDMF_TA Which wink are we on? */
01120    /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
01121    char finaldial[64];
01122    char accountcode[AST_MAX_ACCOUNT_CODE];      /*!< Account code */
01123    int amaflags;              /*!< AMA Flags */
01124    struct tdd_state *tdd;           /*!< TDD flag */
01125    /*! \brief Accumulated call forwarding number. */
01126    char call_forward[AST_MAX_EXTENSION];
01127    /*!
01128     * \brief Voice mailbox location.
01129     * \note Set from the "mailbox" string read in from chan_dahdi.conf
01130     */
01131    char mailbox[AST_MAX_EXTENSION];
01132    /*! \brief Opaque event subscription parameters for message waiting indication support. */
01133    struct ast_event_sub *mwi_event_sub;
01134    /*! \brief Delayed dialing for E911.  Overlap digits for ISDN. */
01135    char dialdest[256];
01136    /*! \brief Time the interface went on-hook. */
01137    int onhooktime;
01138    /*! \brief TRUE if the FXS port is off-hook */
01139    int fxsoffhookstate;
01140    /*! \brief -1 = unknown, 0 = no messages, 1 = new messages available */
01141    int msgstate;
01142 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01143    struct dahdi_vmwi_info mwisend_setting;            /*!< Which VMWI methods to use */
01144    unsigned int mwisend_fsk: 1;     /*! Variable for enabling FSK MWI handling in chan_dahdi */
01145    unsigned int mwisend_rpas:1;     /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
01146 #endif
01147    int distinctivering;          /*!< Which distinctivering to use */
01148    int cidrings;              /*!< Which ring to deliver CID on */
01149    int dtmfrelax;             /*!< whether to run in relaxed DTMF mode */
01150    /*! \brief Holding place for event injected from outside normal operation. */
01151    int fake_event;
01152    /*!
01153     * \brief Minimal time period (ms) between the answer polarity
01154     * switch and hangup polarity switch.
01155     */
01156    int polarityonanswerdelay;
01157    /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
01158    struct timeval polaritydelaytv;
01159    /*!
01160     * \brief Send caller ID after this many rings.
01161     * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
01162     */
01163    int sendcalleridafter;
01164 #ifdef HAVE_PRI
01165    /*! \brief DAHDI PRI control parameters */
01166    struct dahdi_pri *pri;
01167    /*! \brief XXX Purpose??? */
01168    struct dahdi_pvt *bearer;
01169    /*! \brief XXX Purpose??? */
01170    struct dahdi_pvt *realcall;
01171    /*! \brief Opaque libpri call control structure */
01172    q931_call *call;
01173    /*! \brief Channel number in span. */
01174    int prioffset;
01175    /*! \brief Logical span number within trunk group */
01176    int logicalspan;
01177 #endif
01178    /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
01179    int polarity;
01180    /*! \brief DSP feature flags: DSP_FEATURE_xxx */
01181    int dsp_features;
01182 #ifdef HAVE_SS7
01183    /*! \brief SS7 control parameters */
01184    struct dahdi_ss7 *ss7;
01185    /*! \brief Opaque libss7 call control structure */
01186    struct isup_call *ss7call;
01187    char charge_number[50];
01188    char gen_add_number[50];
01189    char gen_dig_number[50];
01190    char orig_called_num[50];
01191    char redirecting_num[50];
01192    char generic_name[50];
01193    unsigned char gen_add_num_plan;
01194    unsigned char gen_add_nai;
01195    unsigned char gen_add_pres_ind;
01196    unsigned char gen_add_type;
01197    unsigned char gen_dig_type;
01198    unsigned char gen_dig_scheme;
01199    char jip_number[50];
01200    unsigned char lspi_type;
01201    unsigned char lspi_scheme;
01202    unsigned char lspi_context;
01203    char lspi_ident[50];
01204    unsigned int call_ref_ident;
01205    unsigned int call_ref_pc;
01206    unsigned char calling_party_cat;
01207    int transcap;
01208    int cic;                   /*!< CIC associated with channel */
01209    unsigned int dpc;                /*!< CIC's DPC */
01210    unsigned int loopedback:1;
01211 #endif
01212 #ifdef HAVE_OPENR2
01213    struct dahdi_mfcr2 *mfcr2;
01214    openr2_chan_t *r2chan;
01215    openr2_calling_party_category_t mfcr2_recvd_category;
01216    openr2_calling_party_category_t mfcr2_category;
01217    int mfcr2_dnis_index;
01218    int mfcr2_ani_index;
01219    int mfcr2call:1;
01220    int mfcr2_answer_pending:1;
01221    int mfcr2_charge_calls:1;
01222    int mfcr2_allow_collect_calls:1;
01223    int mfcr2_forced_release:1;
01224    int mfcr2_dnis_matched:1;
01225    int mfcr2_call_accepted:1;
01226    int mfcr2_accept_on_offer:1;
01227 #endif
01228    /*! \brief DTMF digit in progress.  0 when no digit in progress. */
01229    char begindigit;
01230    /*! \brief TRUE if confrence is muted. */
01231    int muting;
01232 } *iflist = NULL, *ifend = NULL;
01233 
01234 /*! \brief Channel configuration from chan_dahdi.conf .
01235  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
01236  * Generally there is a field here for every possible configuration item.
01237  *
01238  * The state of fields is saved along the parsing and whenever a 'channel'
01239  * statement is reached, the current dahdi_chan_conf is used to configure the
01240  * channel (struct dahdi_pvt)
01241  *
01242  * \see dahdi_chan_init for the default values.
01243  */
01244 struct dahdi_chan_conf {
01245    struct dahdi_pvt chan;
01246 #ifdef HAVE_PRI
01247    struct dahdi_pri pri;
01248 #endif
01249 
01250 #ifdef HAVE_SS7
01251    struct dahdi_ss7 ss7;
01252 #endif
01253 
01254 #ifdef HAVE_OPENR2
01255    struct dahdi_mfcr2_conf mfcr2;
01256 #endif
01257    struct dahdi_params timing;
01258    int is_sig_auto; /*!< Use channel signalling from DAHDI? */
01259 
01260    /*!
01261     * \brief The serial port to listen for SMDI data on
01262     * \note Set from the "smdiport" string read in from chan_dahdi.conf
01263     */
01264    char smdi_port[SMDI_MAX_FILENAME_LEN];
01265 };
01266 
01267 /*! returns a new dahdi_chan_conf with default values (by-value) */
01268 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
01269 {
01270    /* recall that if a field is not included here it is initialized
01271     * to 0 or equivalent
01272     */
01273    struct dahdi_chan_conf conf = {
01274 #ifdef HAVE_PRI
01275       .pri = {
01276          .nsf = PRI_NSF_NONE,
01277          .switchtype = PRI_SWITCH_NI2,
01278          .dialplan = PRI_UNKNOWN + 1,
01279          .localdialplan = PRI_NATIONAL_ISDN + 1,
01280          .nodetype = PRI_CPE,
01281          .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
01282 
01283          .minunused = 2,
01284          .idleext = "",
01285          .idledial = "",
01286          .internationalprefix = "",
01287          .nationalprefix = "",
01288          .localprefix = "",
01289          .privateprefix = "",
01290          .unknownprefix = "",
01291          .resetinterval = -1,
01292       },
01293 #endif
01294 #ifdef HAVE_SS7
01295       .ss7 = {
01296          .called_nai = SS7_NAI_NATIONAL,
01297          .calling_nai = SS7_NAI_NATIONAL,
01298          .internationalprefix = "",
01299          .nationalprefix = "",
01300          .subscriberprefix = "",
01301          .unknownprefix = ""
01302       },
01303 #endif
01304 #ifdef HAVE_OPENR2
01305       .mfcr2 = {
01306          .variant = OR2_VAR_ITU,
01307          .mfback_timeout = -1,
01308          .metering_pulse_timeout = -1,
01309          .max_ani = 10,
01310          .max_dnis = 4,
01311          .get_ani_first = -1,
01312 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
01313          .skip_category_request = -1,
01314 #endif
01315          .call_files = 0,
01316          .allow_collect_calls = 0,
01317          .charge_calls = 1,
01318          .accept_on_offer = 1,
01319          .forced_release = 0,
01320          .double_answer = 0,
01321          .immediate_accept = -1,
01322          .logdir = "",
01323          .r2proto_file = "",
01324          .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
01325          .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
01326       },
01327 #endif
01328       .chan = {
01329          .context = "default",
01330          .cid_num = "",
01331          .cid_name = "",
01332          .mohinterpret = "default",
01333          .mohsuggest = "",
01334          .parkinglot = "",
01335          .transfertobusy = 1,
01336 
01337          .cid_signalling = CID_SIG_BELL,
01338          .cid_start = CID_START_RING,
01339          .dahditrcallerid = 0,
01340          .use_callerid = 1,
01341          .sig = -1,
01342          .outsigmod = -1,
01343 
01344          .cid_rxgain = +5.0,
01345 
01346          .tonezone = -1,
01347 
01348          .echocancel.head.tap_length = 1,
01349 
01350          .busycount = 3,
01351 
01352          .accountcode = "",
01353 
01354          .mailbox = "",
01355 
01356 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
01357          .mwisend_fsk = 1,
01358 #endif
01359          .polarityonanswerdelay = 600,
01360 
01361          .sendcalleridafter = DEFAULT_CIDRINGS,
01362 
01363          .buf_policy = DAHDI_POLICY_IMMEDIATE,
01364          .buf_no = numbufs,
01365          .usefaxbuffers = 0,
01366          .faxbuf_policy = DAHDI_POLICY_IMMEDIATE,
01367          .faxbuf_no = numbufs,
01368       },
01369       .timing = {
01370          .prewinktime = -1,
01371          .preflashtime = -1,
01372          .winktime = -1,
01373          .flashtime = -1,
01374          .starttime = -1,
01375          .rxwinktime = -1,
01376          .rxflashtime = -1,
01377          .debouncetime = -1
01378       },
01379       .is_sig_auto = 1,
01380       .smdi_port = "/dev/ttyS0",
01381    };
01382 
01383    return conf;
01384 }
01385 
01386 
01387 static struct ast_channel *dahdi_request(const char *type, int format, void *data, int *cause);
01388 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
01389 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
01390 static int dahdi_sendtext(struct ast_channel *c, const char *text);
01391 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
01392 static int dahdi_hangup(struct ast_channel *ast);
01393 static int dahdi_answer(struct ast_channel *ast);
01394 static struct ast_frame *dahdi_read(struct ast_channel *ast);
01395 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
01396 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
01397 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
01398 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01399 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01400 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
01401 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value);
01402 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event);
01403 
01404 static const struct ast_channel_tech dahdi_tech = {
01405    .type = "DAHDI",
01406    .description = tdesc,
01407    .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
01408    .requester = dahdi_request,
01409    .send_digit_begin = dahdi_digit_begin,
01410    .send_digit_end = dahdi_digit_end,
01411    .send_text = dahdi_sendtext,
01412    .call = dahdi_call,
01413    .hangup = dahdi_hangup,
01414    .answer = dahdi_answer,
01415    .read = dahdi_read,
01416    .write = dahdi_write,
01417    .bridge = dahdi_bridge,
01418    .exception = dahdi_exception,
01419    .indicate = dahdi_indicate,
01420    .fixup = dahdi_fixup,
01421    .setoption = dahdi_setoption,
01422    .func_channel_read = dahdi_func_read,
01423    .func_channel_write = dahdi_func_write,
01424 };
01425 
01426 #ifdef HAVE_PRI
01427 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
01428 #else
01429 #define GET_CHANNEL(p) ((p)->channel)
01430 #endif
01431 
01432 struct dahdi_pvt *round_robin[32];
01433 
01434 #if defined(HAVE_PRI)
01435 static inline int pri_grab(struct dahdi_pvt *pvt, struct dahdi_pri *pri)
01436 {
01437    int res;
01438    /* Grab the lock first */
01439    do {
01440       res = ast_mutex_trylock(&pri->lock);
01441       if (res) {
01442          DEADLOCK_AVOIDANCE(&pvt->lock);
01443       }
01444    } while (res);
01445    /* Then break the poll */
01446    if (pri->master != AST_PTHREADT_NULL)
01447       pthread_kill(pri->master, SIGURG);
01448    return 0;
01449 }
01450 #endif   /* defined(HAVE_PRI) */
01451 
01452 #if defined(HAVE_SS7)
01453 static inline void ss7_rel(struct dahdi_ss7 *ss7)
01454 {
01455    ast_mutex_unlock(&ss7->lock);
01456 }
01457 #endif   /* defined(HAVE_SS7) */
01458 
01459 #if defined(HAVE_SS7)
01460 static inline int ss7_grab(struct dahdi_pvt *pvt, struct dahdi_ss7 *pri)
01461 {
01462    int res;
01463    /* Grab the lock first */
01464    do {
01465       res = ast_mutex_trylock(&pri->lock);
01466       if (res) {
01467          DEADLOCK_AVOIDANCE(&pvt->lock);
01468       }
01469    } while (res);
01470    /* Then break the poll */
01471    if (pri->master != AST_PTHREADT_NULL)
01472       pthread_kill(pri->master, SIGURG);
01473    return 0;
01474 }
01475 #endif   /* defined(HAVE_SS7) */
01476 #define NUM_CADENCE_MAX 25
01477 static int num_cadence = 4;
01478 static int user_has_defined_cadences = 0;
01479 
01480 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
01481    { { 125, 125, 2000, 4000 } },       /*!< Quick chirp followed by normal ring */
01482    { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
01483    { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
01484    { { 1000, 500, 2500, 5000 } },   /*!< Long ring */
01485 };
01486 
01487 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
01488  * is 1, the second pause is 2 and so on.
01489  */
01490 
01491 static int cidrings[NUM_CADENCE_MAX] = {
01492    2,                            /*!< Right after first long ring */
01493    4,                            /*!< Right after long part */
01494    3,                            /*!< After third chirp */
01495    2,                            /*!< Second spell */
01496 };
01497 
01498 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
01499 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
01500 
01501 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
01502          (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
01503 
01504 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
01505 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
01506 
01507 #define dahdi_get_index(ast, p, nullok)   _dahdi_get_index(ast, p, nullok, __PRETTY_FUNCTION__, __LINE__)
01508 static int _dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok, const char *fname, unsigned long line)
01509 {
01510    int res;
01511    if (p->subs[SUB_REAL].owner == ast)
01512       res = 0;
01513    else if (p->subs[SUB_CALLWAIT].owner == ast)
01514       res = 1;
01515    else if (p->subs[SUB_THREEWAY].owner == ast)
01516       res = 2;
01517    else {
01518       res = -1;
01519       if (!nullok)
01520          ast_log(LOG_WARNING,
01521             "Unable to get index for '%s' on channel %d (%s(), line %lu)\n",
01522             ast ? ast->name : "", p->channel, fname, line);
01523    }
01524    return res;
01525 }
01526 
01527 /*!
01528  * \internal
01529  * \brief Obtain the specified subchannel owner lock if the owner exists.
01530  *
01531  * \param pvt Channel private struct.
01532  * \param sub_idx Subchannel owner to lock.
01533  *
01534  * \note Assumes the pvt->lock is already obtained.
01535  *
01536  * \note
01537  * Because deadlock avoidance may have been necessary, you need to confirm
01538  * the state of things before continuing.
01539  *
01540  * \return Nothing
01541  */
01542 static void dahdi_lock_sub_owner(struct dahdi_pvt *pvt, int sub_idx)
01543 {
01544    for (;;) {
01545       if (!pvt->subs[sub_idx].owner) {
01546          /* No subchannel owner pointer */
01547          break;
01548       }
01549       if (!ast_channel_trylock(pvt->subs[sub_idx].owner)) {
01550          /* Got subchannel owner lock */
01551          break;
01552       }
01553       /* We must unlock the private to avoid the possibility of a deadlock */
01554       DEADLOCK_AVOIDANCE(&pvt->lock);
01555    }
01556 }
01557 
01558 static void wakeup_sub(struct dahdi_pvt *p, int a, struct dahdi_pri *pri)
01559 {
01560 #ifdef HAVE_PRI
01561    if (pri)
01562       ast_mutex_unlock(&pri->lock);
01563 #endif
01564    dahdi_lock_sub_owner(p, a);
01565    if (p->subs[a].owner) {
01566       ast_queue_frame(p->subs[a].owner, &ast_null_frame);
01567       ast_channel_unlock(p->subs[a].owner);
01568    }
01569 #ifdef HAVE_PRI
01570    if (pri)
01571       ast_mutex_lock(&pri->lock);
01572 #endif
01573 }
01574 
01575 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f, void *data)
01576 {
01577 #ifdef HAVE_PRI
01578    struct dahdi_pri *pri = (struct dahdi_pri*) data;
01579 #endif
01580 #ifdef HAVE_SS7
01581    struct dahdi_ss7 *ss7 = (struct dahdi_ss7*) data;
01582 #endif
01583    /* We must unlock the PRI to avoid the possibility of a deadlock */
01584 #if defined(HAVE_PRI) || defined(HAVE_SS7)
01585    if (data) {
01586       switch (p->sig) {
01587 #ifdef HAVE_PRI
01588       case SIG_BRI:
01589       case SIG_BRI_PTMP:
01590       case SIG_PRI:
01591          ast_mutex_unlock(&pri->lock);
01592          break;
01593 #endif
01594 #ifdef HAVE_SS7
01595       case SIG_SS7:
01596          ast_mutex_unlock(&ss7->lock);
01597          break;
01598 #endif
01599       default:
01600          break;
01601       }
01602    }
01603 #endif
01604    for (;;) {
01605       if (p->owner) {
01606          if (ast_channel_trylock(p->owner)) {
01607             DEADLOCK_AVOIDANCE(&p->lock);
01608          } else {
01609             ast_queue_frame(p->owner, f);
01610             ast_channel_unlock(p->owner);
01611             break;
01612          }
01613       } else
01614          break;
01615    }
01616 #if defined(HAVE_PRI) || defined(HAVE_SS7)
01617    if (data) {
01618       switch (p->sig) {
01619 #ifdef HAVE_PRI
01620       case SIG_BRI:
01621       case SIG_BRI_PTMP:
01622       case SIG_PRI:
01623          ast_mutex_lock(&pri->lock);
01624          break;
01625 #endif
01626 #ifdef HAVE_SS7
01627       case SIG_SS7:
01628          ast_mutex_lock(&ss7->lock);
01629          break;
01630 #endif
01631       default:
01632          break;
01633       }
01634    }
01635 #endif
01636 }
01637 
01638 static struct ast_channel *dahdi_new(struct dahdi_pvt *, int, int, int, int, int);
01639 #ifdef HAVE_OPENR2
01640 
01641 static int dahdi_r2_answer(struct dahdi_pvt *p)
01642 {
01643    int res = 0;
01644    /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
01645    * and does not has support for openr2_chan_answer_call_with_mode
01646    *  */
01647 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
01648    const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
01649    int wants_double_answer = ast_true(double_answer) ? 1 : 0;
01650    if (!double_answer) {
01651       /* this still can result in double answer if the channel context
01652       * was configured that way */
01653       res = openr2_chan_answer_call(p->r2chan);
01654    } else if (wants_double_answer) {
01655       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
01656    } else {
01657       res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
01658    }
01659 #else
01660    res = openr2_chan_answer_call(p->r2chan);
01661 #endif
01662    return res;
01663 }
01664 
01665 
01666 
01667 /* should be called with the ast_channel locked */
01668 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
01669 {
01670    openr2_calling_party_category_t cat;
01671    const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
01672    struct dahdi_pvt *p = c->tech_pvt;
01673    if (ast_strlen_zero(catstr)) {
01674       ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
01675             c->name, openr2_proto_get_category_string(p->mfcr2_category));
01676       return p->mfcr2_category;
01677    }
01678    if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
01679       ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
01680             catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
01681       return p->mfcr2_category;
01682    }
01683    ast_debug(1, "Using category %s\n", catstr);
01684    return cat;
01685 }
01686 
01687 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
01688 {
01689    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01690    ast_mutex_lock(&p->lock);
01691    if (p->mfcr2call) {
01692       ast_mutex_unlock(&p->lock);
01693       /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
01694          interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
01695          can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
01696          the other end will see our seize as a forced release and drop the call, we will see an invalid
01697          pattern that will be seen and treated as protocol error. */
01698       ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
01699       return;
01700    }
01701    p->mfcr2call = 1;
01702    /* better safe than sorry ... */
01703    p->cid_name[0] = '\0';
01704    p->cid_num[0] = '\0';
01705    p->rdnis[0] = '\0';
01706    p->exten[0] = '\0';
01707    p->mfcr2_ani_index = '\0';
01708    p->mfcr2_dnis_index = '\0';
01709    p->mfcr2_dnis_matched = 0;
01710    p->mfcr2_answer_pending = 0;
01711    p->mfcr2_call_accepted = 0;
01712    ast_mutex_unlock(&p->lock);
01713    ast_verbose("New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
01714 }
01715 
01716 static int get_alarms(struct dahdi_pvt *p);
01717 static void handle_alarms(struct dahdi_pvt *p, int alms);
01718 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
01719 {
01720    int res;
01721    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01722    ast_mutex_lock(&p->lock);
01723    p->inalarm = alarm ? 1 : 0;
01724    if (p->inalarm) {
01725       res = get_alarms(p);
01726       handle_alarms(p, res);
01727    } else {
01728       ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
01729       manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
01730    }
01731    ast_mutex_unlock(&p->lock);
01732 }
01733 
01734 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
01735 {
01736    ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
01737 }
01738 
01739 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
01740 {
01741    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01742    ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
01743    if (p->owner) {
01744       p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
01745       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
01746    }
01747    ast_mutex_lock(&p->lock);
01748    p->mfcr2call = 0;
01749    ast_mutex_unlock(&p->lock);
01750 }
01751 
01752 static void dahdi_r2_disconnect_call(struct dahdi_pvt *p, openr2_call_disconnect_cause_t cause)
01753 {
01754    if (openr2_chan_disconnect_call(p->r2chan, cause)) {
01755       ast_log(LOG_NOTICE, "Bad! failed to disconnect call on channel %d with reason %s, hope for the best!\n",
01756          p->channel, openr2_proto_get_disconnect_string(cause));
01757       /* force the chan to idle and release the call flag now since we will not see a clean on_call_end */
01758       openr2_chan_set_idle(p->r2chan);
01759       ast_mutex_lock(&p->lock);
01760       p->mfcr2call = 0;
01761       ast_mutex_unlock(&p->lock);
01762    }
01763 }
01764 
01765 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
01766 {
01767    struct dahdi_pvt *p;
01768    struct ast_channel *c;
01769    ast_verbose("MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
01770          openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
01771          openr2_proto_get_category_string(category));
01772    p = openr2_chan_get_client_data(r2chan);
01773    /* if collect calls are not allowed and this is a collect call, reject it! */
01774    if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
01775       ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
01776       dahdi_r2_disconnect_call(p, OR2_CAUSE_COLLECT_CALL_REJECTED);
01777       return;
01778    }
01779    ast_mutex_lock(&p->lock);
01780    p->mfcr2_recvd_category = category;
01781    /* if we're not supposed to use CID, clear whatever we have */
01782    if (!p->use_callerid) {
01783       ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
01784       p->cid_num[0] = 0;
01785       p->cid_name[0] = 0;
01786    }
01787    /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
01788    if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
01789       ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
01790       p->exten[0] = 's';
01791       p->exten[1] = 0;
01792    }
01793    ast_mutex_unlock(&p->lock);
01794    if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
01795       ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
01796             p->channel, p->exten, p->context);
01797       dahdi_r2_disconnect_call(p, OR2_CAUSE_UNALLOCATED_NUMBER);
01798       return;
01799    }
01800    if (!p->mfcr2_accept_on_offer) {
01801       /* The user wants us to start the PBX thread right away without accepting the call first */
01802       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
01803       if (c) {
01804          /* Done here, don't disable reading now since we still need to generate MF tones to accept
01805             the call or reject it and detect the tone off condition of the other end, all of this
01806             will be done in the PBX thread now */
01807          return;
01808       }
01809       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
01810       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
01811    } else if (p->mfcr2_charge_calls) {
01812       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
01813       openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
01814    } else {
01815       ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
01816       openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
01817    }
01818 }
01819 
01820 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
01821 {
01822    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01823    ast_verbose("MFC/R2 call end on channel %d\n", p->channel);
01824    ast_mutex_lock(&p->lock);
01825    p->mfcr2call = 0;
01826    ast_mutex_unlock(&p->lock);
01827 }
01828 
01829 static void dahdi_enable_ec(struct dahdi_pvt *p);
01830 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
01831 {
01832    struct dahdi_pvt *p = NULL;
01833    struct ast_channel *c = NULL;
01834    p = openr2_chan_get_client_data(r2chan);
01835    dahdi_enable_ec(p);
01836    p->mfcr2_call_accepted = 1;
01837    /* if it's an incoming call ... */
01838    if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
01839       ast_verbose("MFC/R2 call has been accepted on backward channel %d\n", openr2_chan_get_number(r2chan));
01840       /* If accept on offer is not set, it means at this point the PBX thread is already
01841          launched (was launched in the 'on call offered' handler) and therefore this callback
01842          is being executed already in the PBX thread rather than the monitor thread, don't launch
01843          any other thread, just disable the openr2 reading and answer the call if needed */
01844       if (!p->mfcr2_accept_on_offer) {
01845          openr2_chan_disable_read(r2chan);
01846          if (p->mfcr2_answer_pending) {
01847             ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
01848             dahdi_r2_answer(p);
01849          }
01850          return;
01851       }
01852       c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
01853       if (c) {
01854          /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
01855             library to forget about it */
01856          openr2_chan_disable_read(r2chan);
01857          return;
01858       }
01859       ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
01860       /* failed to create the channel, bail out and report it as an out of order line */
01861       dahdi_r2_disconnect_call(p, OR2_CAUSE_OUT_OF_ORDER);
01862       return;
01863    }
01864    /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
01865    ast_verbose("MFC/R2 call has been accepted on forward channel %d\n", p->channel);
01866    p->subs[SUB_REAL].needringing = 1;
01867    p->dialing = 0;
01868    /* chan_dahdi will take care of reading from now on in the PBX thread, tell the library to forget about it */
01869    openr2_chan_disable_read(r2chan);
01870 }
01871 
01872 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
01873 {
01874    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01875    ast_verbose("MFC/R2 call has been answered on channel %d\n", openr2_chan_get_number(r2chan));
01876    p->subs[SUB_REAL].needanswer = 1;
01877 }
01878 
01879 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
01880 {
01881    /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
01882 }
01883 
01884 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
01885 {
01886    switch (cause) {
01887    case OR2_CAUSE_BUSY_NUMBER:
01888       return AST_CAUSE_BUSY;
01889    case OR2_CAUSE_NETWORK_CONGESTION:
01890       return AST_CAUSE_CONGESTION;
01891    case OR2_CAUSE_OUT_OF_ORDER:
01892       return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
01893    case OR2_CAUSE_UNALLOCATED_NUMBER:
01894       return AST_CAUSE_UNREGISTERED;
01895    case OR2_CAUSE_NO_ANSWER:
01896       return AST_CAUSE_NO_ANSWER;
01897    case OR2_CAUSE_NORMAL_CLEARING:
01898       return AST_CAUSE_NORMAL_CLEARING;
01899    case OR2_CAUSE_UNSPECIFIED:
01900    default:
01901       return AST_CAUSE_NOTDEFINED;
01902    }
01903 }
01904 
01905 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
01906 {
01907    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01908    ast_verbose("MFC/R2 call disconnected on channel %d\n", openr2_chan_get_number(r2chan));
01909    ast_mutex_lock(&p->lock);
01910    if (!p->owner) {
01911       ast_mutex_unlock(&p->lock);
01912       /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
01913       dahdi_r2_disconnect_call(p, OR2_CAUSE_NORMAL_CLEARING);
01914       return;
01915    }
01916    /* when we have an owner we don't call dahdi_r2_disconnect_call here, that will
01917       be done in dahdi_hangup */
01918    if (p->owner->_state == AST_STATE_UP) {
01919       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
01920       ast_mutex_unlock(&p->lock);
01921    } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
01922       /* being the forward side we must report what happened to the call to whoever requested it */
01923       switch (cause) {
01924       case OR2_CAUSE_BUSY_NUMBER:
01925          p->subs[SUB_REAL].needbusy = 1;
01926          break;
01927       case OR2_CAUSE_NETWORK_CONGESTION:
01928       case OR2_CAUSE_OUT_OF_ORDER:
01929       case OR2_CAUSE_UNALLOCATED_NUMBER:
01930       case OR2_CAUSE_NO_ANSWER:
01931       case OR2_CAUSE_UNSPECIFIED:
01932       case OR2_CAUSE_NORMAL_CLEARING:
01933          p->subs[SUB_REAL].needcongestion = 1;
01934          break;
01935       default:
01936          p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
01937       }
01938       ast_mutex_unlock(&p->lock);
01939    } else {
01940       ast_mutex_unlock(&p->lock);
01941       /* being the backward side and not UP yet, we only need to request hangup */
01942       /* TODO: what about doing this same thing when were AST_STATE_UP? */
01943       ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
01944    }
01945 }
01946 
01947 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
01948 {
01949    switch (level) {
01950    case OR2_LOG_NOTICE:
01951       ast_verbose("%s", logmessage);
01952       break;
01953    case OR2_LOG_WARNING:
01954       ast_log(LOG_WARNING, "%s", logmessage);
01955       break;
01956    case OR2_LOG_ERROR:
01957       ast_log(LOG_ERROR, "%s", logmessage);
01958       break;
01959    case OR2_LOG_STACK_TRACE:
01960    case OR2_LOG_MF_TRACE:
01961    case OR2_LOG_CAS_TRACE:
01962    case OR2_LOG_DEBUG:
01963    case OR2_LOG_EX_DEBUG:
01964       ast_log(LOG_DEBUG, "%s", logmessage);
01965       break;
01966    default:
01967       ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
01968       ast_log(LOG_DEBUG, "%s", logmessage);
01969       break;
01970    }
01971 }
01972 
01973 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
01974 {
01975    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01976    ast_mutex_lock(&p->lock);
01977    p->remotelyblocked = 1;
01978    ast_mutex_unlock(&p->lock);
01979    ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
01980 }
01981 
01982 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
01983 {
01984    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
01985    ast_mutex_lock(&p->lock);
01986    p->remotelyblocked = 0;
01987    ast_mutex_unlock(&p->lock);
01988    ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
01989 }
01990 
01991 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
01992    __attribute__((format (printf, 3, 0)));
01993 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
01994 {
01995 #define CONTEXT_TAG "Context - "
01996    char logmsg[256];
01997    char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
01998    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
01999    snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
02000    dahdi_r2_write_log(level, completemsg);
02001 #undef CONTEXT_TAG
02002 }
02003 
02004 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
02005    __attribute__((format (printf, 3, 0)));
02006 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
02007 {
02008 #define CHAN_TAG "Chan "
02009    char logmsg[256];
02010    char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
02011    vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
02012    snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
02013    dahdi_r2_write_log(level, completemsg);
02014 }
02015 
02016 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
02017 {
02018    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
02019    /* if 'immediate' is set, let's stop requesting DNIS */
02020    if (p->immediate) {
02021       return 0;
02022    }
02023    p->exten[p->mfcr2_dnis_index] = digit;
02024    p->rdnis[p->mfcr2_dnis_index] = digit;
02025    p->mfcr2_dnis_index++;
02026    p->exten[p->mfcr2_dnis_index] = 0;
02027    p->rdnis[p->mfcr2_dnis_index] = 0;
02028    /* if the DNIS is a match and cannot match more, stop requesting DNIS */
02029    if ((p->mfcr2_dnis_matched ||
02030        (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
02031        !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
02032       return 0;
02033    }
02034    /* otherwise keep going */
02035    return 1;
02036 }
02037 
02038 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
02039 {
02040    struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
02041    p->cid_num[p->mfcr2_ani_index] = digit;
02042    p->cid_name[p->mfcr2_ani_index] = digit;
02043    p->mfcr2_ani_index++;
02044    p->cid_num[p->mfcr2_ani_index] = 0;
02045    p->cid_name[p->mfcr2_ani_index] = 0;
02046 }
02047 
02048 static void dahdi_r2_on_billing_pulse_received(openr2_chan_t *r2chan)
02049 {
02050    ast_verbose("MFC/R2 billing pulse received on channel %d\n", openr2_chan_get_number(r2chan));
02051 }
02052 
02053 static openr2_event_interface_t dahdi_r2_event_iface = {
02054    .on_call_init = dahdi_r2_on_call_init,
02055    .on_call_offered = dahdi_r2_on_call_offered,
02056    .on_call_accepted = dahdi_r2_on_call_accepted,
02057    .on_call_answered = dahdi_r2_on_call_answered,
02058    .on_call_disconnect = dahdi_r2_on_call_disconnect,
02059    .on_call_end = dahdi_r2_on_call_end,
02060    .on_call_read = dahdi_r2_on_call_read,
02061    .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
02062    .on_os_error = dahdi_r2_on_os_error,
02063    .on_protocol_error = dahdi_r2_on_protocol_error,
02064    .on_line_blocked = dahdi_r2_on_line_blocked,
02065    .on_line_idle = dahdi_r2_on_line_idle,
02066    /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
02067    .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
02068    .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
02069    .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
02070    /* so far we do nothing with billing pulses */
02071    .on_billing_pulse_received = dahdi_r2_on_billing_pulse_received
02072 };
02073 
02074 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
02075 {
02076    return AST_ALAW(sample);
02077 }
02078 
02079 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
02080 {
02081    return AST_LIN2A(sample);
02082 }
02083 
02084 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
02085    dahdi_r2_alaw_to_linear,
02086    dahdi_r2_linear_to_alaw
02087 };
02088 
02089 #endif /* HAVE_OPENR2 */
02090 
02091 static int restore_gains(struct dahdi_pvt *p);
02092 
02093 static void swap_subs(struct dahdi_pvt *p, int a, int b)
02094 {
02095    int tchan;
02096    int tinthreeway;
02097    struct ast_channel *towner;
02098 
02099    ast_debug(1, "Swapping %d and %d\n", a, b);
02100 
02101    tchan = p->subs[a].chan;
02102    towner = p->subs[a].owner;
02103    tinthreeway = p->subs[a].inthreeway;
02104 
02105    p->subs[a].chan = p->subs[b].chan;
02106    p->subs[a].owner = p->subs[b].owner;
02107    p->subs[a].inthreeway = p->subs[b].inthreeway;
02108 
02109    p->subs[b].chan = tchan;
02110    p->subs[b].owner = towner;
02111    p->subs[b].inthreeway = tinthreeway;
02112 
02113    if (p->subs[a].owner)
02114       ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
02115    if (p->subs[b].owner)
02116       ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
02117    wakeup_sub(p, a, NULL);
02118    wakeup_sub(p, b, NULL);
02119 }
02120 
02121 static int dahdi_open(char *fn)
02122 {
02123    int fd;
02124    int isnum;
02125    int chan = 0;
02126    int bs;
02127    int x;
02128    isnum = 1;
02129    for (x = 0; x < strlen(fn); x++) {
02130       if (!isdigit(fn[x])) {
02131          isnum = 0;
02132          break;
02133       }
02134    }
02135    if (isnum) {
02136       chan = atoi(fn);
02137       if (chan < 1) {
02138          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
02139          return -1;
02140       }
02141       fn = "/dev/dahdi/channel";
02142    }
02143    fd = open(fn, O_RDWR | O_NONBLOCK);
02144    if (fd < 0) {
02145       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
02146       return -1;
02147    }
02148    if (chan) {
02149       if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
02150          x = errno;
02151          close(fd);
02152          errno = x;
02153          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
02154          return -1;
02155       }
02156    }
02157    bs = READ_SIZE;
02158    if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
02159       ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
02160       x = errno;
02161       close(fd);
02162       errno = x;
02163       return -1;
02164    }
02165    return fd;
02166 }
02167 
02168 static void dahdi_close(int fd)
02169 {
02170    if (fd > 0)
02171       close(fd);
02172 }
02173 
02174 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
02175 {
02176    dahdi_close(chan_pvt->subs[sub_num].dfd);
02177    chan_pvt->subs[sub_num].dfd = -1;
02178 }
02179 
02180 #if defined(HAVE_PRI)
02181 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
02182 {
02183    dahdi_close(pri->fds[fd_num]);
02184    pri->fds[fd_num] = -1;
02185 }
02186 #endif   /* defined(HAVE_PRI) */
02187 
02188 #if defined(HAVE_SS7)
02189 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
02190 {
02191    dahdi_close(ss7->fds[fd_num]);
02192    ss7->fds[fd_num] = -1;
02193 }
02194 #endif   /* defined(HAVE_SS7) */
02195 
02196 static int dahdi_setlinear(int dfd, int linear)
02197 {
02198    int res;
02199    res = ioctl(dfd, DAHDI_SETLINEAR, &linear);
02200    if (res)
02201       return res;
02202    return 0;
02203 }
02204 
02205 
02206 static int alloc_sub(struct dahdi_pvt *p, int x)
02207 {
02208    struct dahdi_bufferinfo bi;
02209    int res;
02210    if (p->subs[x].dfd >= 0) {
02211       ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
02212       return -1;
02213    }
02214 
02215    p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
02216    if (p->subs[x].dfd <= -1) {
02217       ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
02218       return -1;
02219    }
02220 
02221    res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
02222    if (!res) {
02223       bi.txbufpolicy = p->buf_policy;
02224       bi.rxbufpolicy = p->buf_policy;
02225       bi.numbufs = p->buf_no;
02226       res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
02227       if (res < 0) {
02228          ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
02229       }
02230    } else
02231       ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
02232 
02233    if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
02234       ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
02235       dahdi_close_sub(p, x);
02236       p->subs[x].dfd = -1;
02237       return -1;
02238    }
02239    ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
02240    return 0;
02241 }
02242 
02243 static int unalloc_sub(struct dahdi_pvt *p, int x)
02244 {
02245    if (!x) {
02246       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
02247       return -1;
02248    }
02249    ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
02250    dahdi_close_sub(p, x);
02251    p->subs[x].linear = 0;
02252    p->subs[x].chan = 0;
02253    p->subs[x].owner = NULL;
02254    p->subs[x].inthreeway = 0;
02255    p->polarity = POLARITY_IDLE;
02256    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
02257    return 0;
02258 }
02259 
02260 static int digit_to_dtmfindex(char digit)
02261 {
02262    if (isdigit(digit))
02263       return DAHDI_TONE_DTMF_BASE + (digit - '0');
02264    else if (digit >= 'A' && digit <= 'D')
02265       return DAHDI_TONE_DTMF_A + (digit - 'A');
02266    else if (digit >= 'a' && digit <= 'd')
02267       return DAHDI_TONE_DTMF_A + (digit - 'a');
02268    else if (digit == '*')
02269       return DAHDI_TONE_DTMF_s;
02270    else if (digit == '#')
02271       return DAHDI_TONE_DTMF_p;
02272    else
02273       return -1;
02274 }
02275 
02276 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
02277 {
02278    struct dahdi_pvt *pvt;
02279    int idx;
02280    int dtmf = -1;
02281 
02282    pvt = chan->tech_pvt;
02283 
02284    ast_mutex_lock(&pvt->lock);
02285 
02286    idx = dahdi_get_index(chan, pvt, 0);
02287 
02288    if ((idx != SUB_REAL) || !pvt->owner)
02289       goto out;
02290 
02291 #ifdef HAVE_PRI
02292    if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
02293          && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
02294       if (pvt->setup_ack) {
02295          if (!pri_grab(pvt, pvt->pri)) {
02296             pri_information(pvt->pri->pri, pvt->call, digit);
02297             pri_rel(pvt->pri);
02298          } else
02299             ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
02300       } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
02301          int res;
02302          ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
02303          res = strlen(pvt->dialdest);
02304          pvt->dialdest[res++] = digit;
02305          pvt->dialdest[res] = '\0';
02306       }
02307       goto out;
02308    }
02309 #endif
02310    if ((dtmf = digit_to_dtmfindex(digit)) == -1)
02311       goto out;
02312 
02313    if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
02314       int res;
02315       struct dahdi_dialoperation zo = {
02316          .op = DAHDI_DIAL_OP_APPEND,
02317       };
02318 
02319       zo.dialstr[0] = 'T';
02320       zo.dialstr[1] = digit;
02321       zo.dialstr[2] = '\0';
02322       if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
02323          ast_log(LOG_WARNING, "Couldn't dial digit %c: %s\n", digit, strerror(errno));
02324       else
02325          pvt->dialing = 1;
02326    } else {
02327       ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
02328       pvt->dialing = 1;
02329       pvt->begindigit = digit;
02330    }
02331 
02332 out:
02333    ast_mutex_unlock(&pvt->lock);
02334 
02335    return 0;
02336 }
02337 
02338 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
02339 {
02340    struct dahdi_pvt *pvt;
02341    int res = 0;
02342    int idx;
02343    int x;
02344 
02345    pvt = chan->tech_pvt;
02346 
02347    ast_mutex_lock(&pvt->lock);
02348 
02349    idx = dahdi_get_index(chan, pvt, 0);
02350 
02351    if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
02352       goto out;
02353 
02354 #ifdef HAVE_PRI
02355    /* This means that the digit was already sent via PRI signalling */
02356    if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
02357          && !pvt->begindigit)
02358       goto out;
02359 #endif
02360 
02361    if (pvt->begindigit) {
02362       x = -1;
02363       ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
02364       res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
02365       pvt->dialing = 0;
02366       pvt->begindigit = 0;
02367    }
02368 
02369 out:
02370    ast_mutex_unlock(&pvt->lock);
02371 
02372    return res;
02373 }
02374 
02375 static char *events[] = {
02376    "No event",
02377    "On hook",
02378    "Ring/Answered",
02379    "Wink/Flash",
02380    "Alarm",
02381    "No more alarm",
02382    "HDLC Abort",
02383    "HDLC Overrun",
02384    "HDLC Bad FCS",
02385    "Dial Complete",
02386    "Ringer On",
02387    "Ringer Off",
02388    "Hook Transition Complete",
02389    "Bits Changed",
02390    "Pulse Start",
02391    "Timer Expired",
02392    "Timer Ping",
02393    "Polarity Reversal",
02394    "Ring Begin",
02395 };
02396 
02397 static struct {
02398    int alarm;
02399    char *name;
02400 } alarms[] = {
02401    { DAHDI_ALARM_RED, "Red Alarm" },
02402    { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
02403    { DAHDI_ALARM_BLUE, "Blue Alarm" },
02404    { DAHDI_ALARM_RECOVER, "Recovering" },
02405    { DAHDI_ALARM_LOOPBACK, "Loopback" },
02406    { DAHDI_ALARM_NOTOPEN, "Not Open" },
02407    { DAHDI_ALARM_NONE, "None" },
02408 };
02409 
02410 static char *alarm2str(int alm)
02411 {
02412    int x;
02413    for (x = 0; x < ARRAY_LEN(alarms); x++) {
02414       if (alarms[x].alarm & alm)
02415          return alarms[x].name;
02416    }
02417    return alm ? "Unknown Alarm" : "No Alarm";
02418 }
02419 
02420 static char *event2str(int event)
02421 {
02422    static char buf[256];
02423    if ((event < (ARRAY_LEN(events))) && (event > -1))
02424       return events[event];
02425    sprintf(buf, "Event %d", event); /* safe */
02426    return buf;
02427 }
02428 
02429 #ifdef HAVE_PRI
02430 static char *dialplan2str(int dialplan)
02431 {
02432    if (dialplan == -1 || dialplan == -2) {
02433       return("Dynamically set dialplan in ISDN");
02434    }
02435    return (pri_plan2str(dialplan));
02436 }
02437 #endif
02438 
02439 static char *dahdi_sig2str(int sig)
02440 {
02441    static char buf[256];
02442    switch (sig) {
02443    case SIG_EM:
02444       return "E & M Immediate";
02445    case SIG_EMWINK:
02446       return "E & M Wink";
02447    case SIG_EM_E1:
02448       return "E & M E1";
02449    case SIG_FEATD:
02450       return "Feature Group D (DTMF)";
02451    case SIG_FEATDMF:
02452       return "Feature Group D (MF)";
02453    case SIG_FEATDMF_TA:
02454       return "Feature Groud D (MF) Tandem Access";
02455    case SIG_FEATB:
02456       return "Feature Group B (MF)";
02457    case SIG_E911:
02458       return "E911 (MF)";
02459    case SIG_FGC_CAMA:
02460       return "FGC/CAMA (Dialpulse)";
02461    case SIG_FGC_CAMAMF:
02462       return "FGC/CAMA (MF)";
02463    case SIG_FXSLS:
02464       return "FXS Loopstart";
02465    case SIG_FXSGS:
02466       return "FXS Groundstart";
02467    case SIG_FXSKS:
02468       return "FXS Kewlstart";
02469    case SIG_FXOLS:
02470       return "FXO Loopstart";
02471    case SIG_FXOGS:
02472       return "FXO Groundstart";
02473    case SIG_FXOKS:
02474       return "FXO Kewlstart";
02475    case SIG_PRI:
02476       return "ISDN PRI";
02477    case SIG_BRI:
02478       return "ISDN BRI Point to Point";
02479    case SIG_BRI_PTMP:
02480       return "ISDN BRI Point to MultiPoint";
02481    case SIG_SS7:
02482       return "SS7";
02483    case SIG_MFCR2:
02484       return "MFC/R2";
02485    case SIG_SF:
02486       return "SF (Tone) Immediate";
02487    case SIG_SFWINK:
02488       return "SF (Tone) Wink";
02489    case SIG_SF_FEATD:
02490       return "SF (Tone) with Feature Group D (DTMF)";
02491    case SIG_SF_FEATDMF:
02492       return "SF (Tone) with Feature Group D (MF)";
02493    case SIG_SF_FEATB:
02494       return "SF (Tone) with Feature Group B (MF)";
02495    case SIG_GR303FXOKS:
02496       return "GR-303 with FXOKS";
02497    case SIG_GR303FXSKS:
02498       return "GR-303 with FXSKS";
02499    case 0:
02500       return "Pseudo";
02501    default:
02502       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
02503       return buf;
02504    }
02505 }
02506 
02507 #define sig2str dahdi_sig2str
02508 
02509 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
02510 {
02511    /* If the conference already exists, and we're already in it
02512       don't bother doing anything */
02513    struct dahdi_confinfo zi;
02514 
02515    memset(&zi, 0, sizeof(zi));
02516    zi.chan = 0;
02517 
02518    if (slavechannel > 0) {
02519       /* If we have only one slave, do a digital mon */
02520       zi.confmode = DAHDI_CONF_DIGITALMON;
02521       zi.confno = slavechannel;
02522    } else {
02523       if (!idx) {
02524          /* Real-side and pseudo-side both participate in conference */
02525          zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
02526             DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
02527       } else
02528          zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
02529       zi.confno = p->confno;
02530    }
02531    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
02532       return 0;
02533    if (c->dfd < 0)
02534       return 0;
02535    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
02536       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
02537       return -1;
02538    }
02539    if (slavechannel < 1) {
02540       p->confno = zi.confno;
02541    }
02542    memcpy(&c->curconf, &zi, sizeof(c->curconf));
02543    ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
02544    return 0;
02545 }
02546 
02547 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
02548 {
02549    /* If they're listening to our channel, they're ours */
02550    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
02551       return 1;
02552    /* If they're a talker on our (allocated) conference, they're ours */
02553    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
02554       return 1;
02555    return 0;
02556 }
02557 
02558 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
02559 {
02560    struct dahdi_confinfo zi;
02561    if (/* Can't delete if there's no dfd */
02562       (c->dfd < 0) ||
02563       /* Don't delete from the conference if it's not our conference */
02564       !isourconf(p, c)
02565       /* Don't delete if we don't think it's conferenced at all (implied) */
02566       ) return 0;
02567    memset(&zi, 0, sizeof(zi));
02568    if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
02569       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
02570       return -1;
02571    }
02572    ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
02573    memcpy(&c->curconf, &zi, sizeof(c->curconf));
02574    return 0;
02575 }
02576 
02577 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
02578 {
02579    int x;
02580    int useslavenative;
02581    struct dahdi_pvt *slave = NULL;
02582    /* Start out optimistic */
02583    useslavenative = 1;
02584    /* Update conference state in a stateless fashion */
02585    for (x = 0; x < 3; x++) {
02586       /* Any three-way calling makes slave native mode *definitely* out
02587          of the question */
02588       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
02589          useslavenative = 0;
02590    }
02591    /* If we don't have any 3-way calls, check to see if we have
02592       precisely one slave */
02593    if (useslavenative) {
02594       for (x = 0; x < MAX_SLAVES; x++) {
02595          if (p->slaves[x]) {
02596             if (slave) {
02597                /* Whoops already have a slave!  No
02598                   slave native and stop right away */
02599                slave = NULL;
02600                useslavenative = 0;
02601                break;
02602             } else {
02603                /* We have one slave so far */
02604                slave = p->slaves[x];
02605             }
02606          }
02607       }
02608    }
02609    /* If no slave, slave native definitely out */
02610    if (!slave)
02611       useslavenative = 0;
02612    else if (slave->law != p->law) {
02613       useslavenative = 0;
02614       slave = NULL;
02615    }
02616    if (out)
02617       *out = slave;
02618    return useslavenative;
02619 }
02620 
02621 static int reset_conf(struct dahdi_pvt *p)
02622 {
02623    p->confno = -1;
02624    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
02625    if (p->subs[SUB_REAL].dfd > -1) {
02626       struct dahdi_confinfo zi;
02627 
02628       memset(&zi, 0, sizeof(zi));
02629       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
02630          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
02631    }
02632    return 0;
02633 }
02634 
02635 static int update_conf(struct dahdi_pvt *p)
02636 {
02637    int needconf = 0;
02638    int x;
02639    int useslavenative;
02640    struct dahdi_pvt *slave = NULL;
02641 
02642    useslavenative = isslavenative(p, &slave);
02643    /* Start with the obvious, general stuff */
02644    for (x = 0; x < 3; x++) {
02645       /* Look for three way calls */
02646       if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
02647          conf_add(p, &p->subs[x], x, 0);
02648          needconf++;
02649       } else {
02650          conf_del(p, &p->subs[x], x);
02651       }
02652    }
02653    /* If we have a slave, add him to our conference now. or DAX
02654       if this is slave native */
02655    for (x = 0; x < MAX_SLAVES; x++) {
02656       if (p->slaves[x]) {
02657          if (useslavenative)
02658             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
02659          else {
02660             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
02661             needconf++;
02662          }
02663       }
02664    }
02665    /* If we're supposed to be in there, do so now */
02666    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
02667       if (useslavenative)
02668          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
02669       else {
02670          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
02671          needconf++;
02672       }
02673    }
02674    /* If we have a master, add ourselves to his conference */
02675    if (p->master) {
02676       if (isslavenative(p->master, NULL)) {
02677          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
02678       } else {
02679          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
02680       }
02681    }
02682    if (!needconf) {
02683       /* Nobody is left (or should be left) in our conference.
02684          Kill it. */
02685       p->confno = -1;
02686    }
02687    ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
02688    return 0;
02689 }
02690 
02691 static void dahdi_enable_ec(struct dahdi_pvt *p)
02692 {
02693    int x;
02694    int res;
02695    if (!p)
02696       return;
02697    if (p->echocanon) {
02698       ast_debug(1, "Echo cancellation already on\n");
02699       return;
02700    }
02701    if (p->digital) {
02702       ast_debug(1, "Echo cancellation isn't required on digital connection\n");
02703       return;
02704    }
02705    if (p->echocancel.head.tap_length) {
02706       if ((p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP) || (p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
02707          x = 1;
02708          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
02709          if (res)
02710             ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
02711       }
02712       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
02713       if (res) {
02714          ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
02715       } else {
02716          p->echocanon = 1;
02717          ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
02718       }
02719    } else
02720       ast_debug(1, "No echo cancellation requested\n");
02721 }
02722 
02723 static void dahdi_train_ec(struct dahdi_pvt *p)
02724 {
02725    int x;
02726    int res;
02727 
02728    if (p && p->echocanon && p->echotraining) {
02729       x = p->echotraining;
02730       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
02731       if (res)
02732          ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
02733       else
02734          ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
02735    } else {
02736       ast_debug(1, "No echo training requested\n");
02737    }
02738 }
02739 
02740 static void dahdi_disable_ec(struct dahdi_pvt *p)
02741 {
02742    int res;
02743 
02744    if (p->echocanon) {
02745       struct dahdi_echocanparams ecp = { .tap_length = 0 };
02746 
02747       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
02748 
02749       if (res)
02750          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
02751       else
02752          ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
02753    }
02754 
02755    p->echocanon = 0;
02756 }
02757 
02758 static void fill_txgain(struct dahdi_gains *g, float gain, int law)
02759 {
02760    int j;
02761    int k;
02762    float linear_gain = pow(10.0, gain / 20.0);
02763 
02764    switch (law) {
02765    case DAHDI_LAW_ALAW:
02766       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
02767          if (gain) {
02768             k = (int) (((float) AST_ALAW(j)) * linear_gain);
02769             if (k > 32767) k = 32767;
02770             if (k < -32767) k = -32767;
02771             g->txgain[j] = AST_LIN2A(k);
02772          } else {
02773             g->txgain[j] = j;
02774          }
02775       }
02776       break;
02777    case DAHDI_LAW_MULAW:
02778       for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
02779          if (gain) {
02780             k = (int) (((float) AST_MULAW(j)) * linear_gain);
02781             if (k > 32767) k = 32767;
02782             if (k < -32767) k = -32767;
02783             g->txgain[j] = AST_LIN2MU(k);
02784          } else {
02785             g->txgain[j] = j;
02786          }
02787       }
02788       break;
02789    }
02790 }
02791 
02792 static void fill_rxgain(struct dahdi_gains *g, float gain, int law)
02793 {
02794    int j;
02795    int k;
02796    float linear_gain = pow(10.0, gain / 20.0);
02797 
02798    switch (law) {
02799    case DAHDI_LAW_ALAW:
02800       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
02801          if (gain) {
02802             k = (int) (((float) AST_ALAW(j)) * linear_gain);
02803             if (k > 32767) k = 32767;
02804             if (k < -32767) k = -32767;
02805             g->rxgain[j] = AST_LIN2A(k);
02806          } else {
02807             g->rxgain[j] = j;
02808          }
02809       }
02810       break;
02811    case DAHDI_LAW_MULAW:
02812       for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
02813          if (gain) {
02814             k = (int) (((float) AST_MULAW(j)) * linear_gain);
02815             if (k > 32767) k = 32767;
02816             if (k < -32767) k = -32767;
02817             g->rxgain[j] = AST_LIN2MU(k);
02818          } else {
02819             g->rxgain[j] = j;
02820          }
02821       }
02822       break;
02823    }
02824 }
02825 
02826 static int set_actual_txgain(int fd, int chan, float gain, int law)
02827 {
02828    struct dahdi_gains g;
02829    int res;
02830 
02831    memset(&g, 0, sizeof(g));
02832    g.chan = chan;
02833    res = ioctl(fd, DAHDI_GETGAINS, &g);
02834    if (res) {
02835       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
02836       return res;
02837    }
02838 
02839    fill_txgain(&g, gain, law);
02840 
02841    return ioctl(fd, DAHDI_SETGAINS, &g);
02842 }
02843 
02844 static int set_actual_rxgain(int fd, int chan, float gain, int law)
02845 {
02846    struct dahdi_gains g;
02847    int res;
02848 
02849    memset(&g, 0, sizeof(g));
02850    g.chan = chan;
02851    res = ioctl(fd, DAHDI_GETGAINS, &g);
02852    if (res) {
02853       ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
02854       return res;
02855    }
02856 
02857    fill_rxgain(&g, gain, law);
02858 
02859    return ioctl(fd, DAHDI_SETGAINS, &g);
02860 }
02861 
02862 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
02863 {
02864    return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
02865 }
02866 
02867 static int bump_gains(struct dahdi_pvt *p)
02868 {
02869    int res;
02870 
02871    /* Bump receive gain by value stored in cid_rxgain */
02872    res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
02873    if (res) {
02874       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
02875       return -1;
02876    }
02877 
02878    return 0;
02879 }
02880 
02881 static int restore_gains(struct dahdi_pvt *p)
02882 {
02883    int res;
02884 
02885    res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
02886    if (res) {
02887       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
02888       return -1;
02889    }
02890 
02891    return 0;
02892 }
02893 
02894 static inline int dahdi_set_hook(int fd, int hs)
02895 {
02896    int x, res;
02897 
02898    x = hs;
02899    res = ioctl(fd, DAHDI_HOOK, &x);
02900 
02901    if (res < 0) {
02902       if (errno == EINPROGRESS)
02903          return 0;
02904       ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
02905       /* will expectedly fail if phone is off hook during operation, such as during a restart */
02906    }
02907 
02908    return res;
02909 }
02910 
02911 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
02912 {
02913    int x, y, res;
02914    x = muted;
02915    if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
02916       y = 1;
02917       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
02918       if (res)
02919          ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n", p->channel, strerror(errno));
02920    }
02921    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
02922    if (res < 0)
02923       ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
02924    return res;
02925 }
02926 
02927 static int save_conference(struct dahdi_pvt *p)
02928 {
02929    struct dahdi_confinfo c;
02930    int res;
02931    if (p->saveconf.confmode) {
02932       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
02933       return -1;
02934    }
02935    p->saveconf.chan = 0;
02936    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
02937    if (res) {
02938       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
02939       p->saveconf.confmode = 0;
02940       return -1;
02941    }
02942    memset(&c, 0, sizeof(c));
02943    c.confmode = DAHDI_CONF_NORMAL;
02944    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
02945    if (res) {
02946       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
02947       return -1;
02948    }
02949    ast_debug(1, "Disabled conferencing\n");
02950    return 0;
02951 }
02952 
02953 /*!
02954  * \brief Send MWI state change
02955  *
02956  * \arg mailbox_full This is the mailbox associated with the FXO line that the
02957  *      MWI state has changed on.
02958  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
02959  *      whether there are messages waiting or not.
02960  *
02961  *  \return nothing
02962  *
02963  * This function does two things:
02964  *
02965  * 1) It generates an internal Asterisk event notifying any other module that
02966  *    cares about MWI that the state of a mailbox has changed.
02967  *
02968  * 2) It runs the script specified by the mwimonitornotify option to allow
02969  *    some custom handling of the state change.
02970  */
02971 static void notify_message(char *mailbox_full, int thereornot)
02972 {
02973    char s[sizeof(mwimonitornotify) + 80];
02974    struct ast_event *event;
02975    char *mailbox, *context;
02976 
02977    /* Strip off @default */
02978    context = mailbox = ast_strdupa(mailbox_full);
02979    strsep(&context, "@");
02980    if (ast_strlen_zero(context))
02981       context = "default";
02982 
02983    if (!(event = ast_event_new(AST_EVENT_MWI,
02984          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
02985          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
02986          AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
02987          AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
02988          AST_EVENT_IE_END))) {
02989       return;
02990    }
02991 
02992    ast_event_queue_and_cache(event);
02993 
02994    if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
02995       snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
02996       ast_safe_system(s);
02997    }
02998 }
02999 
03000 static int restore_conference(struct dahdi_pvt *p)
03001 {
03002    int res;
03003    if (p->saveconf.confmode) {
03004       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
03005       p->saveconf.confmode = 0;
03006       if (res) {
03007          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
03008          return -1;
03009       }
03010    }
03011    ast_debug(1, "Restored conferencing\n");
03012    return 0;
03013 }
03014 
03015 static int send_callerid(struct dahdi_pvt *p);
03016 
03017 static int send_cwcidspill(struct dahdi_pvt *p)
03018 {
03019    p->callwaitcas = 0;
03020    p->cidcwexpire = 0;
03021    if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
03022       return -1;
03023    p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
03024    /* Make sure we account for the end */
03025    p->cidlen += READ_SIZE * 4;
03026    p->cidpos = 0;
03027    send_callerid(p);
03028    ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
03029    return 0;
03030 }
03031 
03032 static int has_voicemail(struct dahdi_pvt *p)
03033 {
03034    int new_msgs;
03035    struct ast_event *event;
03036    char *mailbox, *context;
03037 
03038    mailbox = context = ast_strdupa(p->mailbox);
03039    strsep(&context, "@");
03040    if (ast_strlen_zero(context))
03041       context = "default";
03042 
03043    event = ast_event_get_cached(AST_EVENT_MWI,
03044       AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
03045       AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
03046       AST_EVENT_IE_END);
03047 
03048    if (event) {
03049       new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
03050       ast_event_destroy(event);
03051    } else
03052       new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
03053 
03054    return new_msgs;
03055 }
03056 
03057 static int send_callerid(struct dahdi_pvt *p)
03058 {
03059    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
03060    int res;
03061    /* Take out of linear mode if necessary */
03062    if (p->subs[SUB_REAL].linear) {
03063       p->subs[SUB_REAL].linear = 0;
03064       dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
03065    }
03066    while (p->cidpos < p->cidlen) {
03067       res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
03068       if (res < 0) {
03069          if (errno == EAGAIN)
03070             return 0;
03071          else {
03072             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
03073             return -1;
03074          }
03075       }
03076       if (!res)
03077          return 0;
03078       p->cidpos += res;
03079    }
03080    ast_free(p->cidspill);
03081    p->cidspill = NULL;
03082    if (p->callwaitcas) {
03083       /* Wait for CID/CW to expire */
03084       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
03085    } else
03086       restore_conference(p);
03087    return 0;
03088 }
03089 
03090 static int dahdi_callwait(struct ast_channel *ast)
03091 {
03092    struct dahdi_pvt *p = ast->tech_pvt;
03093    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
03094    if (p->cidspill) {
03095       ast_log(LOG_WARNING, "Spill already exists?!?\n");
03096       ast_free(p->cidspill);
03097    }
03098    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
03099       return -1;
03100    save_conference(p);
03101    /* Silence */
03102    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
03103    if (!p->callwaitrings && p->callwaitingcallerid) {
03104       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
03105       p->callwaitcas = 1;
03106       p->cidlen = 2400 + 680 + READ_SIZE * 4;
03107    } else {
03108       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
03109       p->callwaitcas = 0;
03110       p->cidlen = 2400 + READ_SIZE * 4;
03111    }
03112    p->cidpos = 0;
03113    send_callerid(p);
03114 
03115    return 0;
03116 }
03117 
03118 #if defined(HAVE_SS7)
03119 static unsigned char cid_pres2ss7pres(int cid_pres)
03120 {
03121     return (cid_pres >> 5) & 0x03;
03122 }
03123 #endif   /* defined(HAVE_SS7) */
03124 
03125 #if defined(HAVE_SS7)
03126 static unsigned char cid_pres2ss7screen(int cid_pres)
03127 {
03128    return cid_pres & 0x03;
03129 }
03130 #endif   /* defined(HAVE_SS7) */
03131 
03132 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
03133 {
03134    struct dahdi_pvt *p = ast->tech_pvt;
03135    int x, res, idx,mysig;
03136    char *c, *n, *l;
03137 #ifdef HAVE_PRI
03138    char *s = NULL;
03139 #endif
03140    char dest[256]; /* must be same length as p->dialdest */
03141    ast_mutex_lock(&p->lock);
03142    ast_copy_string(dest, rdest, sizeof(dest));
03143    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
03144    if ((ast->_state == AST_STATE_BUSY)) {
03145       p->subs[SUB_REAL].needbusy = 1;
03146       ast_mutex_unlock(&p->lock);
03147       return 0;
03148    }
03149    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
03150       ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
03151       ast_mutex_unlock(&p->lock);
03152       return -1;
03153    }
03154    p->waitingfordt.tv_sec = 0;
03155    p->dialednone = 0;
03156    if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
03157    {
03158       /* Special pseudo -- automatically up */
03159       ast_setstate(ast, AST_STATE_UP);
03160       ast_mutex_unlock(&p->lock);
03161       return 0;
03162    }
03163    x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
03164    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
03165    if (res)
03166       ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
03167    p->outgoing = 1;
03168 
03169    if (IS_DIGITAL(ast->transfercapability)){
03170       set_actual_gain(p->subs[SUB_REAL].dfd, 0, 0, 0, p->law);
03171    } else {
03172       set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
03173    }  
03174 
03175    mysig = p->sig;
03176    if (p->outsigmod > -1)
03177       mysig = p->outsigmod;
03178 
03179    switch (mysig) {
03180    case SIG_FXOLS:
03181    case SIG_FXOGS:
03182    case SIG_FXOKS:
03183       if (p->owner == ast) {
03184          /* Normal ring, on hook */
03185 
03186          /* Don't send audio while on hook, until the call is answered */
03187          p->dialing = 1;
03188          if (p->use_callerid) {
03189             /* Generate the Caller-ID spill if desired */
03190             if (p->cidspill) {
03191                ast_log(LOG_WARNING, "cidspill already exists??\n");
03192                ast_free(p->cidspill);
03193             }
03194             p->callwaitcas = 0;
03195             if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
03196                p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
03197                p->cidpos = 0;
03198                send_callerid(p);
03199             }
03200          }
03201          /* Choose proper cadence */
03202          if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
03203             if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
03204                ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast->name, strerror(errno));
03205             p->cidrings = cidrings[p->distinctivering - 1];
03206          } else {
03207             if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
03208                ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast->name, strerror(errno));
03209             p->cidrings = p->sendcalleridafter;
03210          }
03211 
03212          /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
03213          c = strchr(dest, '/');
03214          if (c)
03215             c++;
03216          if (c && (strlen(c) < p->stripmsd)) {
03217             ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
03218             c = NULL;
03219          }
03220          if (c) {
03221             p->dop.op = DAHDI_DIAL_OP_REPLACE;
03222             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
03223             ast_debug(1, "FXO: setup deferred dialstring: %s\n", c);
03224          } else {
03225             p->dop.dialstr[0] = '\0';
03226          }
03227          x = DAHDI_RING;
03228          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x) && (errno != EINPROGRESS)) {
03229             ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
03230             ast_mutex_unlock(&p->lock);
03231             return -1;
03232          }
03233          p->dialing = 1;
03234       } else {
03235          /* Call waiting call */
03236          p->callwaitrings = 0;
03237          if (ast->cid.cid_num)
03238             ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
03239          else
03240             p->callwait_num[0] = '\0';
03241          if (ast->cid.cid_name)
03242             ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
03243          else
03244             p->callwait_name[0] = '\0';
03245          /* Call waiting tone instead */
03246          if (dahdi_callwait(ast)) {
03247             ast_mutex_unlock(&p->lock);
03248             return -1;
03249          }
03250          /* Make ring-back */
03251          if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].dfd, DAHDI_TONE_RINGTONE))
03252             ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
03253       }
03254       n = ast->cid.cid_name;
03255       l = ast->cid.cid_num;
03256       if (l)
03257          ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
03258       else
03259          p->lastcid_num[0] = '\0';
03260       if (n)
03261          ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
03262       else
03263          p->lastcid_name[0] = '\0';
03264       ast_setstate(ast, AST_STATE_RINGING);
03265       idx = dahdi_get_index(ast, p, 0);
03266       if (idx > -1) {
03267          p->subs[idx].needringing = 1;
03268       }
03269       break;
03270    case SIG_FXSLS:
03271    case SIG_FXSGS:
03272    case SIG_FXSKS:
03273       if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
03274          ast_debug(1, "Ignore possible polarity reversal on line seizure\n");
03275          p->polaritydelaytv = ast_tvnow();
03276       }
03277       /* fall through */
03278    case SIG_EMWINK:
03279    case SIG_EM:
03280    case SIG_EM_E1:
03281    case SIG_FEATD:
03282    case SIG_FEATDMF:
03283    case SIG_E911:
03284    case SIG_FGC_CAMA:
03285    case SIG_FGC_CAMAMF:
03286    case SIG_FEATB:
03287    case SIG_SFWINK:
03288    case SIG_SF:
03289    case SIG_SF_FEATD:
03290    case SIG_SF_FEATDMF:
03291    case SIG_FEATDMF_TA:
03292    case SIG_SF_FEATB:
03293       c = strchr(dest, '/');
03294       if (c)
03295          c++;
03296       else
03297          c = "";
03298       if (strlen(c) < p->stripmsd) {
03299          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
03300          ast_mutex_unlock(&p->lock);
03301          return -1;
03302       }
03303 #ifdef HAVE_PRI
03304       /* Start the trunk, if not GR-303 */
03305       if (!p->pri) {
03306 #endif
03307          x = DAHDI_START;
03308          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
03309          if (res < 0) {
03310             if (errno != EINPROGRESS) {
03311                ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
03312                ast_mutex_unlock(&p->lock);
03313                return -1;
03314             }
03315          }
03316 #ifdef HAVE_PRI
03317       }
03318 #endif
03319       ast_debug(1, "Dialing '%s'\n", c);
03320       p->dop.op = DAHDI_DIAL_OP_REPLACE;
03321 
03322       c += p->stripmsd;
03323 
03324       switch (mysig) {
03325       case SIG_FEATD:
03326          l = ast->cid.cid_num;
03327          if (l)
03328             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
03329          else
03330             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
03331          break;
03332       case SIG_FEATDMF:
03333          l = ast->cid.cid_num;
03334          if (l)
03335             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
03336          else
03337             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
03338          break;
03339       case SIG_FEATDMF_TA:
03340       {
03341          const char *cic, *ozz;
03342 
03343          /* If you have to go through a Tandem Access point you need to use this */
03344          ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
03345          if (!ozz)
03346             ozz = defaultozz;
03347          cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
03348          if (!cic)
03349             cic = defaultcic;
03350          if (!ozz || !cic) {
03351             ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
03352             ast_mutex_unlock(&p->lock);
03353             return -1;
03354          }
03355          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
03356          snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
03357          p->whichwink = 0;
03358       }
03359          break;
03360       case SIG_E911:
03361          ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
03362          break;
03363       case SIG_FGC_CAMA:
03364          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
03365          break;
03366       case SIG_FGC_CAMAMF:
03367       case SIG_FEATB:
03368          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
03369          break;
03370       default:
03371          if (p->pulse)
03372             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
03373          else
03374             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
03375          break;
03376       }
03377 
03378       if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
03379          memset(p->echorest, 'w', sizeof(p->echorest) - 1);
03380          strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
03381          p->echorest[sizeof(p->echorest) - 1] = '\0';
03382          p->echobreak = 1;
03383          p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
03384       } else
03385          p->echobreak = 0;
03386 
03387       /* waitfordialtone ? */
03388 #ifdef HAVE_PRI
03389       if (!p->pri) {
03390 #endif
03391          if( p->waitfordialtone && CANPROGRESSDETECT(p) && p->dsp ) {
03392             ast_log(LOG_DEBUG, "Defer dialling for %dms or dialtone\n", p->waitfordialtone);
03393             gettimeofday(&p->waitingfordt,NULL);
03394             ast_setstate(ast, AST_STATE_OFFHOOK);
03395             break;
03396          }
03397 #ifdef HAVE_PRI
03398       }
03399 #endif
03400       if (!res) {
03401          if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
03402             int saveerr = errno;
03403 
03404             x = DAHDI_ONHOOK;
03405             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
03406             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
03407             ast_mutex_unlock(&p->lock);
03408             return -1;
03409          }
03410       } else
03411          ast_debug(1, "Deferring dialing...\n");
03412 
03413       p->dialing = 1;
03414       if (ast_strlen_zero(c))
03415          p->dialednone = 1;
03416       ast_setstate(ast, AST_STATE_DIALING);
03417       break;
03418    case 0:
03419       /* Special pseudo -- automatically up*/
03420       ast_setstate(ast, AST_STATE_UP);
03421       break;
03422    case SIG_PRI:
03423    case SIG_BRI:
03424    case SIG_BRI_PTMP:
03425    case SIG_SS7:
03426    case SIG_MFCR2:
03427       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
03428       p->dialdest[0] = '\0';
03429       p->dialing = 1;
03430       break;
03431    default:
03432       ast_debug(1, "not yet implemented\n");
03433       ast_mutex_unlock(&p->lock);
03434       return -1;
03435    }
03436 #ifdef HAVE_SS7
03437    if (p->ss7) {
03438       char ss7_called_nai;
03439       int called_nai_strip;
03440       char ss7_calling_nai;
03441       int calling_nai_strip;
03442       const char *charge_str = NULL;
03443       const char *gen_address = NULL;
03444       const char *gen_digits = NULL;
03445       const char *gen_dig_type = NULL;
03446       const char *gen_dig_scheme = NULL;
03447       const char *gen_name = NULL;
03448       const char *jip_digits = NULL;
03449       const char *lspi_ident = NULL;
03450       const char *rlt_flag = NULL;
03451       const char *call_ref_id = NULL;
03452       const char *call_ref_pc = NULL;
03453       const char *send_far = NULL;
03454 
03455       c = strchr(dest, '/');
03456       if (c) {
03457          c++;
03458       } else {
03459          c = "";
03460       }
03461       if (strlen(c) < p->stripmsd) {
03462          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
03463          ast_mutex_unlock(&p->lock);
03464          return -1;
03465       }
03466 
03467       if (!p->hidecallerid) {
03468          l = ast->cid.cid_num;
03469       } else {
03470          l = NULL;
03471       }
03472 
03473       if (ss7_grab(p, p->ss7)) {
03474          ast_log(LOG_WARNING, "Failed to grab SS7!\n");
03475          ast_mutex_unlock(&p->lock);
03476          return -1;
03477       }
03478       p->digital = IS_DIGITAL(ast->transfercapability);
03479       p->ss7call = isup_new_call(p->ss7->ss7);
03480 
03481       if (!p->ss7call) {
03482          ss7_rel(p->ss7);
03483          ast_mutex_unlock(&p->lock);
03484          ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
03485          return -1;
03486       }
03487 
03488       called_nai_strip = 0;
03489       ss7_called_nai = p->ss7->called_nai;
03490       if (ss7_called_nai == SS7_NAI_DYNAMIC) { /* compute dynamically */
03491          if (strncmp(c + p->stripmsd, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
03492             called_nai_strip = strlen(p->ss7->internationalprefix);
03493             ss7_called_nai = SS7_NAI_INTERNATIONAL;
03494          } else if (strncmp(c + p->stripmsd, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
03495             called_nai_strip = strlen(p->ss7->nationalprefix);
03496             ss7_called_nai = SS7_NAI_NATIONAL;
03497          } else {
03498             ss7_called_nai = SS7_NAI_SUBSCRIBER;
03499          }
03500       }
03501       isup_set_called(p->ss7call, c + p->stripmsd + called_nai_strip, ss7_called_nai, p->ss7->ss7);
03502 
03503       calling_nai_strip = 0;
03504       ss7_calling_nai = p->ss7->calling_nai;
03505       if ((l != NULL) && (ss7_calling_nai == SS7_NAI_DYNAMIC)) { /* compute dynamically */
03506          if (strncmp(l, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
03507             calling_nai_strip = strlen(p->ss7->internationalprefix);
03508             ss7_calling_nai = SS7_NAI_INTERNATIONAL;
03509          } else if (strncmp(l, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
03510             calling_nai_strip = strlen(p->ss7->nationalprefix);
03511             ss7_calling_nai = SS7_NAI_NATIONAL;
03512          } else {
03513             ss7_calling_nai = SS7_NAI_SUBSCRIBER;
03514          }
03515       }
03516       isup_set_calling(p->ss7call, l ? (l + calling_nai_strip) : NULL, ss7_calling_nai,
03517          p->use_callingpres ? cid_pres2ss7pres(ast->cid.cid_pres) : (l ? SS7_PRESENTATION_ALLOWED : SS7_PRESENTATION_RESTRICTED),
03518          p->use_callingpres ? cid_pres2ss7screen(ast->cid.cid_pres) : SS7_SCREENING_USER_PROVIDED );
03519 
03520       isup_set_oli(p->ss7call, ast->cid.cid_ani2);
03521       isup_init_call(p->ss7->ss7, p->ss7call, p->cic, p->dpc);
03522 
03523       ast_channel_lock(ast);
03524       /* Set the charge number if it is set */
03525       charge_str = pbx_builtin_getvar_helper(ast, "SS7_CHARGE_NUMBER");
03526       if (charge_str)
03527          isup_set_charge(p->ss7call, charge_str, SS7_ANI_CALLING_PARTY_SUB_NUMBER, 0x10);
03528 
03529       gen_address = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_ADDRESS");
03530       if (gen_address)
03531          isup_set_gen_address(p->ss7call, gen_address, p->gen_add_nai,p->gen_add_pres_ind, p->gen_add_num_plan,p->gen_add_type); /* need to add some types here for NAI,PRES,TYPE */
03532 
03533       gen_digits = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGITS");
03534       gen_dig_type = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGTYPE");
03535       gen_dig_scheme = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGSCHEME");
03536       if (gen_digits)
03537          isup_set_gen_digits(p->ss7call, gen_digits, atoi(gen_dig_type), atoi(gen_dig_scheme));
03538 
03539       gen_name = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_NAME");
03540       if (gen_name)
03541          isup_set_generic_name(p->ss7call, gen_name, GEN_NAME_TYPE_CALLING_NAME, GEN_NAME_AVAIL_AVAILABLE, GEN_NAME_PRES_ALLOWED);
03542 
03543       jip_digits = pbx_builtin_getvar_helper(ast, "SS7_JIP");
03544       if (jip_digits)
03545          isup_set_jip_digits(p->ss7call, jip_digits);
03546 
03547       lspi_ident = pbx_builtin_getvar_helper(ast, "SS7_LSPI_IDENT");
03548       if (lspi_ident)
03549          isup_set_lspi(p->ss7call, lspi_ident, 0x18, 0x7, 0x00);
03550 
03551       rlt_flag = pbx_builtin_getvar_helper(ast, "SS7_RLT_ON");
03552       if ((rlt_flag) && ((strncmp("NO", rlt_flag, strlen(rlt_flag))) != 0 )) {
03553          isup_set_lspi(p->ss7call, rlt_flag, 0x18, 0x7, 0x00); /* Setting for Nortel DMS-250/500 */
03554       }
03555 
03556       call_ref_id = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_IDENT");
03557       call_ref_pc = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_PC");
03558       if (call_ref_id && call_ref_pc) {
03559          isup_set_callref(p->ss7call, atoi(call_ref_id),
03560                 call_ref_pc ? atoi(call_ref_pc) : 0);
03561       }
03562 
03563       send_far = pbx_builtin_getvar_helper(ast, "SS7_SEND_FAR");
03564       if ((send_far) && ((strncmp("NO", send_far, strlen(send_far))) != 0 ))
03565          (isup_far(p->ss7->ss7, p->ss7call));
03566 
03567       ast_channel_unlock(ast);
03568 
03569       isup_iam(p->ss7->ss7, p->ss7call);
03570       ast_setstate(ast, AST_STATE_DIALING);
03571       ss7_rel(p->ss7);
03572    }
03573 #endif /* HAVE_SS7 */
03574 #ifdef HAVE_OPENR2
03575    if (p->mfcr2) {
03576       openr2_calling_party_category_t chancat;
03577       int callres = 0;
03578       char *c, *l;
03579 
03580       c = strchr(dest, '/');
03581       if (c) {
03582          c++;
03583       } else {
03584          c = "";
03585       }
03586       if (!p->hidecallerid) {
03587          l = ast->cid.cid_num;
03588       } else {
03589          l = NULL;
03590       }
03591       if (strlen(c) < p->stripmsd) {
03592          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
03593          ast_mutex_unlock(&p->lock);
03594          return -1;
03595       }
03596       p->dialing = 1;
03597       ast_channel_lock(ast);
03598       chancat = dahdi_r2_get_channel_category(ast);
03599       ast_channel_unlock(ast);
03600       callres = openr2_chan_make_call(p->r2chan, l, (c + p->stripmsd), chancat);
03601       if (-1 == callres) {
03602          ast_mutex_unlock(&p->lock);
03603          ast_log(LOG_ERROR, "unable to make new MFC/R2 call!\n");
03604          return -1;
03605       }
03606       ast_setstate(ast, AST_STATE_DIALING);
03607    }
03608 #endif /* HAVE_OPENR2 */
03609 #ifdef HAVE_PRI
03610    if (p->pri) {
03611       struct pri_sr *sr;
03612 #ifdef SUPPORT_USERUSER
03613       const char *useruser;
03614 #endif
03615       int pridialplan;
03616       int dp_strip;
03617       int prilocaldialplan;
03618       int ldp_strip;
03619       int exclusive;
03620       const char *rr_str;
03621       int redirect_reason;
03622 
03623       c = strchr(dest, '/');
03624       if (c) {
03625          c++;
03626       } else {
03627          c = "";
03628       }
03629 
03630       l = NULL;
03631       n = NULL;
03632       if (!p->hidecallerid) {
03633          /* If we get to the end of this loop without breaking, there's no
03634           * numeric calleridnum. This is done instead of testing for
03635           * "unknown" or the thousands of other ways that the calleridnum
03636           * could be invalid. */
03637          for (l = ast->cid.cid_num; l && *l; l++) {
03638             if (strchr("0123456789", *l)) {
03639                l = ast->cid.cid_num;
03640                break;
03641             }
03642          }
03643          if (!p->hidecalleridname) {
03644             n = ast->cid.cid_name;
03645          }
03646       }
03647 
03648       if (strlen(c) < p->stripmsd) {
03649          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
03650          ast_mutex_unlock(&p->lock);
03651          return -1;
03652       }
03653       if (mysig != SIG_FXSKS) {
03654          p->dop.op = DAHDI_DIAL_OP_REPLACE;
03655          s = strchr(c + p->stripmsd, 'w');
03656          if (s) {
03657             if (strlen(s) > 1)
03658                snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
03659             else
03660                p->dop.dialstr[0] = '\0';
03661             *s = '\0';
03662          } else {
03663             p->dop.dialstr[0] = '\0';
03664          }
03665       }
03666       if (pri_grab(p, p->pri)) {
03667          ast_log(LOG_WARNING, "Failed to grab PRI!\n");
03668          ast_mutex_unlock(&p->lock);
03669          return -1;
03670       }
03671       if (!(p->call = pri_new_call(p->pri->pri))) {
03672          ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
03673          pri_rel(p->pri);
03674          ast_mutex_unlock(&p->lock);
03675          return -1;
03676       }
03677       if (!(sr = pri_sr_new())) {
03678          ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
03679          pri_rel(p->pri);
03680          ast_mutex_unlock(&p->lock);
03681       }
03682       if (p->bearer || (mysig == SIG_FXSKS)) {
03683          if (p->bearer) {
03684             ast_debug(1, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
03685             p->bearer->call = p->call;
03686          } else
03687             ast_debug(1, "I'm being setup with no bearer right now...\n");
03688 
03689          pri_set_crv(p->pri->pri, p->call, p->channel, 0);
03690       }
03691       p->digital = IS_DIGITAL(ast->transfercapability);
03692 
03693       /* Should the picked channel be used exclusively? */
03694       if (p->priexclusive || p->pri->nodetype == PRI_NETWORK) {
03695          exclusive = 1;
03696       } else {
03697          exclusive = 0;
03698       }
03699 
03700       pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
03701       pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability,
03702          (p->digital ? -1 :
03703             ((p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
03704       if (p->pri->facilityenable)
03705          pri_facility_enable(p->pri->pri);
03706 
03707       ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
03708 
03709       dp_strip = 0;
03710       pridialplan = p->pri->dialplan - 1;
03711       if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
03712          if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
03713             if (pridialplan == -2) {
03714                dp_strip = strlen(p->pri->internationalprefix);
03715             }
03716             pridialplan = PRI_INTERNATIONAL_ISDN;
03717          } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
03718             if (pridialplan == -2) {
03719                dp_strip = strlen(p->pri->nationalprefix);
03720             }
03721             pridialplan = PRI_NATIONAL_ISDN;
03722          } else {
03723             pridialplan = PRI_LOCAL_ISDN;
03724          }
03725       }
03726       while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
03727          switch (c[p->stripmsd]) {
03728          case 'U':
03729             pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
03730             break;
03731          case 'I':
03732             pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
03733             break;
03734          case 'N':
03735             pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
03736             break;
03737          case 'L':
03738             pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
03739             break;
03740          case 'S':
03741             pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
03742             break;
03743          case 'V':
03744             pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
03745             break;
03746          case 'R':
03747             pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
03748             break;
03749          case 'u':
03750             pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
03751             break;
03752          case 'e':
03753             pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
03754             break;
03755          case 'x':
03756             pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
03757             break;
03758          case 'f':
03759             pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
03760             break;
03761          case 'n':
03762             pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
03763             break;
03764          case 'p':
03765             pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
03766             break;
03767          case 'r':
03768             pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
03769             break;
03770          default:
03771             if (isalpha(c[p->stripmsd])) {
03772                ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n",
03773                   c[p->stripmsd] > 'Z' ? "NPI" : "TON", c[p->stripmsd]);
03774             }
03775             break;
03776          }
03777          c++;
03778       }
03779       pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
03780 
03781       ldp_strip = 0;
03782       prilocaldialplan = p->pri->localdialplan - 1;
03783       if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
03784          if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
03785             if (prilocaldialplan == -2) {
03786                ldp_strip = strlen(p->pri->internationalprefix);
03787             }
03788             prilocaldialplan = PRI_INTERNATIONAL_ISDN;
03789          } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
03790             if (prilocaldialplan == -2) {
03791                ldp_strip = strlen(p->pri->nationalprefix);
03792             }
03793             prilocaldialplan = PRI_NATIONAL_ISDN;
03794          } else {
03795             prilocaldialplan = PRI_LOCAL_ISDN;
03796          }
03797       }
03798       if (l != NULL) {
03799          while (*l > '9' && *l != '*' && *l != '#') {
03800             switch (*l) {
03801             case 'U':
03802                prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
03803                break;
03804             case 'I':
03805                prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
03806                break;
03807             case 'N':
03808                prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
03809                break;
03810             case 'L':
03811                prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
03812                break;
03813             case 'S':
03814                prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
03815                break;
03816             case 'V':
03817                prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
03818                break;
03819             case 'R':
03820                prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
03821                break;
03822             case 'u':
03823                prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
03824                break;
03825             case 'e':
03826                prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
03827                break;
03828             case 'x':
03829                prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
03830                break;
03831             case 'f':
03832                prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
03833                break;
03834             case 'n':
03835                prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
03836                break;
03837             case 'p':
03838                prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
03839                break;
03840             case 'r':
03841                prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
03842                break;
03843             default:
03844                if (isalpha(*l)) {
03845                   ast_log(LOG_WARNING,
03846                      "Unrecognized prilocaldialplan %s modifier: %c\n",
03847                      *l > 'Z' ? "NPI" : "TON", *l);
03848                }
03849                break;
03850             }
03851             l++;
03852          }
03853       }
03854       pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
03855          p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
03856       if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
03857          if (!strcasecmp(rr_str, "UNKNOWN"))
03858             redirect_reason = 0;
03859          else if (!strcasecmp(rr_str, "BUSY"))
03860             redirect_reason = 1;
03861          else if (!strcasecmp(rr_str, "NO_REPLY") || !strcasecmp(rr_str, "NOANSWER"))
03862          /* the NOANSWER is to match diversion-reason from chan_sip, (which never reads PRIREDIRECTREASON) */
03863             redirect_reason = 2;
03864          else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
03865             redirect_reason = 15;
03866          else
03867             redirect_reason = PRI_REDIR_UNCONDITIONAL;
03868       } else
03869          redirect_reason = PRI_REDIR_UNCONDITIONAL;
03870       pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
03871 
03872 #ifdef SUPPORT_USERUSER
03873       /* User-user info */
03874       useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
03875       if (useruser)
03876          pri_sr_set_useruser(sr, useruser);
03877 #endif
03878 
03879       if (pri_setup(p->pri->pri, p->call, sr)) {
03880          ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n",
03881             c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
03882          pri_rel(p->pri);
03883          ast_mutex_unlock(&p->lock);
03884          pri_sr_free(sr);
03885          return -1;
03886       }
03887       pri_sr_free(sr);
03888       ast_setstate(ast, AST_STATE_DIALING);
03889       pri_rel(p->pri);
03890    }
03891 #endif
03892    ast_mutex_unlock(&p->lock);
03893    return 0;
03894 }
03895 
03896 static void destroy_dahdi_pvt(struct dahdi_pvt **pvt)
03897 {
03898    struct dahdi_pvt *p = *pvt;
03899    /* Remove channel from the list */
03900    if (p->prev)
03901       p->prev->next = p->next;
03902    if (p->next)
03903       p->next->prev = p->prev;
03904    if (p->use_smdi)
03905       ast_smdi_interface_unref(p->smdi_iface);
03906    if (p->mwi_event_sub)
03907       ast_event_unsubscribe(p->mwi_event_sub);
03908    if (p->vars) {
03909       ast_variables_destroy(p->vars);
03910    }
03911    ast_mutex_destroy(&p->lock);
03912    dahdi_close_sub(p, SUB_REAL);
03913    if (p->owner)
03914       p->owner->tech_pvt = NULL;
03915    free(p);
03916    *pvt = NULL;
03917 }
03918 
03919 static int destroy_channel(struct dahdi_pvt *prev, struct dahdi_pvt *cur, int now)
03920 {
03921    int owned = 0;
03922    int i = 0;
03923 
03924    if (!now) {
03925       if (cur->owner) {
03926          owned = 1;
03927       }
03928 
03929       for (i = 0; i < 3; i++) {
03930          if (cur->subs[i].owner) {
03931             owned = 1;
03932          }
03933       }
03934       if (!owned) {
03935          if (prev) {
03936             prev->next = cur->next;
03937             if (prev->next)
03938                prev->next->prev = prev;
03939             else
03940                ifend = prev;
03941          } else {
03942             iflist = cur->next;
03943             if (iflist)
03944                iflist->prev = NULL;
03945             else
03946                ifend = NULL;
03947          }
03948          destroy_dahdi_pvt(&cur);
03949       }
03950    } else {
03951       if (prev) {
03952          prev->next = cur->next;
03953          if (prev->next)
03954             prev->next->prev = prev;
03955          else
03956             ifend = prev;
03957       } else {
03958          iflist = cur->next;
03959          if (iflist)
03960             iflist->prev = NULL;
03961          else
03962             ifend = NULL;
03963       }
03964       destroy_dahdi_pvt(&cur);
03965    }
03966    return 0;
03967 }
03968 
03969 static void destroy_all_channels(void)
03970 {
03971    int x;
03972    struct dahdi_pvt *p, *pl;
03973 
03974    while (num_restart_pending) {
03975       usleep(1);
03976    }
03977 
03978    ast_mutex_lock(&iflock);
03979    /* Destroy all the interfaces and free their memory */
03980    p = iflist;
03981    while (p) {
03982       /* Free any callerid */
03983       if (p->cidspill)
03984          ast_free(p->cidspill);
03985       pl = p;
03986       p = p->next;
03987       x = pl->channel;
03988       /* Free associated memory */
03989       if (pl)
03990          destroy_dahdi_pvt(&pl);
03991       if (option_verbose > 2)
03992          ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel %d\n", x);
03993    }
03994    iflist = NULL;
03995    ifcount = 0;
03996    ast_mutex_unlock(&iflock);
03997 }
03998 
03999 #if defined(HAVE_PRI)
04000 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
04001 
04002 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, void *data)
04003 {
04004    /* Data will be our digit string */
04005    struct dahdi_pvt *p;
04006    char *digits = (char *) data;
04007 
04008    if (ast_strlen_zero(digits)) {
04009       ast_debug(1, "No digit string sent to application!\n");
04010       return -1;
04011    }
04012 
04013    p = (struct dahdi_pvt *)chan->tech_pvt;
04014 
04015    if (!p) {
04016       ast_debug(1, "Unable to find technology private\n");
04017       return -1;
04018    }
04019 
04020    ast_mutex_lock(&p->lock);
04021 
04022    if (!p->pri || !p->call) {
04023       ast_debug(1, "Unable to find pri or call on channel!\n");
04024       ast_mutex_unlock(&p->lock);
04025       return -1;
04026    }
04027 
04028    if (!pri_grab(p, p->pri)) {
04029       pri_keypad_facility(p->pri->pri, p->call, digits);
04030       pri_rel(p->pri);
04031    } else {
04032       ast_debug(1, "Unable to grab pri to send keypad facility!\n");
04033       ast_mutex_unlock(&p->lock);
04034       return -1;
04035    }
04036 
04037    ast_mutex_unlock(&p->lock);
04038 
04039    return 0;
04040 }
04041 #endif   /* defined(HAVE_PRI) */
04042 
04043 #if defined(HAVE_PRI)
04044 #if defined(HAVE_PRI_PROG_W_CAUSE)
04045 static char *dahdi_send_callrerouting_facility_app = "DAHDISendCallreroutingFacility";
04046 
04047 static int dahdi_send_callrerouting_facility_exec(struct ast_channel *chan, void *data)
04048 {
04049    /* Data will be our digit string */
04050    struct dahdi_pvt *p;
04051    char *parse;
04052    int res = -1;
04053    AST_DECLARE_APP_ARGS(args,
04054       AST_APP_ARG(destination);
04055       AST_APP_ARG(original);
04056       AST_APP_ARG(reason);
04057    );
04058 
04059    if (ast_strlen_zero(data)) {
04060       ast_log(LOG_DEBUG, "No data sent to application!\n");
04061       return -1;
04062    }
04063 
04064    p = (struct dahdi_pvt *)chan->tech_pvt;
04065 
04066    if (!p) {
04067       ast_log(LOG_DEBUG, "Unable to find technology private\n");
04068       return -1;
04069    }
04070 
04071    parse = ast_strdupa(data);
04072    AST_STANDARD_APP_ARGS(args, parse);
04073 
04074    if (ast_strlen_zero(args.destination)) {
04075       ast_log(LOG_WARNING, "callrerouting facility requires at least destination number argument\n");
04076       return -1;
04077    }
04078 
04079    if (ast_strlen_zero(args.original)) {
04080       ast_log(LOG_WARNING, "Callrerouting Facility without original called number argument\n");
04081       args.original = NULL;
04082    }
04083 
04084    if (ast_strlen_zero(args.reason)) {
04085       ast_log(LOG_NOTICE, "Callrerouting Facility without diversion reason argument, defaulting to unknown\n");
04086       args.reason = NULL;
04087    }
04088 
04089    ast_mutex_lock(&p->lock);
04090 
04091    if (!p->pri || !p->call) {
04092       ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
04093       ast_mutex_unlock(&p->lock);
04094       return -1;
04095    }
04096 
04097    switch (p->sig) {
04098    case SIG_PRI:
04099       if (!pri_grab(p, p->pri)) {
04100          if (chan->_state == AST_STATE_RING) {
04101             res = pri_callrerouting_facility(p->pri->pri, p->call, args.destination, args.original, args.reason);
04102          }
04103          pri_rel(p->pri);
04104       } else {
04105          ast_log(LOG_DEBUG, "Unable to grab pri to send callrerouting facility on span %d!\n", p->span);
04106          ast_mutex_unlock(&p->lock);
04107          return -1;
04108       }
04109       break;
04110    }
04111 
04112    ast_mutex_unlock(&p->lock);
04113 
04114    return res;
04115 }
04116 #endif   /* defined(HAVE_PRI_PROG_W_CAUSE) */
04117 #endif   /* defined(HAVE_PRI) */
04118 
04119 #if defined(HAVE_PRI)
04120 static int pri_is_up(struct dahdi_pri *pri)
04121 {
04122    int x;
04123    for (x = 0; x < NUM_DCHANS; x++) {
04124       if (pri->dchanavail[x] == DCHAN_AVAILABLE)
04125          return 1;
04126    }
04127    return 0;
04128 }
04129 #endif   /* defined(HAVE_PRI) */
04130 
04131 #if defined(HAVE_PRI)
04132 static int pri_assign_bearer(struct dahdi_pvt *crv, struct dahdi_pri *pri, struct dahdi_pvt *bearer)
04133 {
04134    bearer->owner = &inuse;
04135    bearer->realcall = crv;
04136    crv->subs[SUB_REAL].dfd = bearer->subs[SUB_REAL].dfd;
04137    if (crv->subs[SUB_REAL].owner)
04138       ast_channel_set_fd(crv->subs[SUB_REAL].owner, 0, crv->subs[SUB_REAL].dfd);
04139    crv->bearer = bearer;
04140    crv->call = bearer->call;
04141    crv->pri = pri;
04142    return 0;
04143 }
04144 #endif   /* defined(HAVE_PRI) */
04145 
04146 #if defined(HAVE_PRI)
04147 static char *pri_order(int level)
04148 {
04149    switch (level) {
04150    case 0:
04151       return "Primary";
04152    case 1:
04153       return "Secondary";
04154    case 2:
04155       return "Tertiary";
04156    case 3:
04157       return "Quaternary";
04158    default:
04159       return "<Unknown>";
04160    }
04161 }
04162 #endif   /* defined(HAVE_PRI) */
04163 
04164 #if defined(HAVE_PRI)
04165 /* Returns fd of the active dchan */
04166 static int pri_active_dchan_fd(struct dahdi_pri *pri)
04167 {
04168    int x = -1;
04169 
04170    for (x = 0; x < NUM_DCHANS; x++) {
04171       if ((pri->dchans[x] == pri->pri))
04172          break;
04173    }
04174 
04175    return pri->fds[x];
04176 }
04177 #endif   /* defined(HAVE_PRI) */
04178 
04179 #if defined(HAVE_PRI)
04180 static int pri_find_dchan(struct dahdi_pri *pri)
04181 {
04182    int oldslot = -1;
04183    struct pri *old;
04184    int newslot = -1;
04185    int x;
04186    old = pri->pri;
04187    for (x = 0; x < NUM_DCHANS; x++) {
04188       if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
04189          newslot = x;
04190       if (pri->dchans[x] == old) {
04191          oldslot = x;
04192       }
04193    }
04194    if (newslot < 0) {
04195       newslot = 0;
04196       /* This is annoying to see on non persistent layer 2 connections.  Let's not complain in that case */
04197       if (pri->sig != SIG_BRI_PTMP && !pri->no_d_channels) {
04198          pri->no_d_channels = 1;
04199          ast_log(LOG_WARNING,
04200             "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
04201             pri->dchannels[newslot]);
04202       }
04203    } else {
04204       pri->no_d_channels = 0;
04205    }
04206    if (old && (oldslot != newslot))
04207       ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
04208          pri->dchannels[oldslot], pri->dchannels[newslot]);
04209    pri->pri = pri->dchans[newslot];
04210    return 0;
04211 }
04212 #endif   /* defined(HAVE_PRI) */
04213 
04214 #if defined(HAVE_OPENR2)
04215 static const char *dahdi_accept_r2_call_app = "DAHDIAcceptR2Call";
04216 
04217 static int dahdi_accept_r2_call_exec(struct ast_channel *chan, void *data)
04218 {
04219    /* data is whether to accept with charge or no charge */
04220    openr2_call_mode_t accept_mode;
04221    int res, timeout, maxloops;
04222    struct ast_frame *f;
04223    struct dahdi_pvt *p;
04224    char *parse;
04225    AST_DECLARE_APP_ARGS(args,
04226          AST_APP_ARG(charge);
04227    );
04228 
04229    if (ast_strlen_zero(data)) {
04230       ast_log(LOG_DEBUG, "No data sent to application!\n");
04231       return -1;
04232    }
04233 
04234    if (chan->tech != &dahdi_tech) {
04235       ast_log(LOG_DEBUG, "Only DAHDI technology accepted!\n");
04236       return -1;
04237    }
04238 
04239    p = (struct dahdi_pvt *)chan->tech_pvt;
04240    if (!p) {
04241       ast_log(LOG_DEBUG, "Unable to find technology private!\n");
04242       return -1;
04243    }
04244 
04245    parse = ast_strdupa(data);
04246    AST_STANDARD_APP_ARGS(args, parse);
04247 
04248    if (ast_strlen_zero(args.charge)) {
04249       ast_log(LOG_WARNING, "DAHDIAcceptR2Call requires 'yes' or 'no' for the charge parameter\n");
04250       return -1;
04251    }
04252 
04253    ast_mutex_lock(&p->lock);
04254    if (!p->mfcr2 || !p->mfcr2call) {
04255       ast_mutex_unlock(&p->lock);
04256       ast_log(LOG_DEBUG, "Channel %s does not seems to be an R2 active channel!\n", chan->name);
04257       return -1;
04258    }
04259 
04260    if (p->mfcr2_call_accepted) {
04261       ast_mutex_unlock(&p->lock);
04262       ast_log(LOG_DEBUG, "MFC/R2 call already accepted on channel %s!\n", chan->name);
04263       return 0;
04264    }
04265    accept_mode = ast_true(args.charge) ? OR2_CALL_WITH_CHARGE : OR2_CALL_NO_CHARGE;
04266    if (openr2_chan_accept_call(p->r2chan, accept_mode)) {
04267       ast_mutex_unlock(&p->lock);
04268       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
04269       return -1;
04270    }
04271    ast_mutex_unlock(&p->lock);
04272 
04273    res = 0;
04274    timeout = 100;
04275    maxloops = 50; /* wait up to 5 seconds */
04276    /* we need to read() until the call is accepted */
04277    while (maxloops > 0) {
04278       maxloops--;
04279       if (ast_check_hangup(chan)) {
04280          break;
04281       }
04282       res = ast_waitfor(chan, timeout);
04283       if (res < 0) {
04284          ast_log(LOG_DEBUG, "ast_waitfor failed on channel %s, going out ...\n", chan->name);
04285          res = -1;
04286          break;
04287       }
04288       if (res == 0) {
04289          continue;
04290       }
04291       f = ast_read(chan);
04292       if (!f) {
04293          ast_log(LOG_DEBUG, "No frame read on channel %s, going out ...\n", chan->name);
04294          res = -1;
04295          break;
04296       }
04297       if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP) {
04298          ast_log(LOG_DEBUG, "Got HANGUP frame on channel %s, going out ...\n", chan->name);
04299          ast_frfree(f);
04300          res = -1;
04301          break;
04302       }
04303       ast_frfree(f);
04304       ast_mutex_lock(&p->lock);
04305       if (p->mfcr2_call_accepted) {
04306          ast_mutex_unlock(&p->lock);
04307          ast_log(LOG_DEBUG, "Accepted MFC/R2 call!\n");
04308          break;
04309       }
04310       ast_mutex_unlock(&p->lock);
04311    }
04312    if (res == -1) {
04313       ast_log(LOG_WARNING, "Failed to accept MFC/R2 call!\n");
04314    }
04315    return res;
04316 }
04317 
04318 static openr2_call_disconnect_cause_t dahdi_ast_cause_to_r2_cause(int cause)
04319 {
04320    openr2_call_disconnect_cause_t r2cause = OR2_CAUSE_NORMAL_CLEARING;
04321    switch (cause) {
04322    case AST_CAUSE_USER_BUSY:
04323    case AST_CAUSE_CALL_REJECTED:
04324    case AST_CAUSE_INTERWORKING: /* I don't know wtf is this but is used sometimes when ekiga rejects a call */
04325       r2cause = OR2_CAUSE_BUSY_NUMBER;
04326       break;
04327 
04328    case AST_CAUSE_NORMAL_CIRCUIT_CONGESTION:
04329    case AST_CAUSE_SWITCH_CONGESTION:
04330       r2cause = OR2_CAUSE_NETWORK_CONGESTION;
04331       break;
04332 
04333    case AST_CAUSE_UNALLOCATED:
04334       r2cause = OR2_CAUSE_UNALLOCATED_NUMBER;
04335       break;
04336 
04337    case AST_CAUSE_NETWORK_OUT_OF_ORDER:
04338    case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
04339       r2cause = OR2_CAUSE_OUT_OF_ORDER;
04340       break;
04341 
04342    case AST_CAUSE_NO_ANSWER:
04343    case AST_CAUSE_NO_USER_RESPONSE:
04344       r2cause = OR2_CAUSE_NO_ANSWER;
04345       break;
04346 
04347    default:
04348       r2cause = OR2_CAUSE_NORMAL_CLEARING;
04349       break;
04350    }
04351    ast_log(LOG_DEBUG, "ast cause %d resulted in openr2 cause %d/%s\n",
04352          cause, r2cause, openr2_proto_get_disconnect_string(r2cause));
04353    return r2cause;
04354 }
04355 #endif
04356 
04357 static int dahdi_hangup(struct ast_channel *ast)
04358 {
04359    int res;
04360    int idx,x, law;
04361    /*static int restore_gains(struct dahdi_pvt *p);*/
04362    struct dahdi_pvt *p = ast->tech_pvt;
04363    struct dahdi_pvt *tmp = NULL;
04364    struct dahdi_pvt *prev = NULL;
04365    struct dahdi_params par;
04366 
04367    ast_debug(1, "dahdi_hangup(%s)\n", ast->name);
04368    if (!ast->tech_pvt) {
04369       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
04370       return 0;
04371    }
04372 
04373    ast_mutex_lock(&p->lock);
04374 
04375    idx = dahdi_get_index(ast, p, 1);
04376 
04377    switch (p->sig) {
04378    case SIG_PRI:
04379    case SIG_BRI:
04380    case SIG_BRI_PTMP:
04381    case SIG_SS7:
04382       x = 1;
04383       ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
04384       /* Fall through */
04385    case SIG_MFCR2:
04386       p->cid_num[0] = '\0';
04387       p->cid_name[0] = '\0';
04388       break;
04389    default:
04390       break;
04391    }
04392 
04393    x = 0;
04394    dahdi_confmute(p, 0);
04395    p->muting = 0;
04396    restore_gains(p);
04397    if (p->origcid_num) {
04398       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
04399       ast_free(p->origcid_num);
04400       p->origcid_num = NULL;
04401    }
04402    if (p->origcid_name) {
04403       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
04404       ast_free(p->origcid_name);
04405       p->origcid_name = NULL;
04406    }
04407    if (p->dsp)
04408       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
04409    p->exten[0] = '\0';
04410 
04411    ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
04412       p->channel, idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
04413    p->ignoredtmf = 0;
04414 
04415    if (idx > -1) {
04416       /* Real channel, do some fixup */
04417       p->subs[idx].owner = NULL;
04418       p->subs[idx].needanswer = 0;
04419       p->subs[idx].needflash = 0;
04420       p->subs[idx].needringing = 0;
04421       p->subs[idx].needbusy = 0;
04422       p->subs[idx].needcongestion = 0;
04423       p->subs[idx].linear = 0;
04424       p->subs[idx].needcallerid = 0;
04425       p->polarity = POLARITY_IDLE;
04426       dahdi_setlinear(p->subs[idx].dfd, 0);
04427       switch (idx) {
04428       case SUB_REAL:
04429          if ((p->subs[SUB_CALLWAIT].dfd > -1) && (p->subs[SUB_THREEWAY].dfd > -1)) {
04430             ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
04431             if (p->subs[SUB_CALLWAIT].inthreeway) {
04432                /* We had flipped over to answer a callwait and now it's gone */
04433                ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
04434                /* Move to the call-wait, but un-own us until they flip back. */
04435                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
04436                unalloc_sub(p, SUB_CALLWAIT);
04437                p->owner = NULL;
04438             } else {
04439                /* The three way hung up, but we still have a call wait */
04440                ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
04441                swap_subs(p, SUB_THREEWAY, SUB_REAL);
04442                unalloc_sub(p, SUB_THREEWAY);
04443                if (p->subs[SUB_REAL].inthreeway) {
04444                   /* This was part of a three way call.  Immediately make way for
04445                      another call */
04446                   ast_debug(1, "Call was complete, setting owner to former third call\n");
04447                   p->subs[SUB_REAL].inthreeway = 0;
04448                   p->owner = p->subs[SUB_REAL].owner;
04449                } else {
04450                   /* This call hasn't been completed yet...  Set owner to NULL */
04451                   ast_debug(1, "Call was incomplete, setting owner to NULL\n");
04452                   p->owner = NULL;
04453                }
04454             }
04455          } else if (p->subs[SUB_CALLWAIT].dfd > -1) {
04456             /* Need to hold the lock for real-call, private, and call-waiting call */
04457             dahdi_lock_sub_owner(p, SUB_CALLWAIT);
04458             if (!p->subs[SUB_CALLWAIT].owner) {
04459                /* The call waiting call dissappeared. */
04460                p->owner = NULL;
04461                break;
04462             }
04463 
04464             /* Move to the call-wait and switch back to them. */
04465             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
04466             unalloc_sub(p, SUB_CALLWAIT);
04467             p->owner = p->subs[SUB_REAL].owner;
04468             if (p->owner->_state != AST_STATE_UP)
04469                p->subs[SUB_REAL].needanswer = 1;
04470             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
04471                ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
04472             /* Unlock the call-waiting call that we swapped to real-call. */
04473             ast_channel_unlock(p->subs[SUB_REAL].owner);
04474          } else if (p->subs[SUB_THREEWAY].dfd > -1) {
04475             swap_subs(p, SUB_THREEWAY, SUB_REAL);
04476             unalloc_sub(p, SUB_THREEWAY);
04477             if (p->subs[SUB_REAL].inthreeway) {
04478                /* This was part of a three way call.  Immediately make way for
04479                   another call */
04480                ast_debug(1, "Call was complete, setting owner to former third call\n");
04481                p->subs[SUB_REAL].inthreeway = 0;
04482                p->owner = p->subs[SUB_REAL].owner;
04483             } else {
04484                /* This call hasn't been completed yet...  Set owner to NULL */
04485                ast_debug(1, "Call was incomplete, setting owner to NULL\n");
04486                p->owner = NULL;
04487             }
04488          }
04489          break;
04490       case SUB_CALLWAIT:
04491          /* Ditch the holding callwait call, and immediately make it availabe */
04492          if (p->subs[SUB_CALLWAIT].inthreeway) {
04493             /* Need to hold the lock for call-waiting call, private, and 3-way call */
04494             dahdi_lock_sub_owner(p, SUB_THREEWAY);
04495 
04496             /* This is actually part of a three way, placed on hold.  Place the third part
04497                on music on hold now */
04498             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
04499                ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
04500                   S_OR(p->mohsuggest, NULL),
04501                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
04502             }
04503             p->subs[SUB_THREEWAY].inthreeway = 0;
04504             /* Make it the call wait now */
04505             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
04506             unalloc_sub(p, SUB_THREEWAY);
04507             if (p->subs[SUB_CALLWAIT].owner) {
04508                /* Unlock the 3-way call that we swapped to call-waiting call. */
04509                ast_channel_unlock(p->subs[SUB_CALLWAIT].owner);
04510             }
04511          } else
04512             unalloc_sub(p, SUB_CALLWAIT);
04513          break;
04514       case SUB_THREEWAY:
04515          /* Need to hold the lock for 3-way call, private, and call-waiting call */
04516          dahdi_lock_sub_owner(p, SUB_CALLWAIT);
04517          if (p->subs[SUB_CALLWAIT].inthreeway) {
04518             /* The other party of the three way call is currently in a call-wait state.
04519                Start music on hold for them, and take the main guy out of the third call */
04520             p->subs[SUB_CALLWAIT].inthreeway = 0;
04521             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
04522                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
04523                   S_OR(p->mohsuggest, NULL),
04524                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
04525             }
04526          }
04527          if (p->subs[SUB_CALLWAIT].owner) {
04528             ast_channel_unlock(p->subs[SUB_CALLWAIT].owner);
04529          }
04530          p->subs[SUB_REAL].inthreeway = 0;
04531          /* If this was part of a three way call index, let us make
04532             another three way call */
04533          unalloc_sub(p, SUB_THREEWAY);
04534          break;
04535       default:
04536          /*
04537           * Should never happen.
04538           * This wasn't any sort of call, so how are we an index?
04539           */
04540          ast_log(LOG_ERROR, "Index found but not any type of call?\n");
04541          break;
04542       }
04543    }
04544 
04545    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
04546       p->owner = NULL;
04547       p->ringt = 0;
04548       p->distinctivering = 0;
04549       p->confirmanswer = 0;
04550       p->cidrings = 1;
04551       p->outgoing = 0;
04552       p->digital = 0;
04553       p->faxhandled = 0;
04554       p->pulsedial = 0;
04555       p->onhooktime = time(NULL);
04556 #if defined(HAVE_PRI) || defined(HAVE_SS7)
04557       p->proceeding = 0;
04558       p->dialing = 0;
04559       p->progress = 0;
04560       p->alerting = 0;
04561       p->setup_ack = 0;
04562       p->rlt = 0;
04563 #endif
04564       if (p->dsp) {
04565          ast_dsp_free(p->dsp);
04566          p->dsp = NULL;
04567       }
04568 
04569       if (p->bufferoverrideinuse) {
04570          /* faxbuffers are in use, revert them */
04571          struct dahdi_bufferinfo bi = {
04572             .txbufpolicy = p->buf_policy,
04573             .rxbufpolicy = p->buf_policy,
04574             .bufsize = p->bufsize,
04575             .numbufs = p->buf_no
04576          };
04577          int bpres;
04578 
04579          if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
04580             ast_log(LOG_WARNING, "Channel '%s' unable to revert faxbuffer policy: %s\n", ast->name, strerror(errno));
04581          }
04582          p->bufferoverrideinuse = 0;
04583       }
04584 
04585       law = DAHDI_LAW_DEFAULT;
04586       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
04587       if (res < 0)
04588          ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
04589       /* Perform low level hangup if no owner left */
04590 #ifdef HAVE_SS7
04591       if (p->ss7) {
04592          if (p->ss7call) {
04593             if (!ss7_grab(p, p->ss7)) {
04594                if (!p->alreadyhungup) {
04595                   const char *cause = pbx_builtin_getvar_helper(ast,"SS7_CAUSE");
04596                   int icause = ast->hangupcause ? ast->hangupcause : -1;
04597 
04598                   if (cause) {
04599                      if (atoi(cause))
04600                         icause = atoi(cause);
04601                   }
04602                   isup_rel(p->ss7->ss7, p->ss7call, icause);
04603                   ss7_rel(p->ss7);
04604                   p->alreadyhungup = 1;
04605                } else
04606                   ast_log(LOG_WARNING, "Trying to hangup twice!\n");
04607             } else {
04608                ast_log(LOG_WARNING, "Unable to grab SS7 on CIC %d\n", p->cic);
04609                res = -1;
04610             }
04611          }
04612       }
04613 #endif
04614 #ifdef HAVE_OPENR2
04615       if (p->mfcr2 && p->mfcr2call && openr2_chan_get_direction(p->r2chan) != OR2_DIR_STOPPED) {
04616          ast_log(LOG_DEBUG, "disconnecting MFC/R2 call on chan %d\n", p->channel);
04617          /* If it's an incoming call, check the mfcr2_forced_release setting */
04618          if (openr2_chan_get_direction(p->r2chan) == OR2_DIR_BACKWARD && p->mfcr2_forced_release) {
04619             dahdi_r2_disconnect_call(p, OR2_CAUSE_FORCED_RELEASE);
04620          } else {
04621             const char *r2causestr = pbx_builtin_getvar_helper(ast, "MFCR2_CAUSE");
04622             int r2cause_user = r2causestr ? atoi(r2causestr) : 0;
04623             openr2_call_disconnect_cause_t r2cause = r2cause_user ? dahdi_ast_cause_to_r2_cause(r2cause_user)
04624                                                              : dahdi_ast_cause_to_r2_cause(ast->hangupcause);
04625             dahdi_r2_disconnect_call(p, r2cause);
04626          }
04627       } else if (p->mfcr2call) {
04628          ast_log(LOG_DEBUG, "Clearing call request on channel %d\n", p->channel);
04629          /* since ast_request() was called but not ast_call() we have not yet dialed
04630          and the openr2 stack will not call on_call_end callback, we need to unset
04631          the mfcr2call flag and bump the monitor count so the monitor thread can take
04632          care of this channel events from now on */
04633          p->mfcr2call = 0;
04634       }
04635 #endif
04636 #ifdef HAVE_PRI
04637       if (p->pri) {
04638 #ifdef SUPPORT_USERUSER
04639          const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
04640 #endif
04641 
04642          /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
04643          if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
04644             if (!pri_grab(p, p->pri)) {
04645                if (p->alreadyhungup) {
04646                   ast_debug(1, "Already hungup...  Calling hangup once, and clearing call\n");
04647 
04648 #ifdef SUPPORT_USERUSER
04649                   pri_call_set_useruser(p->call, useruser);
04650 #endif
04651 
04652                   pri_hangup(p->pri->pri, p->call, -1);
04653                   p->call = NULL;
04654                   if (p->bearer)
04655                      p->bearer->call = NULL;
04656                } else {
04657                   const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
04658                   int icause = ast->hangupcause ? ast->hangupcause : -1;
04659                   ast_debug(1, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
04660 
04661 #ifdef SUPPORT_USERUSER
04662                   pri_call_set_useruser(p->call, useruser);
04663 #endif
04664 
04665                   p->alreadyhungup = 1;
04666                   if (p->bearer)
04667                      p->bearer->alreadyhungup = 1;
04668                   if (cause) {
04669                      if (atoi(cause))
04670                         icause = atoi(cause);
04671                   }
04672                   pri_hangup(p->pri->pri, p->call, icause);
04673                }
04674                if (res < 0)
04675                   ast_log(LOG_WARNING, "pri_disconnect failed\n");
04676                pri_rel(p->pri);
04677             } else {
04678                ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
04679                res = -1;
04680             }
04681          } else {
04682             if (p->bearer)
04683                ast_debug(1, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
04684             p->call = NULL;
04685             res = 0;
04686          }
04687       }
04688 #endif
04689       if (p->sig && ((p->sig != SIG_PRI) && (p->sig != SIG_SS7)
04690          && (p->sig != SIG_BRI)
04691          && (p->sig != SIG_BRI_PTMP))
04692          && (p->sig != SIG_MFCR2))
04693          res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
04694       if (res < 0) {
04695          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
04696       }
04697       switch (p->sig) {
04698       case SIG_FXOGS:
04699       case SIG_FXOLS:
04700       case SIG_FXOKS:
04701          memset(&par, 0, sizeof(par));
04702          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
04703          if (!res) {
04704 #if 0
04705             ast_debug(1, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
04706 #endif
04707             /* If they're off hook, try playing congestion */
04708             if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
04709                tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
04710             else
04711                tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
04712             p->fxsoffhookstate = par.rxisoffhook;
04713          }
04714          break;
04715       case SIG_FXSGS:
04716       case SIG_FXSLS:
04717       case SIG_FXSKS:
04718          /* Make sure we're not made available for at least two seconds assuming
04719             we were actually used for an inbound or outbound call. */
04720          if (ast->_state != AST_STATE_RESERVED) {
04721             time(&p->guardtime);
04722             p->guardtime += 2;
04723          }
04724          break;
04725       default:
04726          tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
04727       }
04728       if (p->cidspill)
04729          ast_free(p->cidspill);
04730       if (p->sig)
04731          dahdi_disable_ec(p);
04732       x = 0;
04733       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
04734       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
04735       p->didtdd = 0;
04736       p->cidspill = NULL;
04737       p->callwaitcas = 0;
04738       p->callwaiting = p->permcallwaiting;
04739       p->hidecallerid = p->permhidecallerid;
04740       p->waitingfordt.tv_sec = 0;
04741       p->dialing = 0;
04742       p->rdnis[0] = '\0';
04743       update_conf(p);
04744       reset_conf(p);
04745       /* Restore data mode */
04746       if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
04747          x = 0;
04748          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
04749       }
04750 #ifdef HAVE_PRI
04751       if (p->bearer) {
04752          ast_debug(1, "Freeing up bearer channel %d\n", p->bearer->channel);
04753          /* Free up the bearer channel as well, and
04754             don't use its file descriptor anymore */
04755          update_conf(p->bearer);
04756          reset_conf(p->bearer);
04757          p->bearer->owner = NULL;
04758          p->bearer->realcall = NULL;
04759          p->bearer = NULL;
04760          p->subs[SUB_REAL].dfd = -1;
04761          p->pri = NULL;
04762       }
04763 #endif
04764       if (num_restart_pending == 0)
04765          restart_monitor();
04766    }
04767 
04768    p->callwaitingrepeat = 0;
04769    p->cidcwexpire = 0;
04770    p->oprmode = 0;
04771    ast->tech_pvt = NULL;
04772    ast_mutex_unlock(&p->lock);
04773    ast_module_unref(ast_module_info->self);
04774    ast_verb(3, "Hungup '%s'\n", ast->name);
04775 
04776    ast_mutex_lock(&iflock);
04777 
04778    if (p->restartpending) {
04779       num_restart_pending--;
04780    }
04781 
04782    tmp = iflist;
04783    prev = NULL;
04784    if (p->destroy) {
04785       while (tmp) {
04786          if (tmp == p) {
04787             destroy_channel(prev, tmp, 0);
04788             break;
04789          } else {
04790             prev = tmp;
04791             tmp = tmp->next;
04792          }
04793       }
04794    }
04795    ast_mutex_unlock(&iflock);
04796    return 0;
04797 }
04798 
04799 static int dahdi_answer(struct ast_channel *ast)
04800 {
04801    struct dahdi_pvt *p = ast->tech_pvt;
04802    int res = 0;
04803    int idx;
04804    int oldstate = ast->_state;
04805    ast_setstate(ast, AST_STATE_UP);
04806    ast_mutex_lock(&p->lock);
04807    idx = dahdi_get_index(ast, p, 0);
04808    if (idx < 0)
04809       idx = SUB_REAL;
04810    /* nothing to do if a radio channel */
04811    if ((p->radio || (p->oprmode < 0))) {
04812       ast_mutex_unlock(&p->lock);
04813       return 0;
04814    }
04815    switch (p->sig) {
04816    case SIG_FXSLS:
04817    case SIG_FXSGS:
04818    case SIG_FXSKS:
04819       p->ringt = 0;
04820       /* Fall through */
04821    case SIG_EM:
04822    case SIG_EM_E1:
04823    case SIG_EMWINK:
04824    case SIG_FEATD:
04825    case SIG_FEATDMF:
04826    case SIG_FEATDMF_TA:
04827    case SIG_E911:
04828    case SIG_FGC_CAMA:
04829    case SIG_FGC_CAMAMF:
04830    case SIG_FEATB:
04831    case SIG_SF:
04832    case SIG_SFWINK:
04833    case SIG_SF_FEATD:
04834    case SIG_SF_FEATDMF:
04835    case SIG_SF_FEATB:
04836    case SIG_FXOLS:
04837    case SIG_FXOGS:
04838    case SIG_FXOKS:
04839       /* Pick up the line */
04840       ast_debug(1, "Took %s off hook\n", ast->name);
04841       if (p->hanguponpolarityswitch) {
04842          p->polaritydelaytv = ast_tvnow();
04843       }
04844       res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
04845       tone_zone_play_tone(p->subs[idx].dfd, -1);
04846       p->dialing = 0;
04847       if ((idx == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
04848          if (oldstate == AST_STATE_RINGING) {
04849             ast_debug(1, "Finally swapping real and threeway\n");
04850             tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, -1);
04851             swap_subs(p, SUB_THREEWAY, SUB_REAL);
04852             p->owner = p->subs[SUB_REAL].owner;
04853          }
04854       }
04855       if (p->sig & __DAHDI_SIG_FXS) {
04856          dahdi_enable_ec(p);
04857          dahdi_train_ec(p);
04858       }
04859       break;
04860 #ifdef HAVE_PRI
04861    case SIG_BRI:
04862    case SIG_BRI_PTMP:
04863    case SIG_PRI:
04864       /* Send a pri acknowledge */
04865       if (!pri_grab(p, p->pri)) {
04866          p->proceeding = 1;
04867          p->dialing = 0;
04868          res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
04869          pri_rel(p->pri);
04870       } else {
04871          ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
04872          res = -1;
04873       }
04874       break;
04875 #endif
04876 #ifdef HAVE_SS7
04877    case SIG_SS7:
04878       if (!ss7_grab(p, p->ss7)) {
04879          p->proceeding = 1;
04880          res = isup_anm(p->ss7->ss7, p->ss7call);
04881          ss7_rel(p->ss7);
04882       } else {
04883          ast_log(LOG_WARNING, "Unable to grab SS7 on span %d\n", p->span);
04884          res = -1;
04885       }
04886       break;
04887 #endif
04888 #ifdef HAVE_OPENR2
04889    case SIG_MFCR2:
04890       if (!p->mfcr2_call_accepted) {
04891          /* The call was not accepted on offer nor the user, so it must be accepted now before answering,
04892             openr2_chan_answer_call will be called when the callback on_call_accepted is executed */
04893          p->mfcr2_answer_pending = 1;
04894          if (p->mfcr2_charge_calls) {
04895             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge before answering on chan %d\n", p->channel);
04896             openr2_chan_accept_call(p->r2chan, OR2_CALL_WITH_CHARGE);
04897          } else {
04898             ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge before answering on chan %d\n", p->channel);
04899             openr2_chan_accept_call(p->r2chan, OR2_CALL_NO_CHARGE);
04900          }
04901       } else {
04902          ast_log(LOG_DEBUG, "Answering MFC/R2 call on chan %d\n", p->channel);
04903          dahdi_r2_answer(p);
04904       }
04905       break;
04906 #endif
04907    case 0:
04908       ast_mutex_unlock(&p->lock);
04909       return 0;
04910    default:
04911       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
04912       res = -1;
04913    }
04914    ast_mutex_unlock(&p->lock);
04915    return res;
04916 }
04917 
04918 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04919 {
04920    char *cp;
04921    signed char *scp;
04922    int x;
04923    int idx;
04924    struct dahdi_pvt *p = chan->tech_pvt, *pp;
04925    struct oprmode *oprmode;
04926 
04927 
04928    /* all supported options require data */
04929    if (!data || (datalen < 1)) {
04930       errno = EINVAL;
04931       return -1;
04932    }
04933 
04934    switch (option) {
04935    case AST_OPTION_TXGAIN:
04936       scp = (signed char *) data;
04937       idx = dahdi_get_index(chan, p, 0);
04938       if (idx < 0) {
04939          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
04940          return -1;
04941       }
04942       ast_debug(1, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
04943       return set_actual_txgain(p->subs[idx].dfd, 0, p->txgain + (float) *scp, p->law);
04944    case AST_OPTION_RXGAIN:
04945       scp = (signed char *) data;
04946       idx = dahdi_get_index(chan, p, 0);
04947       if (idx < 0) {
04948          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
04949          return -1;
04950       }
04951       ast_debug(1, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
04952       return set_actual_rxgain(p->subs[idx].dfd, 0, p->rxgain + (float) *scp, p->law);
04953    case AST_OPTION_TONE_VERIFY:
04954       if (!p->dsp)
04955          break;
04956       cp = (char *) data;
04957       switch (*cp) {
04958       case 1:
04959          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
04960          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
04961          break;
04962       case 2:
04963          ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
04964          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
04965          break;
04966       default:
04967          ast_debug(1, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
04968          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
04969          break;
04970       }
04971       break;
04972    case AST_OPTION_TDD:
04973       /* turn on or off TDD */
04974       cp = (char *) data;
04975       p->mate = 0;
04976       if (!*cp) { /* turn it off */
04977          ast_debug(1, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
04978          if (p->tdd)
04979             tdd_free(p->tdd);
04980          p->tdd = 0;
04981          break;
04982       }
04983       ast_debug(1, "Set option TDD MODE, value: %s(%d) on %s\n",
04984          (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
04985       dahdi_disable_ec(p);
04986       /* otherwise, turn it on */
04987       if (!p->didtdd) { /* if havent done it yet */
04988          unsigned char mybuf[41000];/*! \todo XXX This is an abuse of the stack!! */
04989          unsigned char *buf;
04990          int size, res, fd, len;
04991          struct pollfd fds[1];
04992 
04993          buf = mybuf;
04994          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
04995          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
04996          len = 40000;
04997          idx = dahdi_get_index(chan, p, 0);
04998          if (idx < 0) {
04999             ast_log(LOG_WARNING, "No index in TDD?\n");
05000             return -1;
05001          }
05002          fd = p->subs[idx].dfd;
05003          while (len) {
05004             if (ast_check_hangup(chan))
05005                return -1;
05006             size = len;
05007             if (size > READ_SIZE)
05008                size = READ_SIZE;
05009             fds[0].fd = fd;
05010             fds[0].events = POLLPRI | POLLOUT;
05011             fds[0].revents = 0;
05012             res = poll(fds, 1, -1);
05013             if (!res) {
05014                ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
05015                continue;
05016             }
05017             /* if got exception */
05018             if (fds[0].revents & POLLPRI)
05019                return -1;
05020             if (!(fds[0].revents & POLLOUT)) {
05021                ast_debug(1, "write fd not ready on channel %d\n", p->channel);
05022                continue;
05023             }
05024             res = write(fd, buf, size);
05025             if (res != size) {
05026                if (res == -1) return -1;
05027                ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
05028                break;
05029             }
05030             len -= size;
05031             buf += size;
05032          }
05033          p->didtdd = 1; /* set to have done it now */
05034       }
05035       if (*cp == 2) { /* Mate mode */
05036          if (p->tdd)
05037             tdd_free(p->tdd);
05038          p->tdd = 0;
05039          p->mate = 1;
05040          break;
05041       }
05042       if (!p->tdd) { /* if we dont have one yet */
05043          p->tdd = tdd_new(); /* allocate one */
05044       }
05045       break;
05046    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
05047       if (!p->dsp)
05048          break;
05049       cp = (char *) data;
05050       ast_debug(1, "Set option RELAX DTMF, value: %s(%d) on %s\n",
05051          *cp ? "ON" : "OFF", (int) *cp, chan->name);
05052       ast_dsp_set_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
05053       break;
05054    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
05055       cp = (char *) data;
05056       if (!*cp) {
05057          ast_debug(1, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
05058          x = 0;
05059          dahdi_disable_ec(p);
05060       } else {
05061          ast_debug(1, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
05062          x = 1;
05063       }
05064       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x) == -1)
05065          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", p->channel, x, strerror(errno));
05066       break;
05067    case AST_OPTION_OPRMODE:  /* Operator services mode */
05068       oprmode = (struct oprmode *) data;
05069       /* We don't support operator mode across technologies */
05070       if (strcasecmp(chan->tech->type, oprmode->peer->tech->type)) {
05071          ast_log(LOG_NOTICE, "Operator mode not supported on %s to %s calls.\n",
05072                chan->tech->type, oprmode->peer->tech->type);
05073          errno = EINVAL;
05074          return -1;
05075       }
05076       pp = oprmode->peer->tech_pvt;
05077       p->oprmode = pp->oprmode = 0;
05078       /* setup peers */
05079       p->oprpeer = pp;
05080       pp->oprpeer = p;
05081       /* setup modes, if any */
05082       if (oprmode->mode)
05083       {
05084          pp->oprmode = oprmode->mode;
05085          p->oprmode = -oprmode->mode;
05086       }
05087       ast_debug(1, "Set Operator Services mode, value: %d on %s/%s\n",
05088          oprmode->mode, chan->name,oprmode->peer->name);
05089       break;
05090    case AST_OPTION_ECHOCAN:
05091       cp = (char *) data;
05092       if (*cp) {
05093          ast_debug(1, "Enabling echo cancellation on %s\n", chan->name);
05094          dahdi_enable_ec(p);
05095       } else {
05096          ast_debug(1, "Disabling echo cancellation on %s\n", chan->name);
05097          dahdi_disable_ec(p);
05098       }
05099       break;
05100    }
05101    errno = 0;
05102 
05103    return 0;
05104 }
05105 
05106 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
05107 {
05108    struct dahdi_pvt *p = chan->tech_pvt;
05109    int res = 0;
05110 
05111    if (!strcasecmp(data, "rxgain")) {
05112       ast_mutex_lock(&p->lock);
05113       snprintf(buf, len, "%f", p->rxgain);
05114       ast_mutex_unlock(&p->lock);
05115    } else if (!strcasecmp(data, "txgain")) {
05116       ast_mutex_lock(&p->lock);
05117       snprintf(buf, len, "%f", p->txgain);
05118       ast_mutex_unlock(&p->lock);
05119    } else {
05120       ast_copy_string(buf, "", len);
05121       res = -1;
05122    }
05123 
05124    return res;
05125 }
05126 
05127 
05128 static int parse_buffers_policy(const char *parse, int *num_buffers, int *policy)
05129 {
05130    int res;
05131    char policy_str[21] = "";
05132    
05133    if (((res = sscanf(parse, "%d,%20s", num_buffers, policy_str)) != 2) &&
05134       ((res = sscanf(parse, "%d|%20s", num_buffers, policy_str)) != 2)) {
05135       ast_log(LOG_WARNING, "Parsing buffer string '%s' failed.\n", parse);
05136       return 1;
05137    }
05138    if (*num_buffers < 0) {
05139       ast_log(LOG_WARNING, "Invalid buffer count given '%d'.\n", *num_buffers);
05140       return -1;
05141    }
05142    if (!strcasecmp(policy_str, "full")) {
05143       *policy = DAHDI_POLICY_WHEN_FULL;
05144    } else if (!strcasecmp(policy_str, "immediate")) {
05145       *policy = DAHDI_POLICY_IMMEDIATE;
05146 #ifdef DAHDI_POLICY_HALF_FULL
05147    } else if (!strcasecmp(policy_str, "half")) {
05148       *policy = DAHDI_POLICY_HALF_FULL;
05149 #endif
05150    } else {
05151       ast_log(LOG_WARNING, "Invalid policy name given '%s'.\n", policy_str);
05152       return -1;
05153    }
05154 
05155    return 0;
05156 }
05157 
05158 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value)
05159 {
05160    struct dahdi_pvt *p = chan->tech_pvt;
05161    int res = 0;
05162 
05163    if (!strcasecmp(data, "buffers")) {
05164       int num_bufs, policy;
05165 
05166       if (!(parse_buffers_policy(value, &num_bufs, &policy))) {
05167          struct dahdi_bufferinfo bi = {
05168             .txbufpolicy = policy,
05169             .rxbufpolicy = policy,
05170             .bufsize = p->bufsize,
05171             .numbufs = num_bufs,
05172          };
05173          int bpres;
05174 
05175          if ((bpres = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
05176             ast_log(LOG_WARNING, "Channel '%d' unable to override buffer policy: %s\n", p->channel, strerror(errno));
05177          } else {
05178             p->bufferoverrideinuse = 1;
05179          }
05180       } else {
05181          res = -1;
05182       }
05183    } else {
05184       res = -1;
05185    }
05186 
05187    return res;
05188 }
05189 
05190 static void dahdi_unlink(struct dahdi_pvt *slave, struct dahdi_pvt *master, int needlock)
05191 {
05192    /* Unlink a specific slave or all slaves/masters from a given master */
05193    int x;
05194    int hasslaves;
05195    if (!master)
05196       return;
05197    if (needlock) {
05198       ast_mutex_lock(&master->lock);
05199       if (slave) {
05200          while (ast_mutex_trylock(&slave->lock)) {
05201             DEADLOCK_AVOIDANCE(&master->lock);
05202          }
05203       }
05204    }
05205    hasslaves = 0;
05206    for (x = 0; x < MAX_SLAVES; x++) {
05207       if (master->slaves[x]) {
05208          if (!slave || (master->slaves[x] == slave)) {
05209             /* Take slave out of the conference */
05210             ast_debug(1, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
05211             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
05212             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
05213             master->slaves[x]->master = NULL;
05214             master->slaves[x] = NULL;
05215          } else
05216             hasslaves = 1;
05217       }
05218       if (!hasslaves)
05219          master->inconference = 0;
05220    }
05221    if (!slave) {
05222       if (master->master) {
05223          /* Take master out of the conference */
05224          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
05225          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
05226          hasslaves = 0;
05227          for (x = 0; x < MAX_SLAVES; x++) {
05228             if (master->master->slaves[x] == master)
05229                master->master->slaves[x] = NULL;
05230             else if (master->master->slaves[x])
05231                hasslaves = 1;
05232          }
05233          if (!hasslaves)
05234             master->master->inconference = 0;
05235       }
05236       master->master = NULL;
05237    }
05238    update_conf(master);
05239    if (needlock) {
05240       if (slave)
05241          ast_mutex_unlock(&slave->lock);
05242       ast_mutex_unlock(&master->lock);
05243    }
05244 }
05245 
05246 static void dahdi_link(struct dahdi_pvt *slave, struct dahdi_pvt *master) {
05247    int x;
05248    if (!slave || !master) {
05249       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
05250       return;
05251    }
05252    for (x = 0; x < MAX_SLAVES; x++) {
05253       if (!master->slaves[x]) {
05254          master->slaves[x] = slave;
05255          break;
05256       }
05257    }
05258    if (x >= MAX_SLAVES) {
05259       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
05260       master->slaves[MAX_SLAVES - 1] = slave;
05261    }
05262    if (slave->master)
05263       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
05264    slave->master = master;
05265 
05266    ast_debug(1, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
05267 }
05268 
05269 static void disable_dtmf_detect(struct dahdi_pvt *p)
05270 {
05271    int val;
05272 
05273    p->ignoredtmf = 1;
05274 
05275    val = 0;
05276    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
05277 
05278    if (!p->hardwaredtmf && p->dsp) {
05279       p->dsp_features &= ~DSP_FEATURE_DIGIT_DETECT;
05280       ast_dsp_set_features(p->dsp, p->dsp_features);
05281    }
05282 }
05283 
05284 static void enable_dtmf_detect(struct dahdi_pvt *p)
05285 {
05286    int val;
05287 
05288    if (p->channel == CHAN_PSEUDO)
05289       return;
05290 
05291    p->ignoredtmf = 0;
05292 
05293    val = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
05294    ioctl(p->subs[SUB_REAL].dfd, DAHDI_TONEDETECT, &val);
05295 
05296    if (!p->hardwaredtmf && p->dsp) {
05297       p->dsp_features |= DSP_FEATURE_DIGIT_DETECT;
05298       ast_dsp_set_features(p->dsp, p->dsp_features);
05299    }
05300 }
05301 
05302 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)
05303 {
05304    struct ast_channel *who;
05305    struct dahdi_pvt *p0, *p1, *op0, *op1;
05306    struct dahdi_pvt *master = NULL, *slave = NULL;
05307    struct ast_frame *f;
05308    int inconf = 0;
05309    int nothingok = 1;
05310    int ofd0, ofd1;
05311    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
05312    int os0 = -1, os1 = -1;
05313    int priority = 0;
05314    struct ast_channel *oc0, *oc1;
05315    enum ast_bridge_result res;
05316 
05317 #ifdef PRI_2BCT
05318    int triedtopribridge = 0;
05319 #endif
05320 
05321    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
05322       There is code below to handle it properly until DTMF is actually seen,
05323       but due to currently unresolved issues it's ignored...
05324    */
05325 
05326    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
05327       return AST_BRIDGE_FAILED_NOWARN;
05328 
05329    ast_channel_lock(c0);
05330    while (ast_channel_trylock(c1)) {
05331       CHANNEL_DEADLOCK_AVOIDANCE(c0);
05332    }
05333 
05334    p0 = c0->tech_pvt;
05335    p1 = c1->tech_pvt;
05336    /* cant do pseudo-channels here */
05337    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
05338       ast_channel_unlock(c0);
05339       ast_channel_unlock(c1);
05340       return AST_BRIDGE_FAILED_NOWARN;
05341    }
05342 
05343    oi0 = dahdi_get_index(c0, p0, 0);
05344    oi1 = dahdi_get_index(c1, p1, 0);
05345    if ((oi0 < 0) || (oi1 < 0)) {
05346       ast_channel_unlock(c0);
05347       ast_channel_unlock(c1);
05348       return AST_BRIDGE_FAILED;
05349    }
05350 
05351    op0 = p0 = c0->tech_pvt;
05352    op1 = p1 = c1->tech_pvt;
05353    ofd0 = c0->fds[0];
05354    ofd1 = c1->fds[0];
05355    oc0 = p0->owner;
05356    oc1 = p1->owner;
05357 
05358    if (ast_mutex_trylock(&p0->lock)) {
05359       /* Don't block, due to potential for deadlock */
05360       ast_channel_unlock(c0);
05361       ast_channel_unlock(c1);
05362       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
05363       return AST_BRIDGE_RETRY;
05364    }
05365    if (ast_mutex_trylock(&p1->lock)) {
05366       /* Don't block, due to potential for deadlock */
05367       ast_mutex_unlock(&p0->lock);
05368       ast_channel_unlock(c0);
05369       ast_channel_unlock(c1);
05370       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
05371       return AST_BRIDGE_RETRY;
05372    }
05373 
05374    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
05375       if (p0->owner && p1->owner) {
05376          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
05377          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
05378             master = p0;
05379             slave = p1;
05380             inconf = 1;
05381          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
05382             master = p1;
05383             slave = p0;
05384             inconf = 1;
05385          } else {
05386             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
05387             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
05388                p0->channel,
05389                oi0, (p0->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
05390                p0->subs[SUB_REAL].inthreeway, p0->channel,
05391                oi0, (p1->subs[SUB_CALLWAIT].dfd > -1) ? 1 : 0,
05392                p1->subs[SUB_REAL].inthreeway);
05393          }
05394          nothingok = 0;
05395       }
05396    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
05397       if (p1->subs[SUB_THREEWAY].inthreeway) {
05398          master = p1;
05399          slave = p0;
05400          nothingok = 0;
05401       }
05402    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
05403       if (p0->subs[SUB_THREEWAY].inthreeway) {
05404          master = p0;
05405          slave = p1;
05406          nothingok = 0;
05407       }
05408    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
05409       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise,
05410          don't put us in anything */
05411       if (p1->subs[SUB_CALLWAIT].inthreeway) {
05412          master = p1;
05413          slave = p0;
05414          nothingok = 0;
05415       }
05416    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
05417       /* Same as previous */
05418       if (p0->subs[SUB_CALLWAIT].inthreeway) {
05419          master = p0;
05420          slave = p1;
05421          nothingok = 0;
05422       }
05423    }
05424    ast_debug(1, "master: %d, slave: %d, nothingok: %d\n",
05425       master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
05426    if (master && slave) {
05427       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
05428          in an active threeway call with a channel that is ringing, we should
05429          indicate ringing. */
05430       if ((oi1 == SUB_THREEWAY) &&
05431          p1->subs[SUB_THREEWAY].inthreeway &&
05432          p1->subs[SUB_REAL].owner &&
05433          p1->subs[SUB_REAL].inthreeway &&
05434          (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
05435          ast_debug(1,
05436             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
05437             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
05438          tone_zone_play_tone(p0->subs[oi0].dfd, DAHDI_TONE_RINGTONE);
05439          os1 = p1->subs[SUB_REAL].owner->_state;
05440       } else {
05441          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
05442             p0->channel, oi0, c0->name, p1->channel, oi1, c1->name);
05443          tone_zone_play_tone(p0->subs[oi0].dfd, -1);
05444       }
05445       if ((oi0 == SUB_THREEWAY) &&
05446          p0->subs[SUB_THREEWAY].inthreeway &&
05447          p0->subs[SUB_REAL].owner &&
05448          p0->subs[SUB_REAL].inthreeway &&
05449          (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
05450          ast_debug(1,
05451             "Playing ringback on %d/%d(%s) since %d/%d(%s) is in a ringing three-way\n",
05452             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
05453          tone_zone_play_tone(p1->subs[oi1].dfd, DAHDI_TONE_RINGTONE);
05454          os0 = p0->subs[SUB_REAL].owner->_state;
05455       } else {
05456          ast_debug(1, "Stopping tones on %d/%d(%s) talking to %d/%d(%s)\n",
05457             p1->channel, oi1, c1->name, p0->channel, oi0, c0->name);
05458          tone_zone_play_tone(p1->subs[oi1].dfd, -1);
05459       }
05460       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
05461          if (!p0->echocanbridged || !p1->echocanbridged) {
05462             /* Disable echo cancellation if appropriate */
05463             dahdi_disable_ec(p0);
05464             dahdi_disable_ec(p1);
05465          }
05466       }
05467       dahdi_link(slave, master);
05468       master->inconference = inconf;
05469    } else if (!nothingok)
05470       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
05471 
05472    update_conf(p0);
05473    update_conf(p1);
05474    t0 = p0->subs[SUB_REAL].inthreeway;
05475    t1 = p1->subs[SUB_REAL].inthreeway;
05476 
05477    ast_mutex_unlock(&p0->lock);
05478    ast_mutex_unlock(&p1->lock);
05479 
05480    ast_channel_unlock(c0);
05481    ast_channel_unlock(c1);
05482 
05483    /* Native bridge failed */
05484    if ((!master || !slave) && !nothingok) {
05485       dahdi_enable_ec(p0);
05486       dahdi_enable_ec(p1);
05487       return AST_BRIDGE_FAILED;
05488    }
05489 
05490    ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
05491 
05492    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
05493       disable_dtmf_detect(op0);
05494 
05495    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
05496       disable_dtmf_detect(op1);
05497 
05498    for (;;) {
05499       struct ast_channel *c0_priority[2] = {c0, c1};
05500       struct ast_channel *c1_priority[2] = {c1, c0};
05501 
05502       /* Here's our main loop...  Start by locking things, looking for private parts,
05503          and then balking if anything is wrong */
05504 
05505       ast_channel_lock(c0);
05506       while (ast_channel_trylock(c1)) {
05507          CHANNEL_DEADLOCK_AVOIDANCE(c0);
05508       }
05509 
05510       p0 = c0->tech_pvt;
05511       p1 = c1->tech_pvt;
05512 
05513       if (op0 == p0)
05514          i0 = dahdi_get_index(c0, p0, 1);
05515       if (op1 == p1)
05516          i1 = dahdi_get_index(c1, p1, 1);
05517 
05518       ast_channel_unlock(c0);
05519       ast_channel_unlock(c1);
05520 
05521       if (!timeoutms ||
05522          (op0 != p0) ||
05523          (op1 != p1) ||
05524          (ofd0 != c0->fds[0]) ||
05525          (ofd1 != c1->fds[0]) ||
05526          (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) ||
05527          (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) ||
05528          (oc0 != p0->owner) ||
05529          (oc1 != p1->owner) ||
05530          (t0 != p0->subs[SUB_REAL].inthreeway) ||
05531          (t1 != p1->subs[SUB_REAL].inthreeway) ||
05532          (oi0 != i0) ||
05533          (oi1 != i1)) {
05534          ast_debug(1, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
05535             op0->channel, oi0, op1->channel, oi1);
05536          res = AST_BRIDGE_RETRY;
05537          goto return_from_bridge;
05538       }
05539 
05540 #ifdef PRI_2BCT
05541       if (!triedtopribridge) {
05542          triedtopribridge = 1;
05543          if (p0->pri && p0->pri == p1->pri && p0->transfer && p1->transfer) {
05544             ast_mutex_lock(&p0->pri->lock);
05545             if (p0->call && p1->call) {
05546                pri_channel_bridge(p0->call, p1->call);
05547             }
05548             ast_mutex_unlock(&p0->pri->lock);
05549          }
05550       }
05551 #endif
05552 
05553       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
05554       if (!who) {
05555          ast_debug(1, "Ooh, empty read...\n");
05556          continue;
05557       }
05558       f = ast_read(who);
05559       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
05560          *fo = f;
05561          *rc = who;
05562          res = AST_BRIDGE_COMPLETE;
05563          goto return_from_bridge;
05564       }
05565       if (f->frametype == AST_FRAME_DTMF) {
05566          if ((who == c0) && p0->pulsedial) {
05567             ast_write(c1, f);
05568          } else if ((who == c1) && p1->pulsedial) {
05569             ast_write(c0, f);
05570          } else {
05571             *fo = f;
05572             *rc = who;
05573             res = AST_BRIDGE_COMPLETE;
05574             goto return_from_bridge;
05575          }
05576       }
05577       ast_frfree(f);
05578 
05579       /* Swap who gets priority */
05580       priority = !priority;
05581    }
05582 
05583 return_from_bridge:
05584    if (op0 == p0)
05585       dahdi_enable_ec(p0);
05586 
05587    if (op1 == p1)
05588       dahdi_enable_ec(p1);
05589 
05590    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
05591       enable_dtmf_detect(op0);
05592 
05593    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
05594       enable_dtmf_detect(op1);
05595 
05596    dahdi_unlink(slave, master, 1);
05597 
05598    return res;
05599 }
05600 
05601 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
05602 {
05603    struct dahdi_pvt *p = newchan->tech_pvt;
05604    int x;
05605    ast_mutex_lock(&p->lock);
05606    ast_debug(1, "New owner for channel %d is %s\n", p->channel, newchan->name);
05607    if (p->owner == oldchan) {
05608       p->owner = newchan;
05609    }
05610    for (x = 0; x < 3; x++)
05611       if (p->subs[x].owner == oldchan) {
05612          if (!x)
05613             dahdi_unlink(NULL, p, 0);
05614          p->subs[x].owner = newchan;
05615       }
05616    update_conf(p);
05617    ast_mutex_unlock(&p->lock);
05618    if (newchan->_state == AST_STATE_RINGING) {
05619       dahdi_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
05620    }
05621    return 0;
05622 }
05623 
05624 static int dahdi_ring_phone(struct dahdi_pvt *p)
05625 {
05626    int x;
05627    int res;
05628    /* Make sure our transmit state is on hook */
05629    x = 0;
05630    x = DAHDI_ONHOOK;
05631    res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
05632    do {
05633       x = DAHDI_RING;
05634       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
05635       if (res) {
05636          switch (errno) {
05637          case EBUSY:
05638          case EINTR:
05639             /* Wait just in case */
05640             usleep(10000);
05641             continue;
05642          case EINPROGRESS:
05643             res = 0;
05644             break;
05645          default:
05646             ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
05647             res = 0;
05648          }
05649       }
05650    } while (res);
05651    return res;
05652 }
05653 
05654 static void *ss_thread(void *data);
05655 
05656 /*!
05657  * \internal
05658  * \brief Attempt to transfer 3-way call.
05659  *
05660  * \param p private structure.
05661  *
05662  * \note
05663  * On entry these locks are held: real-call, private, 3-way call.
05664  *
05665  * \retval 1 Transfer successful.  3-way call is unlocked and subchannel is unalloced.
05666  *         Swapped real and 3-way subchannel.
05667  * \retval 0 Transfer successful.  3-way call is unlocked and subchannel is unalloced.
05668  * \retval -1 on error.  Caller must unlock 3-way call.
05669  */
05670 static int attempt_transfer(struct dahdi_pvt *p)
05671 {
05672    /* In order to transfer, we need at least one of the channels to
05673       actually be in a call bridge.  We can't conference two applications
05674       together (but then, why would we want to?) */
05675    if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
05676       /* The three-way person we're about to transfer to could still be in MOH, so
05677          stop it now if appropriate */
05678       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
05679          ast_queue_control(p->subs[SUB_THREEWAY].owner, AST_CONTROL_UNHOLD);
05680       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
05681          /*
05682           * This may not be safe.
05683           * We currently hold the locks on the real-call, private, and 3-way call.
05684           * We could possibly avoid this here by using an ast_queue_control() instead.
05685           * However, the following ast_channel_masquerade() is going to be locking
05686           * the bridged channel again anyway.
05687           */
05688          ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
05689       }
05690       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RING) {
05691          tone_zone_play_tone(p->subs[SUB_THREEWAY].dfd, DAHDI_TONE_RINGTONE);
05692       }
05693        if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
05694          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
05695                ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
05696          return -1;
05697       }
05698       /* Orphan the channel after releasing the lock */
05699       ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
05700       unalloc_sub(p, SUB_THREEWAY);
05701    } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
05702       ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
05703       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
05704          /*
05705           * This may not be safe.
05706           * We currently hold the locks on the real-call, private, and 3-way call.
05707           * We could possibly avoid this here by using an ast_queue_control() instead.
05708           * However, the following ast_channel_masquerade() is going to be locking
05709           * the bridged channel again anyway.
05710           */
05711          ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
05712       }
05713       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RING) {
05714          tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
05715       }
05716       if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
05717          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
05718                ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
05719          return -1;
05720       }
05721       /* Three-way is now the REAL */
05722       swap_subs(p, SUB_THREEWAY, SUB_REAL);
05723       ast_channel_unlock(p->subs[SUB_REAL].owner);
05724       unalloc_sub(p, SUB_THREEWAY);
05725       /* Tell the caller not to hangup */
05726       return 1;
05727    } else {
05728       ast_debug(1, "Neither %s nor %s are in a bridge, nothing to transfer\n",
05729          p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
05730       return -1;
05731    }
05732    return 0;
05733 }
05734 
05735 static int check_for_conference(struct dahdi_pvt *p)
05736 {
05737    struct dahdi_confinfo ci;
05738    /* Fine if we already have a master, etc */
05739    if (p->master || (p->confno > -1))
05740       return 0;
05741    memset(&ci, 0, sizeof(ci));
05742    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
05743       ast_log(LOG_WARNING, "Failed to get conference info on channel %d: %s\n", p->channel, strerror(errno));
05744       return 0;
05745    }
05746    /* If we have no master and don't have a confno, then
05747       if we're in a conference, it's probably a MeetMe room or
05748       some such, so don't let us 3-way out! */
05749    if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
05750       ast_verb(3, "Avoiding 3-way call when in an external conference\n");
05751       return 1;
05752    }
05753    return 0;
05754 }
05755 
05756 /*! Checks channel for alarms
05757  * \param p a channel to check for alarms.
05758  * \returns the alarms on the span to which the channel belongs, or alarms on
05759  *          the channel if no span alarms.
05760  */
05761 static int get_alarms(struct dahdi_pvt *p)
05762 {
05763    int res;
05764    struct dahdi_spaninfo zi;
05765    struct dahdi_params params;
05766 
05767    memset(&zi, 0, sizeof(zi));
05768    zi.spanno = p->span;
05769 
05770    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SPANSTAT, &zi)) >= 0) {
05771       if (zi.alarms != DAHDI_ALARM_NONE)
05772          return zi.alarms;
05773    } else {
05774       ast_log(LOG_WARNING, "Unable to determine alarm on channel %d: %s\n", p->channel, strerror(errno));
05775       return 0;
05776    }
05777 
05778    /* No alarms on the span. Check for channel alarms. */
05779    memset(&params, 0, sizeof(params));
05780    if ((res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &params)) >= 0)
05781       return params.chan_alarms;
05782 
05783    ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
05784 
05785    return DAHDI_ALARM_NONE;
05786 }
05787 
05788 static void dahdi_handle_dtmfup(struct ast_channel *ast, int idx, struct ast_frame **dest)
05789 {
05790    struct dahdi_pvt *p = ast->tech_pvt;
05791    struct ast_frame *f = *dest;
05792 
05793    ast_debug(1, "DTMF digit: %c on %s\n", f->subclass, ast->name);
05794 
05795    if (p->confirmanswer) {
05796       ast_debug(1, "Confirm answer on %s!\n", ast->name);
05797       /* Upon receiving a DTMF digit, consider this an answer confirmation instead
05798          of a DTMF digit */
05799       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
05800       p->subs[idx].f.subclass = AST_CONTROL_ANSWER;
05801       *dest = &p->subs[idx].f;
05802       /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
05803       p->confirmanswer = 0;
05804    } else if (p->callwaitcas) {
05805       if ((f->subclass == 'A') || (f->subclass == 'D')) {
05806          ast_debug(1, "Got some DTMF, but it's for the CAS\n");
05807          if (p->cidspill)
05808             ast_free(p->cidspill);
05809          send_cwcidspill(p);
05810       }
05811       p->callwaitcas = 0;
05812       p->subs[idx].f.frametype = AST_FRAME_NULL;
05813       p->subs[idx].f.subclass = 0;
05814       *dest = &p->subs[idx].f;
05815    } else if (f->subclass == 'f') {
05816       /* Fax tone -- Handle and return NULL */
05817       if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
05818          /* If faxbuffers are configured, use them for the fax transmission */
05819          if (p->usefaxbuffers && !p->bufferoverrideinuse) {
05820             struct dahdi_bufferinfo bi = {
05821                .txbufpolicy = p->faxbuf_policy,
05822                .bufsize = p->bufsize,
05823                .numbufs = p->faxbuf_no
05824             };
05825             int res;
05826 
05827             if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
05828                ast_log(LOG_WARNING, "Channel '%s' unable to set faxbuffer policy, reason: %s\n", ast->name, strerror(errno));
05829             } else {
05830                p->bufferoverrideinuse = 1;
05831             }
05832          }
05833          p->faxhandled = 1;
05834          if (strcmp(ast->exten, "fax")) {
05835             const char *target_context = S_OR(ast->macrocontext, ast->context);
05836 
05837             /* We need to unlock 'ast' here because ast_exists_extension has the
05838              * potential to start autoservice on the channel. Such action is prone
05839              * to deadlock.
05840              */
05841             ast_mutex_unlock(&p->lock);
05842             ast_channel_unlock(ast);
05843             if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
05844                ast_channel_lock(ast);
05845                ast_mutex_lock(&p->lock);
05846                ast_verb(3, "Redirecting %s to fax extension\n", ast->name);
05847                /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
05848                pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
05849                if (ast_async_goto(ast, target_context, "fax", 1))
05850                   ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
05851             } else {
05852                ast_channel_lock(ast);
05853                ast_mutex_lock(&p->lock);
05854                ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
05855             }
05856          } else {
05857             ast_debug(1, "Already in a fax extension, not redirecting\n");
05858          }
05859       } else {
05860          ast_debug(1, "Fax already handled\n");
05861       }
05862       dahdi_confmute(p, 0);
05863       p->subs[idx].f.frametype = AST_FRAME_NULL;
05864       p->subs[idx].f.subclass = 0;
05865       *dest = &p->subs[idx].f;
05866    }
05867 }
05868 
05869 static void handle_alarms(struct dahdi_pvt *p, int alms)
05870 {
05871    const char *alarm_str = alarm2str(alms);
05872 
05873    ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm_str);
05874    manager_event(EVENT_FLAG_SYSTEM, "Alarm",
05875       "Alarm: %s\r\n"
05876       "Channel: %d\r\n",
05877       alarm_str, p->channel);
05878 }
05879 
05880 static struct ast_frame *dahdi_handle_event(struct ast_channel *ast)
05881 {
05882    int res, x;
05883    int idx, mysig;
05884    char *c;
05885    struct dahdi_pvt *p = ast->tech_pvt;
05886    pthread_t threadid;
05887    struct ast_channel *chan;
05888    struct ast_frame *f;
05889 
05890    idx = dahdi_get_index(ast, p, 0);
05891    if (idx < 0) {
05892       return &ast_null_frame;
05893    }
05894    if (idx != SUB_REAL) {
05895       ast_log(LOG_ERROR, "We got an event on a non real sub.  Fix it!\n");
05896    }
05897 
05898    mysig = p->sig;
05899    if (p->outsigmod > -1)
05900       mysig = p->outsigmod;
05901 
05902    p->subs[idx].f.frametype = AST_FRAME_NULL;
05903    p->subs[idx].f.subclass = 0;
05904    p->subs[idx].f.datalen = 0;
05905    p->subs[idx].f.samples = 0;
05906    p->subs[idx].f.mallocd = 0;
05907    p->subs[idx].f.offset = 0;
05908    p->subs[idx].f.src = "dahdi_handle_event";
05909    p->subs[idx].f.data.ptr = NULL;
05910    f = &p->subs[idx].f;
05911 
05912    if (p->fake_event) {
05913       res = p->fake_event;
05914       p->fake_event = 0;
05915    } else
05916       res = dahdi_get_event(p->subs[idx].dfd);
05917 
05918    ast_debug(1, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, idx);
05919 
05920    if (res & (DAHDI_EVENT_PULSEDIGIT | DAHDI_EVENT_DTMFUP)) {
05921       p->pulsedial = (res & DAHDI_EVENT_PULSEDIGIT) ? 1 : 0;
05922       ast_debug(1, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
05923 #ifdef HAVE_PRI
05924       if (!p->proceeding && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) && p->pri && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
05925          /* absorb event */
05926       } else {
05927 #endif
05928          dahdi_confmute(p, 0);
05929          p->subs[idx].f.frametype = AST_FRAME_DTMF_END;
05930          p->subs[idx].f.subclass = res & 0xff;
05931 #ifdef HAVE_PRI
05932       }
05933 #endif
05934       dahdi_handle_dtmfup(ast, idx, &f);
05935       return f;
05936    }
05937 
05938    if (res & DAHDI_EVENT_DTMFDOWN) {
05939       ast_debug(1, "DTMF Down '%c'\n", res & 0xff);
05940       /* Mute conference */
05941       dahdi_confmute(p, 1);
05942       p->subs[idx].f.frametype = AST_FRAME_DTMF_BEGIN;
05943       p->subs[idx].f.subclass = res & 0xff;
05944       return &p->subs[idx].f;
05945    }
05946 
05947    switch (res) {
05948       case DAHDI_EVENT_EC_DISABLED:
05949          ast_verb(3, "Channel %d echo canceler disabled due to CED detection\n", p->channel);
05950          p->echocanon = 0;
05951          break;
05952       case DAHDI_EVENT_BITSCHANGED:
05953 #ifdef HAVE_OPENR2
05954          if (p->sig != SIG_MFCR2) {
05955             ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
05956          } else {
05957             ast_log(LOG_DEBUG, "bits changed in chan %d\n", p->channel);
05958             openr2_chan_handle_cas(p->r2chan);
05959          }
05960 #else
05961          ast_log(LOG_WARNING, "Received bits changed on %s signalling?\n", sig2str(p->sig));
05962 #endif
05963       case DAHDI_EVENT_PULSE_START:
05964          /* Stop tone if there's a pulse start and the PBX isn't started */
05965          if (!ast->pbx)
05966             tone_zone_play_tone(p->subs[idx].dfd, -1);
05967          break;
05968       case DAHDI_EVENT_DIALCOMPLETE:
05969 #ifdef HAVE_OPENR2
05970          if ((p->sig & SIG_MFCR2) && p->r2chan && ast->_state != AST_STATE_UP) {
05971             /* we don't need to do anything for this event for R2 signaling
05972                if the call is being setup */
05973             break;
05974          }
05975 #endif
05976          if (p->inalarm) break;
05977          if ((p->radio || (p->oprmode < 0))) break;
05978          if (ioctl(p->subs[idx].dfd,DAHDI_DIALING,&x) == -1) {
05979             ast_log(LOG_DEBUG, "DAHDI_DIALING ioctl failed on %s: %s\n",ast->name, strerror(errno));
05980             return NULL;
05981          }
05982          if (!x) { /* if not still dialing in driver */
05983             dahdi_enable_ec(p);
05984             if (p->echobreak) {
05985                dahdi_train_ec(p);
05986                ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
05987                p->dop.op = DAHDI_DIAL_OP_REPLACE;
05988                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
05989                p->echobreak = 0;
05990             } else {
05991                p->dialing = 0;
05992                if ((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) {
05993                   /* if thru with dialing after offhook */
05994                   if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
05995                      ast_setstate(ast, AST_STATE_UP);
05996                      p->subs[idx].f.frametype = AST_FRAME_CONTROL;
05997                      p->subs[idx].f.subclass = AST_CONTROL_ANSWER;
05998                      break;
05999                   } else { /* if to state wait for offhook to dial rest */
06000                      /* we now wait for off hook */
06001                      ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
06002                   }
06003                }
06004                if (ast->_state == AST_STATE_DIALING) {
06005                   if ((p->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
06006                      ast_debug(1, "Done dialing, but waiting for progress detection before doing more...\n");
06007                   } else if (p->confirmanswer || (!p->dialednone
06008                      && ((mysig == SIG_EM) || (mysig == SIG_EM_E1)
06009                         || (mysig == SIG_EMWINK) || (mysig == SIG_FEATD)
06010                         || (mysig == SIG_FEATDMF_TA) || (mysig == SIG_FEATDMF)
06011                         || (mysig == SIG_E911) || (mysig == SIG_FGC_CAMA)
06012                         || (mysig == SIG_FGC_CAMAMF) || (mysig == SIG_FEATB)
06013                         || (mysig == SIG_SF) || (mysig == SIG_SFWINK)
06014                         || (mysig == SIG_SF_FEATD) || (mysig == SIG_SF_FEATDMF)
06015                         || (mysig == SIG_SF_FEATB)))) {
06016                      ast_setstate(ast, AST_STATE_RINGING);
06017                   } else if (!p->answeronpolarityswitch) {
06018                      ast_setstate(ast, AST_STATE_UP);
06019                      p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06020                      p->subs[idx].f.subclass = AST_CONTROL_ANSWER;
06021                      /* If aops=0 and hops=1, this is necessary */
06022                      p->polarity = POLARITY_REV;
06023                   } else {
06024                      /* Start clean, so we can catch the change to REV polarity when party answers */
06025                      p->polarity = POLARITY_IDLE;
06026                   }
06027                }
06028             }
06029          }
06030          break;
06031       case DAHDI_EVENT_ALARM:
06032 #ifdef HAVE_PRI
06033          if ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
06034             if (!p->pri || !p->pri->pri || (pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0)) {
06035                /* T309 is not enabled : hangup calls when alarm occurs */
06036                if (p->call) {
06037                   if (p->pri && p->pri->pri) {
06038                      if (!pri_grab(p, p->pri)) {
06039                         pri_hangup(p->pri->pri, p->call, -1);
06040                         pri_destroycall(p->pri->pri, p->call);
06041                         p->call = NULL;
06042                         pri_rel(p->pri);
06043                      } else
06044                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
06045                   } else
06046                      ast_log(LOG_WARNING, "The PRI Call has not been destroyed\n");
06047                }
06048                if (p->owner)
06049                   p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
06050             }
06051          }
06052          if (p->bearer)
06053             p->bearer->inalarm = 1;
06054          else
06055 #endif
06056          p->inalarm = 1;
06057          res = get_alarms(p);
06058          handle_alarms(p, res);
06059 #ifdef HAVE_PRI
06060          if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
06061             /* fall through intentionally */
06062          } else {
06063             break;
06064          }
06065 #endif
06066 #ifdef HAVE_SS7
06067          if (p->sig == SIG_SS7)
06068             break;
06069 #endif
06070 #ifdef HAVE_OPENR2
06071          if (p->sig == SIG_MFCR2)
06072             break;
06073 #endif
06074       case DAHDI_EVENT_ONHOOK:
06075          if (p->radio) {
06076             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06077             p->subs[idx].f.subclass = AST_CONTROL_RADIO_UNKEY;
06078             break;
06079          }
06080          if (p->oprmode < 0)
06081          {
06082             if (p->oprmode != -1) break;
06083             if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
06084             {
06085                /* Make sure it starts ringing */
06086                dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
06087                dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RING);
06088                save_conference(p->oprpeer);
06089                tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
06090             }
06091             break;
06092          }
06093          switch (p->sig) {
06094          case SIG_FXOLS:
06095          case SIG_FXOGS:
06096          case SIG_FXOKS:
06097             p->onhooktime = time(NULL);
06098             p->fxsoffhookstate = 0;
06099             p->msgstate = -1;
06100             /* Check for some special conditions regarding call waiting */
06101             if (idx == SUB_REAL) {
06102                /* The normal line was hung up */
06103                if (p->subs[SUB_CALLWAIT].owner) {
06104                   /* Need to hold the lock for real-call, private, and call-waiting call */
06105                   dahdi_lock_sub_owner(p, SUB_CALLWAIT);
06106                   if (!p->subs[SUB_CALLWAIT].owner) {
06107                      /*
06108                       * The call waiting call dissappeared.
06109                       * This is now a normal hangup.
06110                       */
06111                      dahdi_disable_ec(p);
06112                      return NULL;
06113                   }
06114 
06115                   /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
06116                   swap_subs(p, SUB_CALLWAIT, SUB_REAL);
06117                   ast_verb(3, "Channel %d still has (callwait) call, ringing phone\n", p->channel);
06118                   unalloc_sub(p, SUB_CALLWAIT);
06119 #if 0
06120                   p->subs[idx].needanswer = 0;
06121                   p->subs[idx].needringing = 0;
06122 #endif
06123                   p->callwaitingrepeat = 0;
06124                   p->cidcwexpire = 0;
06125                   p->owner = NULL;
06126                   /* Don't start streaming audio yet if the incoming call isn't up yet */
06127                   if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
06128                      p->dialing = 1;
06129                   /* Unlock the call-waiting call that we swapped to real-call. */
06130                   ast_channel_unlock(p->subs[SUB_REAL].owner);
06131                   dahdi_ring_phone(p);
06132                } else if (p->subs[SUB_THREEWAY].owner) {
06133                   unsigned int mssinceflash;
06134 
06135                   /* Need to hold the lock for real-call, private, and 3-way call */
06136                   dahdi_lock_sub_owner(p, SUB_THREEWAY);
06137                   if (!p->subs[SUB_THREEWAY].owner) {
06138                      ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
06139                      /* Just hangup */
06140                      return NULL;
06141                   }
06142                   if (p->owner != ast) {
06143                      ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
06144                      ast_log(LOG_WARNING, "This isn't good...\n");
06145                      /* Just hangup */
06146                      return NULL;
06147                   }
06148 
06149                   mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
06150                   ast_debug(1, "Last flash was %d ms ago\n", mssinceflash);
06151                   if (mssinceflash < MIN_MS_SINCE_FLASH) {
06152                      /* It hasn't been long enough since the last flashook.  This is probably a bounce on
06153                         hanging up.  Hangup both channels now */
06154                      ast_debug(1, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
06155                      ast_queue_hangup_with_cause(p->subs[SUB_THREEWAY].owner, AST_CAUSE_NO_ANSWER);
06156                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
06157                      ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
06158                   } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
06159                      if (p->transfer) {
06160                         /* In any case this isn't a threeway call anymore */
06161                         p->subs[SUB_REAL].inthreeway = 0;
06162                         p->subs[SUB_THREEWAY].inthreeway = 0;
06163                         /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
06164                         if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
06165                            /* Swap subs and dis-own channel */
06166                            swap_subs(p, SUB_THREEWAY, SUB_REAL);
06167                            /* Unlock the 3-way call that we swapped to real-call. */
06168                            ast_channel_unlock(p->subs[SUB_REAL].owner);
06169                            p->owner = NULL;
06170                            /* Ring the phone */
06171                            dahdi_ring_phone(p);
06172                         } else {
06173                            res = attempt_transfer(p);
06174                            if (res < 0) {
06175                               /* Transfer attempt failed. */
06176                               p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
06177                               ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
06178                            } else if (res) {
06179                               /* Don't actually hang up at this point */
06180                               break;
06181                            }
06182                         }
06183                      } else {
06184                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
06185                         ast_channel_unlock(p->subs[SUB_THREEWAY].owner);
06186                      }
06187                   } else {
06188                      /* Swap subs and dis-own channel */
06189                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
06190                      /* Unlock the 3-way call that we swapped to real-call. */
06191                      ast_channel_unlock(p->subs[SUB_REAL].owner);
06192                      p->owner = NULL;
06193                      /* Ring the phone */
06194                      dahdi_ring_phone(p);
06195                   }
06196                }
06197             } else {
06198                ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", idx);
06199             }
06200             /* Fall through */
06201          default:
06202             dahdi_disable_ec(p);
06203             return NULL;
06204          }
06205          break;
06206       case DAHDI_EVENT_RINGOFFHOOK:
06207          if (p->inalarm) break;
06208          if (p->oprmode < 0)
06209          {
06210             if ((p->sig == SIG_FXOLS) || (p->sig == SIG_FXOKS) || (p->sig == SIG_FXOGS))
06211             {
06212                /* Make sure it stops ringing */
06213                dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
06214                tone_zone_play_tone(p->oprpeer->subs[SUB_REAL].dfd, -1);
06215                restore_conference(p->oprpeer);
06216             }
06217             break;
06218          }
06219          if (p->radio)
06220          {
06221             p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06222             p->subs[idx].f.subclass = AST_CONTROL_RADIO_KEY;
06223             break;
06224          }
06225          /* for E911, its supposed to wait for offhook then dial
06226             the second half of the dial string */
06227          if (((mysig == SIG_E911) || (mysig == SIG_FGC_CAMA) || (mysig == SIG_FGC_CAMAMF)) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
06228             c = strchr(p->dialdest, '/');
06229             if (c)
06230                c++;
06231             else
06232                c = p->dialdest;
06233             if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
06234             else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
06235             if (strlen(p->dop.dialstr) > 4) {
06236                memset(p->echorest, 'w', sizeof(p->echorest) - 1);
06237                strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
06238                p->echorest[sizeof(p->echorest) - 1] = '\0';
06239                p->echobreak = 1;
06240                p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
06241             } else
06242                p->echobreak = 0;
06243             if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
06244                int saveerr = errno;
06245 
06246                x = DAHDI_ONHOOK;
06247                ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
06248                ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
06249                return NULL;
06250                }
06251             p->dialing = 1;
06252             return &p->subs[idx].f;
06253          }
06254          switch (p->sig) {
06255          case SIG_FXOLS:
06256          case SIG_FXOGS:
06257          case SIG_FXOKS:
06258             p->fxsoffhookstate = 1;
06259             switch (ast->_state) {
06260             case AST_STATE_RINGING:
06261                dahdi_enable_ec(p);
06262                dahdi_train_ec(p);
06263                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06264                p->subs[idx].f.subclass = AST_CONTROL_ANSWER;
06265                /* Make sure it stops ringing */
06266                p->subs[SUB_REAL].needringing = 0;
06267                dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
06268                ast_debug(1, "channel %d answered\n", p->channel);
06269                if (p->cidspill) {
06270                   /* Cancel any running CallerID spill */
06271                   ast_free(p->cidspill);
06272                   p->cidspill = NULL;
06273                }
06274                p->dialing = 0;
06275                p->callwaitcas = 0;
06276                if (p->confirmanswer) {
06277                   /* Ignore answer if "confirm answer" is enabled */
06278                   p->subs[idx].f.frametype = AST_FRAME_NULL;
06279                   p->subs[idx].f.subclass = 0;
06280                } else if (!ast_strlen_zero(p->dop.dialstr)) {
06281                   /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
06282                   res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
06283                   if (res < 0) {
06284                      ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
06285                      p->dop.dialstr[0] = '\0';
06286                      return NULL;
06287                   } else {
06288                      ast_debug(1, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
06289                      p->subs[idx].f.frametype = AST_FRAME_NULL;
06290                      p->subs[idx].f.subclass = 0;
06291                      p->dialing = 1;
06292                   }
06293                   p->dop.dialstr[0] = '\0';
06294                   ast_setstate(ast, AST_STATE_DIALING);
06295                } else
06296                   ast_setstate(ast, AST_STATE_UP);
06297                return &p->subs[idx].f;
06298             case AST_STATE_DOWN:
06299                ast_setstate(ast, AST_STATE_RING);
06300                ast->rings = 1;
06301                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06302                p->subs[idx].f.subclass = AST_CONTROL_OFFHOOK;
06303                ast_debug(1, "channel %d picked up\n", p->channel);
06304                return &p->subs[idx].f;
06305             case AST_STATE_UP:
06306                /* Make sure it stops ringing */
06307                dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
06308                /* Okay -- probably call waiting*/
06309                if (ast_bridged_channel(p->owner))
06310                   ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
06311                p->subs[idx].needunhold = 1;
06312                break;
06313             case AST_STATE_RESERVED:
06314                /* Start up dialtone */
06315                if (has_voicemail(p))
06316                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
06317                else
06318                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
06319                break;
06320             default:
06321                ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
06322             }
06323             break;
06324          case SIG_FXSLS:
06325          case SIG_FXSGS:
06326          case SIG_FXSKS:
06327             if (ast->_state == AST_STATE_RING) {
06328                p->ringt = p->ringt_base;
06329             }
06330 
06331             /* If we get a ring then we cannot be in
06332              * reversed polarity. So we reset to idle */
06333             ast_debug(1, "Setting IDLE polarity due "
06334                "to ring. Old polarity was %d\n",
06335                p->polarity);
06336             p->polarity = POLARITY_IDLE;
06337 
06338             /* Fall through */
06339          case SIG_EM:
06340          case SIG_EM_E1:
06341          case SIG_EMWINK:
06342          case SIG_FEATD:
06343          case SIG_FEATDMF:
06344          case SIG_FEATDMF_TA:
06345          case SIG_E911:
06346          case SIG_FGC_CAMA:
06347          case SIG_FGC_CAMAMF:
06348          case SIG_FEATB:
06349          case SIG_SF:
06350          case SIG_SFWINK:
06351          case SIG_SF_FEATD:
06352          case SIG_SF_FEATDMF:
06353          case SIG_SF_FEATB:
06354             if (ast->_state == AST_STATE_PRERING)
06355                ast_setstate(ast, AST_STATE_RING);
06356             if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
06357                ast_debug(1, "Ring detected\n");
06358                p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06359                p->subs[idx].f.subclass = AST_CONTROL_RING;
06360             } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
06361                ast_debug(1, "Line answered\n");
06362                if (p->confirmanswer) {
06363                   p->subs[idx].f.frametype = AST_FRAME_NULL;
06364                   p->subs[idx].f.subclass = 0;
06365                } else {
06366                   p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06367                   p->subs[idx].f.subclass = AST_CONTROL_ANSWER;
06368                   ast_setstate(ast, AST_STATE_UP);
06369                }
06370             } else if (ast->_state != AST_STATE_RING)
06371                ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
06372             break;
06373          default:
06374             ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
06375          }
06376          break;
06377       case DAHDI_EVENT_RINGBEGIN:
06378          switch (p->sig) {
06379          case SIG_FXSLS:
06380          case SIG_FXSGS:
06381          case SIG_FXSKS:
06382             if (ast->_state == AST_STATE_RING) {
06383                p->ringt = p->ringt_base;
06384             }
06385             break;
06386          }
06387          break;
06388       case DAHDI_EVENT_RINGEROFF:
06389          if (p->inalarm) break;
06390          if ((p->radio || (p->oprmode < 0))) break;
06391          ast->rings++;
06392          if ((ast->rings > p->cidrings) && (p->cidspill)) {
06393             ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
06394             ast_free(p->cidspill);
06395             p->cidspill = NULL;
06396             p->callwaitcas = 0;
06397          }
06398          p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06399          p->subs[idx].f.subclass = AST_CONTROL_RINGING;
06400          break;
06401       case DAHDI_EVENT_RINGERON:
06402          break;
06403       case DAHDI_EVENT_NOALARM:
06404          p->inalarm = 0;
06405 #ifdef HAVE_PRI
06406          /* Extremely unlikely but just in case */
06407          if (p->bearer)
06408             p->bearer->inalarm = 0;
06409 #endif
06410          ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
06411          manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
06412                         "Channel: %d\r\n", p->channel);
06413          break;
06414       case DAHDI_EVENT_WINKFLASH:
06415          if (p->inalarm) break;
06416          if (p->radio) break;
06417          if (p->oprmode < 0) break;
06418          if (p->oprmode > 1)
06419          {
06420             struct dahdi_params par;
06421 
06422             memset(&par, 0, sizeof(par));
06423             if (ioctl(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par) != -1)
06424             {
06425                if (!par.rxisoffhook)
06426                {
06427                   /* Make sure it stops ringing */
06428                   dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RINGOFF);
06429                   dahdi_set_hook(p->oprpeer->subs[SUB_REAL].dfd, DAHDI_RING);
06430                   save_conference(p);
06431                   tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
06432                }
06433             }
06434             break;
06435          }
06436          /* Remember last time we got a flash-hook */
06437          p->flashtime = ast_tvnow();
06438          switch (mysig) {
06439          case SIG_FXOLS:
06440          case SIG_FXOGS:
06441          case SIG_FXOKS:
06442             ast_debug(1, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
06443                idx, p->subs[SUB_REAL].dfd, p->subs[SUB_CALLWAIT].dfd, p->subs[SUB_THREEWAY].dfd);
06444             p->callwaitcas = 0;
06445 
06446             if (idx != SUB_REAL) {
06447                ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", idx, p->channel);
06448                goto winkflashdone;
06449             }
06450 
06451             if (p->subs[SUB_CALLWAIT].owner) {
06452                /* Need to hold the lock for real-call, private, and call-waiting call */
06453                dahdi_lock_sub_owner(p, SUB_CALLWAIT);
06454                if (!p->subs[SUB_CALLWAIT].owner) {
06455                   /*
06456                    * The call waiting call dissappeared.
06457                    * Let's just ignore this flash-hook.
06458                    */
06459                   ast_log(LOG_NOTICE, "Whoa, the call-waiting call disappeared.\n");
06460                   goto winkflashdone;
06461                }
06462 
06463                /* Swap to call-wait */
06464                swap_subs(p, SUB_REAL, SUB_CALLWAIT);
06465                tone_zone_play_tone(p->subs[SUB_REAL].dfd, -1);
06466                p->owner = p->subs[SUB_REAL].owner;
06467                ast_debug(1, "Making %s the new owner\n", p->owner->name);
06468                if (p->owner->_state == AST_STATE_RINGING) {
06469                   ast_setstate(p->owner, AST_STATE_UP);
06470                   p->subs[SUB_REAL].needanswer = 1;
06471                }
06472                p->callwaitingrepeat = 0;
06473                p->cidcwexpire = 0;
06474 
06475                /* Start music on hold if appropriate */
06476                if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
06477                   ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD,
06478                      S_OR(p->mohsuggest, NULL),
06479                      !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06480                }
06481                p->subs[SUB_CALLWAIT].needhold = 1;
06482                if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
06483                   ast_queue_control_data(p->subs[SUB_REAL].owner, AST_CONTROL_HOLD,
06484                      S_OR(p->mohsuggest, NULL),
06485                      !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06486                }
06487                p->subs[SUB_REAL].needunhold = 1;
06488 
06489                /* Unlock the call-waiting call that we swapped to real-call. */
06490                ast_channel_unlock(p->subs[SUB_REAL].owner);
06491             } else if (!p->subs[SUB_THREEWAY].owner) {
06492                if (!p->threewaycalling) {
06493                   /* Just send a flash if no 3-way calling */
06494                   p->subs[SUB_REAL].needflash = 1;
06495                   goto winkflashdone;
06496                } else if (!check_for_conference(p)) {
06497                   char cid_num[256];
06498                   char cid_name[256];
06499 
06500                   cid_num[0] = 0;
06501                   cid_name[0] = 0;
06502                   if (p->dahditrcallerid && p->owner) {
06503                      if (p->owner->cid.cid_num)
06504                         ast_copy_string(cid_num, p->owner->cid.cid_num, sizeof(cid_num));
06505                      if (p->owner->cid.cid_name)
06506                         ast_copy_string(cid_name, p->owner->cid.cid_name, sizeof(cid_name));
06507                   }
06508                   /* XXX This section needs much more error checking!!! XXX */
06509                   /* Start a 3-way call if feasible */
06510                   if (!((ast->pbx) ||
06511                      (ast->_state == AST_STATE_UP) ||
06512                      (ast->_state == AST_STATE_RING))) {
06513                      ast_debug(1, "Flash when call not up or ringing\n");
06514                      goto winkflashdone;
06515                   }
06516                   if (alloc_sub(p, SUB_THREEWAY)) {
06517                      ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
06518                      goto winkflashdone;
06519                   }
06520                   /* Make new channel */
06521                   chan = dahdi_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
06522                   if (!chan) {
06523                      ast_log(LOG_WARNING,
06524                         "Cannot allocate new call structure on channel %d\n",
06525                         p->channel);
06526                      unalloc_sub(p, SUB_THREEWAY);
06527                      goto winkflashdone;
06528                   }
06529                   if (p->dahditrcallerid) {
06530                      if (!p->origcid_num)
06531                         p->origcid_num = ast_strdup(p->cid_num);
06532                      if (!p->origcid_name)
06533                         p->origcid_name = ast_strdup(p->cid_name);
06534                      ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
06535                      ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
06536                   }
06537                   /* Swap things around between the three-way and real call */
06538                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
06539                   /* Disable echo canceller for better dialing */
06540                   dahdi_disable_ec(p);
06541                   res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_DIALRECALL);
06542                   if (res)
06543                      ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
06544                   p->owner = chan;
06545                   if (ast_pthread_create_detached(&threadid, NULL, ss_thread, chan)) {
06546                      ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
06547                      res = tone_zone_play_tone(p->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
06548                      dahdi_enable_ec(p);
06549                      ast_hangup(chan);
06550                   } else {
06551                      ast_verb(3, "Started three way call on channel %d\n", p->channel);
06552 
06553                      /* Start music on hold if appropriate */
06554                      if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
06555                         ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD,
06556                            S_OR(p->mohsuggest, NULL),
06557                            !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
06558                      }
06559                      p->subs[SUB_THREEWAY].needhold = 1;
06560                   }
06561                }
06562             } else {
06563                /* Already have a 3 way call */
06564                int orig_3way_sub;
06565 
06566                /* Need to hold the lock for real-call, private, and 3-way call */
06567                dahdi_lock_sub_owner(p, SUB_THREEWAY);
06568                if (!p->subs[SUB_THREEWAY].owner) {
06569                   /*
06570                    * The 3-way call dissappeared.
06571                    * Let's just ignore this flash-hook.
06572                    */
06573                   ast_log(LOG_NOTICE, "Whoa, the 3-way call disappeared.\n");
06574                   goto winkflashdone;
06575                }
06576                orig_3way_sub = SUB_THREEWAY;
06577 
06578                if (p->subs[SUB_THREEWAY].inthreeway) {
06579                   /* Call is already up, drop the last person */
06580                   ast_debug(1, "Got flash with three way call up, dropping last call on %d\n", p->channel);
06581                   /* If the primary call isn't answered yet, use it */
06582                   if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
06583                      /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
06584                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
06585                      orig_3way_sub = SUB_REAL;
06586                      p->owner = p->subs[SUB_REAL].owner;
06587                   }
06588                   /* Drop the last call and stop the conference */
06589                   ast_verb(3, "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
06590                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
06591                   p->subs[SUB_REAL].inthreeway = 0;
06592                   p->subs[SUB_THREEWAY].inthreeway = 0;
06593                } else {
06594                   /* Lets see what we're up to */
06595                   if (((ast->pbx) || (ast->_state == AST_STATE_UP)) &&
06596                      (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
06597                      ast_verb(3, "Building conference call with %s and %s\n",
06598                         p->subs[SUB_THREEWAY].owner->name,
06599                         p->subs[SUB_REAL].owner->name);
06600                      /* Put them in the threeway, and flip */
06601                      p->subs[SUB_THREEWAY].inthreeway = 1;
06602                      p->subs[SUB_REAL].inthreeway = 1;
06603                      if (ast->_state == AST_STATE_UP) {
06604                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
06605                         orig_3way_sub = SUB_REAL;
06606                      }
06607                      if (ast_bridged_channel(p->subs[orig_3way_sub].owner)) {
06608                         ast_queue_control(p->subs[orig_3way_sub].owner, AST_CONTROL_UNHOLD);
06609                      }
06610                      p->subs[orig_3way_sub].needunhold = 1;
06611                      p->owner = p->subs[SUB_REAL].owner;
06612                   } else {
06613                      ast_verb(3, "Dumping incomplete call on %s\n", p->subs[SUB_THREEWAY].owner->name);
06614                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
06615                      orig_3way_sub = SUB_REAL;
06616                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
06617                      p->owner = p->subs[SUB_REAL].owner;
06618                      if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
06619                         ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
06620                      }
06621                      p->subs[SUB_REAL].needunhold = 1;
06622                      dahdi_enable_ec(p);
06623                   }
06624                }
06625                ast_channel_unlock(p->subs[orig_3way_sub].owner);
06626             }
06627 winkflashdone:
06628             update_conf(p);
06629             break;
06630          case SIG_EM:
06631          case SIG_EM_E1:
06632          case SIG_FEATD:
06633          case SIG_SF:
06634          case SIG_SFWINK:
06635          case SIG_SF_FEATD:
06636          case SIG_FXSLS:
06637          case SIG_FXSGS:
06638             if (option_debug) {
06639                if (p->dialing)
06640                   ast_debug(1, "Ignoring wink on channel %d\n", p->channel);
06641                else
06642                   ast_debug(1, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
06643             }
06644             break;
06645          case SIG_FEATDMF_TA:
06646             switch (p->whichwink) {
06647             case 0:
06648                ast_debug(1, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
06649                snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
06650                break;
06651             case 1:
06652                ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
06653                break;
06654             case 2:
06655                ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
06656                return NULL;
06657             }
06658             p->whichwink++;
06659             /* Fall through */
06660          case SIG_FEATDMF:
06661          case SIG_E911:
06662          case SIG_FGC_CAMAMF:
06663          case SIG_FGC_CAMA:
06664          case SIG_FEATB:
06665          case SIG_SF_FEATDMF:
06666          case SIG_SF_FEATB:
06667          case SIG_EMWINK:
06668             /* FGD MF and EMWINK *Must* wait for wink */
06669             if (!ast_strlen_zero(p->dop.dialstr)) {
06670                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
06671                if (res < 0) {
06672                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
06673                   p->dop.dialstr[0] = '\0';
06674                   return NULL;
06675                } else
06676                   ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
06677             }
06678             p->dop.dialstr[0] = '\0';
06679             break;
06680          default:
06681             ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
06682          }
06683          break;
06684       case DAHDI_EVENT_HOOKCOMPLETE:
06685          if (p->inalarm) break;
06686          if ((p->radio || (p->oprmode < 0))) break;
06687          if (p->waitingfordt.tv_sec) break;
06688          switch (mysig) {
06689          case SIG_FXSLS:  /* only interesting for FXS */
06690          case SIG_FXSGS:
06691          case SIG_FXSKS:
06692          case SIG_EM:
06693          case SIG_EM_E1:
06694          case SIG_EMWINK:
06695          case SIG_FEATD:
06696          case SIG_SF:
06697          case SIG_SFWINK:
06698          case SIG_SF_FEATD:
06699             if (!ast_strlen_zero(p->dop.dialstr)) {
06700                res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
06701                if (res < 0) {
06702                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", p->channel, strerror(errno));
06703                   p->dop.dialstr[0] = '\0';
06704                   return NULL;
06705                } else
06706                   ast_debug(1, "Sent deferred digit string: %s\n", p->dop.dialstr);
06707             }
06708             p->dop.dialstr[0] = '\0';
06709             p->dop.op = DAHDI_DIAL_OP_REPLACE;
06710             break;
06711          case SIG_FEATDMF:
06712          case SIG_FEATDMF_TA:
06713          case SIG_E911:
06714          case SIG_FGC_CAMA:
06715          case SIG_FGC_CAMAMF:
06716          case SIG_FEATB:
06717          case SIG_SF_FEATDMF:
06718          case SIG_SF_FEATB:
06719             ast_debug(1, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
06720             break;
06721          default:
06722             break;
06723          }
06724          break;
06725       case DAHDI_EVENT_POLARITY:
06726          /*
06727           * If we get a Polarity Switch event, this could be
06728           * due to line seizure, remote end connect or remote end disconnect.
06729           *
06730           * Check to see if we should change the polarity state and
06731           * mark the channel as UP or if this is an indication
06732           * of remote end disconnect.
06733           */
06734 
06735          if (p->polarityonanswerdelay > 0) {
06736             /* check if event is not too soon after OffHook or Answer */
06737             if (ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
06738                switch (ast->_state) {
06739                case AST_STATE_DIALING:       /*!< Digits (or equivalent) have been dialed */
06740                case AST_STATE_RINGING:       /*!< Remote end is ringing */
06741                   if (p->answeronpolarityswitch) {
06742                      ast_debug(1, "Answering on polarity switch! channel %d\n", p->channel);
06743                      ast_setstate(p->owner, AST_STATE_UP);
06744                      p->polarity = POLARITY_REV;
06745                      if (p->hanguponpolarityswitch) {
06746                         p->polaritydelaytv = ast_tvnow();
06747                      }
06748                   } else {
06749                      ast_debug(1, "Ignore Answer on polarity switch, channel %d\n", p->channel);
06750                   }
06751                   break;
06752 
06753                case AST_STATE_UP:         /*!< Line is up */
06754                case AST_STATE_RING:       /*!< Line is ringing */
06755                   if (p->hanguponpolarityswitch) {
06756                      ast_debug(1, "HangingUp on polarity switch! channel %d\n", p->channel);
06757                      ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
06758                      p->polarity = POLARITY_IDLE;
06759                   } else {
06760                      ast_debug(1, "Ignore Hangup on polarity switch, channel %d\n", p->channel);
06761                   }
06762                   break;
06763 
06764                case AST_STATE_DOWN:       /*!< Channel is down and available */
06765                case AST_STATE_RESERVED:      /*!< Channel is down, but reserved */
06766                case AST_STATE_OFFHOOK:       /*!< Channel is off hook */
06767                case AST_STATE_BUSY:       /*!< Line is busy */
06768                case AST_STATE_DIALING_OFFHOOK:     /*!< Digits (or equivalent) have been dialed while offhook */
06769                case AST_STATE_PRERING:       /*!< Channel has detected an incoming call and is waiting for ring */
06770                default:
06771                   if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
06772                      ast_debug(1, "Ignoring Polarity switch on channel %d, state %d\n", p->channel, ast->_state);
06773                   }
06774                }
06775 
06776             } else {
06777                /* event is too soon after OffHook or Answer */
06778                switch (ast->_state) {
06779                case AST_STATE_DIALING:       /*!< Digits (or equivalent) have been dialed */
06780                case AST_STATE_RINGING:       /*!< Remote end is ringing */
06781                   if (p->answeronpolarityswitch) {
06782                      ast_debug(1, "Polarity switch detected but NOT answering (too close to OffHook event) on channel %d, state %d\n", p->channel, ast->_state);
06783                   }
06784                   break;
06785 
06786                case AST_STATE_UP:         /*!< Line is up */
06787                case AST_STATE_RING:       /*!< Line is ringing */
06788                   if (p->hanguponpolarityswitch) {
06789                      ast_debug(1, "Polarity switch detected but NOT hanging up (too close to Answer event) on channel %d, state %d\n", p->channel, ast->_state);
06790                   }
06791                   break;
06792 
06793                default: 
06794                   if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
06795                      ast_debug(1, "Polarity switch detected (too close to previous event) on channel %d, state %d\n", p->channel, ast->_state);
06796                   }
06797                }
06798             }
06799          }
06800 
06801          /* Added more log_debug information below to provide a better indication of what is going on */
06802          ast_debug(1, "Polarity Reversal event occured - DEBUG 2: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
06803          break;
06804       default:
06805          ast_debug(1, "Dunno what to do with event %d on channel %d\n", res, p->channel);
06806    }
06807    return &p->subs[idx].f;
06808 }
06809 
06810 static struct ast_frame *__dahdi_exception(struct ast_channel *ast)
06811 {
06812    struct dahdi_pvt *p = ast->tech_pvt;
06813    int res;
06814    int idx;
06815    struct ast_frame *f;
06816 
06817 
06818    idx = dahdi_get_index(ast, p, 1);
06819    if (idx < 0) {
06820       idx = SUB_REAL;
06821    }
06822 
06823    p->subs[idx].f.frametype = AST_FRAME_NULL;
06824    p->subs[idx].f.datalen = 0;
06825    p->subs[idx].f.samples = 0;
06826    p->subs[idx].f.mallocd = 0;
06827    p->subs[idx].f.offset = 0;
06828    p->subs[idx].f.subclass = 0;
06829    p->subs[idx].f.delivery = ast_tv(0,0);
06830    p->subs[idx].f.src = "dahdi_exception";
06831    p->subs[idx].f.data.ptr = NULL;
06832 
06833    if ((!p->owner) && (!(p->radio || (p->oprmode < 0)))) {
06834       /* If nobody owns us, absorb the event appropriately, otherwise
06835          we loop indefinitely.  This occurs when, during call waiting, the
06836          other end hangs up our channel so that it no longer exists, but we
06837          have neither FLASH'd nor ONHOOK'd to signify our desire to
06838          change to the other channel. */
06839       if (p->fake_event) {
06840          res = p->fake_event;
06841          p->fake_event = 0;
06842       } else
06843          res = dahdi_get_event(p->subs[SUB_REAL].dfd);
06844       /* Switch to real if there is one and this isn't something really silly... */
06845       if ((res != DAHDI_EVENT_RINGEROFF) && (res != DAHDI_EVENT_RINGERON) &&
06846          (res != DAHDI_EVENT_HOOKCOMPLETE)) {
06847          ast_debug(1, "Restoring owner of channel %d on event %d\n", p->channel, res);
06848          p->owner = p->subs[SUB_REAL].owner;
06849          if (p->owner && ast != p->owner) {
06850             /*
06851              * Could this even happen?
06852              * Possible deadlock because we do not have the real-call lock.
06853              */
06854             ast_log(LOG_WARNING, "Event %s on %s is not restored owner %s\n",
06855                event2str(res), ast->name, p->owner->name);
06856          }
06857          if (p->owner && ast_bridged_channel(p->owner))
06858             ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
06859          p->subs[SUB_REAL].needunhold = 1;
06860       }
06861       switch (res) {
06862       case DAHDI_EVENT_ONHOOK:
06863          dahdi_disable_ec(p);
06864          if (p->owner) {
06865             ast_verb(3, "Channel %s still has call, ringing phone\n", p->owner->name);
06866             dahdi_ring_phone(p);
06867             p->callwaitingrepeat = 0;
06868             p->cidcwexpire = 0;
06869          } else {
06870             ast_log(LOG_WARNING, "Absorbed %s, but nobody is left!?!?\n",
06871                event2str(res));
06872          }
06873          update_conf(p);
06874          break;
06875       case DAHDI_EVENT_RINGOFFHOOK:
06876          dahdi_enable_ec(p);
06877          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
06878          if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
06879             p->subs[SUB_REAL].needanswer = 1;
06880             p->dialing = 0;
06881          }
06882          break;
06883       case DAHDI_EVENT_HOOKCOMPLETE:
06884       case DAHDI_EVENT_RINGERON:
06885       case DAHDI_EVENT_RINGEROFF:
06886          /* Do nothing */
06887          break;
06888       case DAHDI_EVENT_WINKFLASH:
06889          p->flashtime = ast_tvnow();
06890          if (p->owner) {
06891             ast_verb(3, "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
06892             if (p->owner->_state != AST_STATE_UP) {
06893                /* Answer if necessary */
06894                p->subs[SUB_REAL].needanswer = 1;
06895                ast_setstate(p->owner, AST_STATE_UP);
06896             }
06897             p->callwaitingrepeat = 0;
06898             p->cidcwexpire = 0;
06899             if (ast_bridged_channel(p->owner))
06900                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
06901             p->subs[SUB_REAL].needunhold = 1;
06902          } else {
06903             ast_log(LOG_WARNING, "Absorbed %s, but nobody is left!?!?\n",
06904                event2str(res));
06905          }
06906          update_conf(p);
06907          break;
06908       default:
06909          ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
06910          break;
06911       }
06912       f = &p->subs[idx].f;
06913       return f;
06914    }
06915    if (!(p->radio || (p->oprmode < 0)))
06916       ast_debug(1, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
06917    /* If it's not us, return NULL immediately */
06918    if (ast != p->owner) {
06919       ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
06920       f = &p->subs[idx].f;
06921       return f;
06922    }
06923    f = dahdi_handle_event(ast);
06924    return f;
06925 }
06926 
06927 static struct ast_frame *dahdi_exception(struct ast_channel *ast)
06928 {
06929    struct dahdi_pvt *p = ast->tech_pvt;
06930    struct ast_frame *f;
06931    ast_mutex_lock(&p->lock);
06932    f = __dahdi_exception(ast);
06933    ast_mutex_unlock(&p->lock);
06934    return f;
06935 }
06936 
06937 static struct ast_frame *dahdi_read(struct ast_channel *ast)
06938 {
06939    struct dahdi_pvt *p = ast->tech_pvt;
06940    int res;
06941    int idx;
06942    void *readbuf;
06943    struct ast_frame *f;
06944 
06945    while (ast_mutex_trylock(&p->lock)) {
06946       CHANNEL_DEADLOCK_AVOIDANCE(ast);
06947    }
06948 
06949    idx = dahdi_get_index(ast, p, 0);
06950 
06951    /* Hang up if we don't really exist */
06952    if (idx < 0)   {
06953       ast_log(LOG_WARNING, "We don't exist?\n");
06954       ast_mutex_unlock(&p->lock);
06955       return NULL;
06956    }
06957 
06958    if ((p->radio || (p->oprmode < 0)) && p->inalarm) {
06959       ast_mutex_unlock(&p->lock);
06960       return NULL;
06961    }
06962 
06963    p->subs[idx].f.frametype = AST_FRAME_NULL;
06964    p->subs[idx].f.datalen = 0;
06965    p->subs[idx].f.samples = 0;
06966    p->subs[idx].f.mallocd = 0;
06967    p->subs[idx].f.offset = 0;
06968    p->subs[idx].f.subclass = 0;
06969    p->subs[idx].f.delivery = ast_tv(0,0);
06970    p->subs[idx].f.src = "dahdi_read";
06971    p->subs[idx].f.data.ptr = NULL;
06972 
06973    /* make sure it sends initial key state as first frame */
06974    if ((p->radio || (p->oprmode < 0)) && (!p->firstradio))
06975    {
06976       struct dahdi_params ps;
06977 
06978       memset(&ps, 0, sizeof(ps));
06979       ps.channo = p->channel;
06980       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
06981          ast_mutex_unlock(&p->lock);
06982          return NULL;
06983       }
06984       p->firstradio = 1;
06985       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
06986       if (ps.rxisoffhook)
06987       {
06988          p->subs[idx].f.subclass = AST_CONTROL_RADIO_KEY;
06989       }
06990       else
06991       {
06992          p->subs[idx].f.subclass = AST_CONTROL_RADIO_UNKEY;
06993       }
06994       ast_mutex_unlock(&p->lock);
06995       return &p->subs[idx].f;
06996    }
06997    if (p->ringt == 1) {
06998       ast_mutex_unlock(&p->lock);
06999       return NULL;
07000    }
07001    else if (p->ringt > 0)
07002       p->ringt--;
07003 
07004 #ifdef HAVE_OPENR2
07005    if (p->mfcr2) {
07006       openr2_chan_process_event(p->r2chan);
07007    }
07008 #endif
07009 
07010    if (p->subs[idx].needringing) {
07011       /* Send ringing frame if requested */
07012       p->subs[idx].needringing = 0;
07013       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07014       p->subs[idx].f.subclass = AST_CONTROL_RINGING;
07015       ast_setstate(ast, AST_STATE_RINGING);
07016       ast_mutex_unlock(&p->lock);
07017       return &p->subs[idx].f;
07018    }
07019 
07020    if (p->subs[idx].needbusy) {
07021       /* Send busy frame if requested */
07022       p->subs[idx].needbusy = 0;
07023       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07024       p->subs[idx].f.subclass = AST_CONTROL_BUSY;
07025       ast_mutex_unlock(&p->lock);
07026       return &p->subs[idx].f;
07027    }
07028 
07029    if (p->subs[idx].needcongestion) {
07030       /* Send congestion frame if requested */
07031       p->subs[idx].needcongestion = 0;
07032       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07033       p->subs[idx].f.subclass = AST_CONTROL_CONGESTION;
07034       ast_mutex_unlock(&p->lock);
07035       return &p->subs[idx].f;
07036    }
07037 
07038    if (p->subs[idx].needcallerid && !ast->cid.cid_tns) {
07039       ast_set_callerid(ast, S_OR(p->lastcid_num, NULL),
07040                      S_OR(p->lastcid_name, NULL),
07041                      S_OR(p->lastcid_num, NULL)
07042                      );
07043       p->subs[idx].needcallerid = 0;
07044    }
07045 
07046    if (p->subs[idx].needanswer) {
07047       /* Send answer frame if requested */
07048       p->subs[idx].needanswer = 0;
07049       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07050       p->subs[idx].f.subclass = AST_CONTROL_ANSWER;
07051       ast_mutex_unlock(&p->lock);
07052       return &p->subs[idx].f;
07053    }
07054 #ifdef HAVE_OPENR2
07055    if (p->mfcr2 && openr2_chan_get_read_enabled(p->r2chan)) {
07056       /* openr2 took care of reading and handling any event
07057         (needanswer, needbusy etc), if we continue we will read()
07058         twice, lets just return a null frame. This should only
07059         happen when openr2 is dialing out */
07060       ast_mutex_unlock(&p->lock);
07061       return &ast_null_frame;
07062    }
07063 #endif
07064 
07065    if (p->subs[idx].needflash) {
07066       /* Send answer frame if requested */
07067       p->subs[idx].needflash = 0;
07068       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07069       p->subs[idx].f.subclass = AST_CONTROL_FLASH;
07070       ast_mutex_unlock(&p->lock);
07071       return &p->subs[idx].f;
07072    }
07073 
07074    if (p->subs[idx].needhold) {
07075       /* Send answer frame if requested */
07076       p->subs[idx].needhold = 0;
07077       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07078       p->subs[idx].f.subclass = AST_CONTROL_HOLD;
07079       ast_mutex_unlock(&p->lock);
07080       ast_debug(1, "Sending hold on '%s'\n", ast->name);
07081       return &p->subs[idx].f;
07082    }
07083 
07084    if (p->subs[idx].needunhold) {
07085       /* Send answer frame if requested */
07086       p->subs[idx].needunhold = 0;
07087       p->subs[idx].f.frametype = AST_FRAME_CONTROL;
07088       p->subs[idx].f.subclass = AST_CONTROL_UNHOLD;
07089       ast_mutex_unlock(&p->lock);
07090       ast_debug(1, "Sending unhold on '%s'\n", ast->name);
07091       return &p->subs[idx].f;
07092    }
07093 
07094    if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
07095       if (!p->subs[idx].linear) {
07096          p->subs[idx].linear = 1;
07097          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
07098          if (res)
07099             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, idx);
07100       }
07101    } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
07102       (ast->rawreadformat == AST_FORMAT_ALAW)) {
07103       if (p->subs[idx].linear) {
07104          p->subs[idx].linear = 0;
07105          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
07106          if (res)
07107             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, idx);
07108       }
07109    } else {
07110       ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
07111       ast_mutex_unlock(&p->lock);
07112       return NULL;
07113    }
07114    readbuf = ((unsigned char *)p->subs[idx].buffer) + AST_FRIENDLY_OFFSET;
07115    CHECK_BLOCKING(ast);
07116    res = read(p->subs[idx].dfd, readbuf, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
07117    ast_clear_flag(ast, AST_FLAG_BLOCKING);
07118    /* Check for hangup */
07119    if (res < 0) {
07120       f = NULL;
07121       if (res == -1) {
07122          if (errno == EAGAIN) {
07123             /* Return "NULL" frame if there is nobody there */
07124             ast_mutex_unlock(&p->lock);
07125             return &p->subs[idx].f;
07126          } else if (errno == ELAST) {
07127             f = __dahdi_exception(ast);
07128          } else
07129             ast_log(LOG_WARNING, "dahdi_rec: %s\n", strerror(errno));
07130       }
07131       ast_mutex_unlock(&p->lock);
07132       return f;
07133    }
07134    if (res != (p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE)) {
07135       ast_debug(1, "Short read (%d/%d), must be an event...\n", res, p->subs[idx].linear ? READ_SIZE * 2 : READ_SIZE);
07136       f = __dahdi_exception(ast);
07137       ast_mutex_unlock(&p->lock);
07138       return f;
07139    }
07140    if (p->tdd) { /* if in TDD mode, see if we receive that */
07141       int c;
07142 
07143       c = tdd_feed(p->tdd,readbuf,READ_SIZE);
07144       if (c < 0) {
07145          ast_debug(1,"tdd_feed failed\n");
07146          ast_mutex_unlock(&p->lock);
07147          return NULL;
07148       }
07149       if (c) { /* if a char to return */
07150          p->subs[idx].f.subclass = 0;
07151          p->subs[idx].f.frametype = AST_FRAME_TEXT;
07152          p->subs[idx].f.mallocd = 0;
07153          p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
07154          p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET;
07155          p->subs[idx].f.datalen = 1;
07156          *((char *) p->subs[idx].f.data.ptr) = c;
07157          ast_mutex_unlock(&p->lock);
07158          return &p->subs[idx].f;
07159       }
07160    }
07161    /* Ensure the CW timer decrements only on a single subchannel */
07162    if (p->callwaitingrepeat && dahdi_get_index(ast, p, 1) == SUB_REAL) {
07163       p->callwaitingrepeat--;
07164    }
07165    if (p->cidcwexpire)
07166       p->cidcwexpire--;
07167    /* Repeat callwaiting */
07168    if (p->callwaitingrepeat == 1) {
07169       p->callwaitrings++;
07170       dahdi_callwait(ast);
07171    }
07172    /* Expire CID/CW */
07173    if (p->cidcwexpire == 1) {
07174       ast_verb(3, "CPE does not support Call Waiting Caller*ID.\n");
07175       restore_conference(p);
07176    }
07177    if (p->subs[idx].linear) {
07178       p->subs[idx].f.datalen = READ_SIZE * 2;
07179    } else
07180       p->subs[idx].f.datalen = READ_SIZE;
07181 
07182    /* Handle CallerID Transmission */
07183    if ((p->owner == ast) && p->cidspill &&((ast->_state == AST_STATE_UP) || (ast->rings == p->cidrings))) {
07184       send_callerid(p);
07185    }
07186 
07187    p->subs[idx].f.frametype = AST_FRAME_VOICE;
07188    p->subs[idx].f.subclass = ast->rawreadformat;
07189    p->subs[idx].f.samples = READ_SIZE;
07190    p->subs[idx].f.mallocd = 0;
07191    p->subs[idx].f.offset = AST_FRIENDLY_OFFSET;
07192    p->subs[idx].f.data.ptr = p->subs[idx].buffer + AST_FRIENDLY_OFFSET / sizeof(p->subs[idx].buffer[0]);
07193 #if 0
07194    ast_debug(1, "Read %d of voice on %s\n", p->subs[idx].f.datalen, ast->name);
07195 #endif
07196    if (p->dialing || /* Transmitting something */
07197       (idx && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
07198       ((idx == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
07199       ) {
07200       /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
07201          don't send anything */
07202       p->subs[idx].f.frametype = AST_FRAME_NULL;
07203       p->subs[idx].f.subclass = 0;
07204       p->subs[idx].f.samples = 0;
07205       p->subs[idx].f.mallocd = 0;
07206       p->subs[idx].f.offset = 0;
07207       p->subs[idx].f.data.ptr = NULL;
07208       p->subs[idx].f.datalen= 0;
07209    }
07210    if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect || p->callprogress || p->waitingfordt.tv_sec) && !idx) {
07211       /* Perform busy detection etc on the dahdi line */
07212       int mute;
07213 
07214       f = ast_dsp_process(ast, p->dsp, &p->subs[idx].f);
07215 
07216       /* Check if DSP code thinks we should be muting this frame and mute the conference if so */
07217       mute = ast_dsp_was_muted(p->dsp);
07218       if (p->muting != mute) {
07219          p->muting = mute;
07220          dahdi_confmute(p, mute);
07221       }
07222 
07223       if (f) {
07224          if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_BUSY)) {
07225             if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
07226                /* Treat this as a "hangup" instead of a "busy" on the assumption that
07227                   a busy */
07228                f = NULL;
07229             }
07230          } else if (f->frametype == AST_FRAME_DTMF) {
07231 #ifdef HAVE_PRI
07232             if (!p->proceeding && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) && p->pri &&
07233                ((!p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) ||
07234                (p->outgoing && (p->pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)))) {
07235                /* Don't accept in-band DTMF when in overlap dial mode */
07236                f->frametype = AST_FRAME_NULL;
07237                f->subclass = 0;
07238             }
07239 #endif
07240             /* DSP clears us of being pulse */
07241             p->pulsedial = 0;
07242          } else if (p->waitingfordt.tv_sec) {
07243             if (ast_tvdiff_ms(ast_tvnow(), p->waitingfordt) >= p->waitfordialtone ) {
07244                p->waitingfordt.tv_sec = 0;
07245                ast_log(LOG_WARNING, "Never saw dialtone on channel %d\n", p->channel);
07246                f=NULL;
07247             } else if (f->frametype == AST_FRAME_VOICE) {
07248                f->frametype = AST_FRAME_NULL;
07249                f->subclass = 0;
07250                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) {
07251                   p->waitingfordt.tv_sec = 0;
07252                   p->dsp_features &= ~DSP_FEATURE_WAITDIALTONE;
07253                   ast_dsp_set_features(p->dsp, p->dsp_features);
07254                   ast_log(LOG_DEBUG, "Got 10 samples of dialtone!\n");
07255                   if (!ast_strlen_zero(p->dop.dialstr)) { /* Dial deferred digits */
07256                      res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop);
07257                      if (res < 0) {
07258                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
07259                         p->dop.dialstr[0] = '\0';
07260                         ast_mutex_unlock(&p->lock);
07261                         return NULL;
07262                      } else {
07263                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
07264                         p->dialing = 1;
07265                         p->dop.dialstr[0] = '\0';
07266                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
07267                         ast_setstate(ast, AST_STATE_DIALING);
07268                      }
07269                   }
07270                }
07271             }
07272          }
07273       }
07274    } else
07275       f = &p->subs[idx].f;
07276 
07277    if (f && (f->frametype == AST_FRAME_DTMF))
07278       dahdi_handle_dtmfup(ast, idx, &f);
07279 
07280    /* If we have a fake_event, trigger exception to handle it */
07281    if (p->fake_event)
07282       ast_set_flag(ast, AST_FLAG_EXCEPTION);
07283 
07284    ast_mutex_unlock(&p->lock);
07285    return f;
07286 }
07287 
07288 static int my_dahdi_write(struct dahdi_pvt *p, unsigned char *buf, int len, int idx, int linear)
07289 {
07290    int sent=0;
07291    int size;
07292    int res;
07293    int fd;
07294    fd = p->subs[idx].dfd;
07295    while (len) {
07296       size = len;
07297       if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
07298          size = (linear ? READ_SIZE * 2 : READ_SIZE);
07299       res = write(fd, buf, size);
07300       if (res != size) {
07301          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
07302          return sent;
07303       }
07304       len -= size;
07305       buf += size;
07306    }
07307    return sent;
07308 }
07309 
07310 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame)
07311 {
07312    struct dahdi_pvt *p = ast->tech_pvt;
07313    int res;
07314    int idx;
07315    idx = dahdi_get_index(ast, p, 0);
07316    if (idx < 0) {
07317       ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
07318       return -1;
07319    }
07320 
07321 #if 0
07322 #ifdef HAVE_PRI
07323    ast_mutex_lock(&p->lock);
07324    if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
07325       if (p->pri->pri) {
07326          if (!pri_grab(p, p->pri)) {
07327                pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
07328                pri_rel(p->pri);
07329          } else
07330                ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07331       }
07332       p->proceeding=1;
07333    }
07334    ast_mutex_unlock(&p->lock);
07335 #endif
07336 #endif
07337    /* Write a frame of (presumably voice) data */
07338    if (frame->frametype != AST_FRAME_VOICE) {
07339       if (frame->frametype != AST_FRAME_IMAGE)
07340          ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
07341       return 0;
07342    }
07343    if ((frame->subclass != AST_FORMAT_SLINEAR) &&
07344       (frame->subclass != AST_FORMAT_ULAW) &&
07345       (frame->subclass != AST_FORMAT_ALAW)) {
07346       ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
07347       return -1;
07348    }
07349    if (p->dialing) {
07350       ast_debug(1, "Dropping frame since I'm still dialing on %s...\n",ast->name);
07351       return 0;
07352    }
07353    if (!p->owner) {
07354       ast_debug(1, "Dropping frame since there is no active owner on %s...\n",ast->name);
07355       return 0;
07356    }
07357    if (p->cidspill) {
07358       ast_debug(1, "Dropping frame since I've still got a callerid spill\n");
07359       return 0;
07360    }
07361    /* Return if it's not valid data */
07362    if (!frame->data.ptr || !frame->datalen)
07363       return 0;
07364 
07365    if (frame->subclass == AST_FORMAT_SLINEAR) {
07366       if (!p->subs[idx].linear) {
07367          p->subs[idx].linear = 1;
07368          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
07369          if (res)
07370             ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
07371       }
07372       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 1);
07373    } else {
07374       /* x-law already */
07375       if (p->subs[idx].linear) {
07376          p->subs[idx].linear = 0;
07377          res = dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
07378          if (res)
07379             ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
07380       }
07381       res = my_dahdi_write(p, (unsigned char *)frame->data.ptr, frame->datalen, idx, 0);
07382    }
07383    if (res < 0) {
07384       ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
07385       return -1;
07386    }
07387    return 0;
07388 }
07389 
07390 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen)
07391 {
07392    struct dahdi_pvt *p = chan->tech_pvt;
07393    int res=-1;
07394    int idx;
07395    int func = DAHDI_FLASH;
07396    ast_mutex_lock(&p->lock);
07397    idx = dahdi_get_index(chan, p, 0);
07398    ast_debug(1, "Requested indication %d on channel %s\n", condition, chan->name);
07399 #ifdef HAVE_OPENR2
07400    if (p->mfcr2 && !p->mfcr2_call_accepted) {
07401       ast_mutex_unlock(&p->lock);
07402       /* if this is an R2 call and the call is not yet accepted, we don't want the
07403          tone indications to mess up with the MF tones */
07404       return 0;
07405    }
07406 #endif
07407    if (idx == SUB_REAL) {
07408       switch (condition) {
07409       case AST_CONTROL_BUSY:
07410 #ifdef HAVE_PRI
07411          if (p->priindication_oob && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))) {
07412             chan->hangupcause = AST_CAUSE_USER_BUSY;
07413             chan->_softhangup |= AST_SOFTHANGUP_DEV;
07414             res = 0;
07415          } else if (!p->progress &&
07416                ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))
07417                && p->pri && !p->outgoing) {
07418             if (p->pri->pri) {
07419                if (!pri_grab(p, p->pri)) {
07420 #ifdef HAVE_PRI_PROG_W_CAUSE
07421                   pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, PRI_CAUSE_USER_BUSY); /* cause = 17 */
07422 #else
07423                   pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07424 #endif
07425                   pri_rel(p->pri);
07426                }
07427                else
07428                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07429             }
07430             p->progress = 1;
07431             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_BUSY);
07432          } else
07433 #endif
07434             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_BUSY);
07435          break;
07436       case AST_CONTROL_RINGING:
07437 #ifdef HAVE_PRI
07438          if ((!p->alerting) && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))
07439                && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
07440             if (p->pri->pri) {
07441                if (!pri_grab(p, p->pri)) {
07442                   pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
07443                   pri_rel(p->pri);
07444                }
07445                else
07446                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07447             }
07448             p->alerting = 1;
07449          }
07450 
07451 #endif
07452 #ifdef HAVE_SS7
07453          if ((!p->alerting) && (p->sig == SIG_SS7) && p->ss7 && !p->outgoing && (chan->_state != AST_STATE_UP)) {
07454             if (p->ss7->ss7) {
07455                ss7_grab(p, p->ss7);
07456 
07457                if ((isup_far(p->ss7->ss7, p->ss7call)) != -1)
07458                   p->rlt = 1;
07459                if (p->rlt != 1) /* No need to send CPG if call will be RELEASE */
07460                   isup_cpg(p->ss7->ss7, p->ss7call, CPG_EVENT_ALERTING);
07461                p->alerting = 1;
07462                ss7_rel(p->ss7);
07463             }
07464          }
07465 #endif
07466 
07467          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_RINGTONE);
07468 
07469          if (chan->_state != AST_STATE_UP) {
07470             if ((chan->_state != AST_STATE_RING) ||
07471                ((p->sig != SIG_FXSKS) &&
07472              (p->sig != SIG_FXSLS) &&
07473              (p->sig != SIG_FXSGS)))
07474             ast_setstate(chan, AST_STATE_RINGING);
07475          }
07476          break;
07477       case AST_CONTROL_PROCEEDING:
07478          ast_debug(1,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
07479 #ifdef HAVE_PRI
07480          if (!p->proceeding && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))
07481                && p->pri && !p->outgoing) {
07482             if (p->pri->pri) {
07483                if (!pri_grab(p, p->pri)) {
07484                   pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
07485                   pri_rel(p->pri);
07486                }
07487                else
07488                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07489             }
07490             p->proceeding = 1;
07491             p->dialing = 0;
07492          }
07493 #endif
07494 #ifdef HAVE_SS7
07495          /* This IF sends the FAR for an answered ALEG call */
07496          if (chan->_state == AST_STATE_UP && (p->rlt != 1) && (p->sig == SIG_SS7)){
07497             if ((isup_far(p->ss7->ss7, p->ss7call)) != -1)
07498                p->rlt = 1;
07499          }
07500 
07501          if (!p->proceeding && p->sig == SIG_SS7 && p->ss7 && !p->outgoing) {
07502             if (p->ss7->ss7) {
07503                ss7_grab(p, p->ss7);
07504                isup_acm(p->ss7->ss7, p->ss7call);
07505                p->proceeding = 1;
07506                ss7_rel(p->ss7);
07507 
07508             }
07509          }
07510 #endif
07511          /* don't continue in ast_indicate */
07512          res = 0;
07513          break;
07514       case AST_CONTROL_PROGRESS:
07515          ast_debug(1,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
07516 #ifdef HAVE_PRI
07517          p->digital = 0;   /* Digital-only calls isn't allows any inband progress messages */
07518          if (!p->progress && !p->alerting && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))
07519                && p->pri && !p->outgoing) {
07520             if (p->pri->pri) {
07521                if (!pri_grab(p, p->pri)) {
07522 #ifdef HAVE_PRI_PROG_W_CAUSE
07523                   pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, -1);  /* no cause at all */
07524 #else
07525                   pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07526 #endif
07527                   pri_rel(p->pri);
07528                }
07529                else
07530                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07531             }
07532             p->progress = 1;
07533          }
07534 #endif
07535 #ifdef HAVE_SS7
07536          if (!p->progress && p->sig==SIG_SS7 && p->ss7 && !p->outgoing) {
07537             if (p->ss7->ss7) {
07538                ss7_grab(p, p->ss7);
07539                isup_cpg(p->ss7->ss7, p->ss7call, CPG_EVENT_INBANDINFO);
07540                p->progress = 1;
07541                ss7_rel(p->ss7);
07542                /* enable echo canceler here on SS7 calls */
07543                dahdi_enable_ec(p);
07544 
07545             }
07546          }
07547 #endif
07548          /* don't continue in ast_indicate */
07549          res = 0;
07550          break;
07551       case AST_CONTROL_CONGESTION:
07552          chan->hangupcause = AST_CAUSE_CONGESTION;
07553 #ifdef HAVE_PRI
07554          if (p->priindication_oob && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))) {
07555             chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
07556             chan->_softhangup |= AST_SOFTHANGUP_DEV;
07557             res = 0;
07558          } else if (!p->progress && ((p->sig == SIG_PRI) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP))
07559                && p->pri && !p->outgoing) {
07560             if (p->pri) {
07561                if (!pri_grab(p, p->pri)) {
07562 #ifdef HAVE_PRI_PROG_W_CAUSE
07563                   pri_progress_with_cause(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1, PRI_CAUSE_SWITCH_CONGESTION); /* cause = 42 */
07564 #else
07565                   pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
07566 #endif
07567                   pri_rel(p->pri);
07568                } else
07569                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07570             }
07571             p->progress = 1;
07572             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
07573          } else
07574 #endif
07575             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
07576          break;
07577       case AST_CONTROL_HOLD:
07578 #ifdef HAVE_PRI
07579          if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
07580             if (!pri_grab(p, p->pri)) {
07581                res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
07582                pri_rel(p->pri);
07583             } else
07584                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07585          } else
07586 #endif
07587             ast_moh_start(chan, data, p->mohinterpret);
07588          break;
07589       case AST_CONTROL_UNHOLD:
07590 #ifdef HAVE_PRI
07591          if (p->pri && !strcasecmp(p->mohinterpret, "passthrough")) {
07592             if (!pri_grab(p, p->pri)) {
07593                res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
07594                pri_rel(p->pri);
07595             } else
07596                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07597          } else
07598 #endif
07599             ast_moh_stop(chan);
07600          break;
07601       case AST_CONTROL_RADIO_KEY:
07602          if (p->radio)
07603             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_OFFHOOK);
07604          res = 0;
07605          break;
07606       case AST_CONTROL_RADIO_UNKEY:
07607          if (p->radio)
07608             res = dahdi_set_hook(p->subs[idx].dfd, DAHDI_RINGOFF);
07609          res = 0;
07610          break;
07611       case AST_CONTROL_FLASH:
07612          /* flash hookswitch */
07613          if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
07614             /* Clear out the dial buffer */
07615             p->dop.dialstr[0] = '\0';
07616             if ((ioctl(p->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
07617                ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
07618                   chan->name, strerror(errno));
07619             } else
07620                res = 0;
07621          } else
07622             res = 0;
07623          break;
07624       case AST_CONTROL_SRCUPDATE:
07625          res = 0;
07626          break;
07627       case -1:
07628          res = tone_zone_play_tone(p->subs[idx].dfd, -1);
07629          break;
07630       }
07631    } else
07632       res = 0;
07633    ast_mutex_unlock(&p->lock);
07634    return res;
07635 }
07636 
07637 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, int transfercapability)
07638 {
07639    struct ast_channel *tmp;
07640    int deflaw;
07641    int res;
07642    int x,y;
07643    int features;
07644    struct ast_str *chan_name;
07645    struct ast_variable *v;
07646    struct dahdi_params ps;
07647    if (i->subs[idx].owner) {
07648       ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[idx]);
07649       return NULL;
07650    }
07651    y = 1;
07652    chan_name = ast_str_alloca(32);
07653    do {
07654 #ifdef HAVE_PRI
07655       if (i->bearer || (i->pri && (i->sig == SIG_FXSKS)))
07656          ast_str_set(&chan_name, 0, "%d:%d-%d", i->pri->trunkgroup, i->channel, y);
07657       else
07658 #endif
07659       if (i->channel == CHAN_PSEUDO)
07660          ast_str_set(&chan_name, 0, "pseudo-%ld", ast_random());
07661       else
07662          ast_str_set(&chan_name, 0, "%d-%d", i->channel, y);
07663       for (x = 0; x < 3; x++) {
07664          if ((idx != x) && i->subs[x].owner && !strcasecmp(ast_str_buffer(chan_name), i->subs[x].owner->name + 6))
07665             break;
07666       }
07667       y++;
07668    } while (x < 3);
07669    tmp = ast_channel_alloc(0, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "DAHDI/%s", ast_str_buffer(chan_name));
07670    if (!tmp)
07671       return NULL;
07672    tmp->tech = &dahdi_tech;
07673    memset(&ps, 0, sizeof(ps));
07674    ps.channo = i->channel;
07675    res = ioctl(i->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps);
07676    if (res) {
07677       ast_log(LOG_WARNING, "Unable to get parameters, assuming MULAW: %s\n", strerror(errno));
07678       ps.curlaw = DAHDI_LAW_MULAW;
07679    }
07680    if (ps.curlaw == DAHDI_LAW_ALAW)
07681       deflaw = AST_FORMAT_ALAW;
07682    else
07683       deflaw = AST_FORMAT_ULAW;
07684    if (law) {
07685       if (law == DAHDI_LAW_ALAW)
07686          deflaw = AST_FORMAT_ALAW;
07687       else
07688          deflaw = AST_FORMAT_ULAW;
07689    }
07690    ast_channel_set_fd(tmp, 0, i->subs[idx].dfd);
07691    tmp->nativeformats = deflaw;
07692    /* Start out assuming ulaw since it's smaller :) */
07693    tmp->rawreadformat = deflaw;
07694    tmp->readformat = deflaw;
07695    tmp->rawwriteformat = deflaw;
07696    tmp->writeformat = deflaw;
07697    i->subs[idx].linear = 0;
07698    dahdi_setlinear(i->subs[idx].dfd, i->subs[idx].linear);
07699    features = 0;
07700    if (idx == SUB_REAL) {
07701       if (i->busydetect && CANBUSYDETECT(i))
07702          features |= DSP_FEATURE_BUSY_DETECT;
07703       if ((i->callprogress & CALLPROGRESS_PROGRESS) && CANPROGRESSDETECT(i))
07704          features |= DSP_FEATURE_CALL_PROGRESS;
07705       if ((i->waitfordialtone) && CANPROGRESSDETECT(i))
07706          features |= DSP_FEATURE_WAITDIALTONE;
07707       if ((!i->outgoing && (i->callprogress & CALLPROGRESS_FAX_INCOMING)) ||
07708          (i->outgoing && (i->callprogress & CALLPROGRESS_FAX_OUTGOING))) {
07709          features |= DSP_FEATURE_FAX_DETECT;
07710       }
07711       x = DAHDI_TONEDETECT_ON | DAHDI_TONEDETECT_MUTE;
07712       if (ioctl(i->subs[idx].dfd, DAHDI_TONEDETECT, &x)) {
07713          i->hardwaredtmf = 0;
07714          features |= DSP_FEATURE_DIGIT_DETECT;
07715       } else if (NEED_MFDETECT(i)) {
07716          i->hardwaredtmf = 1;
07717          features |= DSP_FEATURE_DIGIT_DETECT;
07718       }
07719    }
07720    if (features) {
07721       if (i->dsp) {
07722          ast_debug(1, "Already have a dsp on %s?\n", tmp->name);
07723       } else {
07724          if (i->channel != CHAN_PSEUDO)
07725             i->dsp = ast_dsp_new();
07726          else
07727             i->dsp = NULL;
07728          if (i->dsp) {
07729             i->dsp_features = features;
07730 #if defined(HAVE_PRI) || defined(HAVE_SS7)
07731             /* We cannot do progress detection until receives PROGRESS message */
07732             if (i->outgoing && ((i->sig == SIG_PRI) || (i->sig == SIG_BRI) || (i->sig == SIG_BRI_PTMP) || (i->sig == SIG_SS7))) {
07733                /* Remember requested DSP features, don't treat
07734                   talking as ANSWER */
07735                i->dsp_features = features & ~DSP_PROGRESS_TALK;
07736                features = 0;
07737             }
07738 #endif
07739             ast_dsp_set_features(i->dsp, features);
07740             ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
07741             if (!ast_strlen_zero(progzone))
07742                ast_dsp_set_call_progress_zone(i->dsp, progzone);
07743             if (i->busydetect && CANBUSYDETECT(i)) {
07744                ast_dsp_set_busy_count(i->dsp, i->busycount);
07745                ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
07746             }
07747          }
07748       }
07749    }
07750 
07751    if (state == AST_STATE_RING)
07752       tmp->rings = 1;
07753    tmp->tech_pvt = i;
07754    if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
07755       /* Only FXO signalled stuff can be picked up */
07756       tmp->callgroup = i->callgroup;
07757       tmp->pickupgroup = i->pickupgroup;
07758    }
07759    if (!ast_strlen_zero(i->parkinglot))
07760       ast_string_field_set(tmp, parkinglot, i->parkinglot);
07761    if (!ast_strlen_zero(i->language))
07762       ast_string_field_set(tmp, language, i->language);
07763    if (!i->owner)
07764       i->owner = tmp;
07765    if (!ast_strlen_zero(i->accountcode))
07766       ast_string_field_set(tmp, accountcode, i->accountcode);
07767    if (i->amaflags)
07768       tmp->amaflags = i->amaflags;
07769    i->subs[idx].owner = tmp;
07770    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07771    ast_string_field_set(tmp, call_forward, i->call_forward);
07772    /* If we've been told "no ADSI" then enforce it */
07773    if (!i->adsi)
07774       tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07775    if (!ast_strlen_zero(i->exten))
07776       ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
07777    if (!ast_strlen_zero(i->rdnis))
07778       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
07779    if (!ast_strlen_zero(i->dnid))
07780       tmp->cid.cid_dnid = ast_strdup(i->dnid);
07781 
07782    /* Don't use ast_set_callerid() here because it will
07783     * generate a needless NewCallerID event */
07784 #ifdef PRI_ANI
07785    if (!ast_strlen_zero(i->cid_ani))
07786       tmp->cid.cid_ani = ast_strdup(i->cid_ani);
07787    else
07788       tmp->cid.cid_ani = ast_strdup(i->cid_num);
07789 #else
07790    tmp->cid.cid_ani = ast_strdup(i->cid_num);
07791 #endif
07792    tmp->cid.cid_pres = i->callingpres;
07793    tmp->cid.cid_ton = i->cid_ton;
07794    tmp->cid.cid_ani2 = i->cid_ani2;
07795 #if defined(HAVE_PRI) || defined(HAVE_SS7)
07796    tmp->transfercapability = transfercapability;
07797    pbx_builtin_setvar_helper(tmp, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
07798    if (transfercapability & AST_TRANS_CAP_DIGITAL)
07799       i->digital = 1;
07800    /* Assume calls are not idle calls unless we're told differently */
07801    i->isidlecall = 0;
07802    i->alreadyhungup = 0;
07803 #endif
07804    /* clear the fake event in case we posted one before we had ast_channel */
07805    i->fake_event = 0;
07806    /* Assure there is no confmute on this channel */
07807    dahdi_confmute(i, 0);
07808    i->muting = 0;
07809    /* Configure the new channel jb */
07810    ast_jb_configure(tmp, &global_jbconf);
07811 
07812    ast_devstate_changed_literal(ast_state_chan2dev(state), tmp->name);
07813 
07814    for (v = i->vars ; v ; v = v->next)
07815       pbx_builtin_setvar_helper(tmp, v->name, v->value);
07816 
07817    if (startpbx) {
07818 #ifdef HAVE_OPENR2
07819       if (i->mfcr2call) {
07820          pbx_builtin_setvar_helper(tmp, "MFCR2_CATEGORY", openr2_proto_get_category_string(i->mfcr2_recvd_category));
07821       }
07822 #endif
07823       if (ast_pbx_start(tmp)) {
07824          ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
07825          ast_hangup(tmp);
07826          i->owner = NULL;
07827          return NULL;
07828       }
07829    }
07830 
07831    ast_module_ref(ast_module_info->self);
07832    return tmp;
07833 }
07834 
07835 
07836 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
07837 {
07838    char c;
07839 
07840    *str = 0; /* start with empty output buffer */
07841    for (;;)
07842    {
07843       /* Wait for the first digit (up to specified ms). */
07844       c = ast_waitfordigit(chan, ms);
07845       /* if timeout, hangup or error, return as such */
07846       if (c < 1)
07847          return c;
07848       *str++ = c;
07849       *str = 0;
07850       if (strchr(term, c))
07851          return 1;
07852    }
07853 }
07854 
07855 static int dahdi_wink(struct dahdi_pvt *p, int idx)
07856 {
07857    int j;
07858    dahdi_set_hook(p->subs[idx].dfd, DAHDI_WINK);
07859    for (;;)
07860    {
07861       /* set bits of interest */
07862       j = DAHDI_IOMUX_SIGEVENT;
07863       /* wait for some happening */
07864       if (ioctl(p->subs[idx].dfd,DAHDI_IOMUX,&j) == -1) return(-1);
07865       /* exit loop if we have it */
07866       if (j & DAHDI_IOMUX_SIGEVENT) break;
07867    }
07868    /* get the event info */
07869    if (ioctl(p->subs[idx].dfd,DAHDI_GETEVENT,&j) == -1) return(-1);
07870    return 0;
07871 }
07872 
07873 /*! \brief enable or disable the chan_dahdi Do-Not-Disturb mode for a DAHDI channel
07874  * \param dahdichan "Physical" DAHDI channel (e.g: DAHDI/5)
07875  * \param on 1 to enable, 0 to disable
07876  *
07877  * chan_dahdi has a DND (Do Not Disturb) mode for each dahdichan (physical
07878  * DAHDI channel). Use this to enable or disable it.
07879  *
07880  * \bug the use of the word "channel" for those dahdichans is really confusing.
07881  */
07882 static void dahdi_dnd(struct dahdi_pvt *dahdichan, int on)
07883 {
07884    /* Do not disturb */
07885    dahdichan->dnd = on;
07886    ast_verb(3, "%s DND on channel %d\n",
07887          on? "Enabled" : "Disabled",
07888          dahdichan->channel);
07889    manager_event(EVENT_FLAG_SYSTEM, "DNDState",
07890          "Channel: DAHDI/%d\r\n"
07891          "Status: %s\r\n", dahdichan->channel,
07892          on? "enabled" : "disabled");
07893 }
07894 
07895 static void *ss_thread(void *data)
07896 {
07897    struct ast_channel *chan = data;
07898    struct dahdi_pvt *p = chan->tech_pvt;
07899    char exten[AST_MAX_EXTENSION] = "";
07900    char exten2[AST_MAX_EXTENSION] = "";
07901    unsigned char buf[256];
07902    char dtmfcid[300];
07903    char dtmfbuf[300];
07904    struct callerid_state *cs = NULL;
07905    char *name = NULL, *number = NULL;
07906    int distMatches;
07907    int curRingData[3];
07908    int receivedRingT;
07909    int counter1;
07910    int counter;
07911    int samples = 0;
07912    struct ast_smdi_md_message *smdi_msg = NULL;
07913    int flags = 0;
07914    int i;
07915    int timeout;
07916    int getforward = 0;
07917    char *s1, *s2;
07918    int len = 0;
07919    int res;
07920    int idx;
07921 
07922    ast_mutex_lock(&ss_thread_lock);
07923    ss_thread_count++;
07924    ast_mutex_unlock(&ss_thread_lock);
07925    /* in the bizarre case where the channel has become a zombie before we
07926       even get started here, abort safely
07927    */
07928    if (!p) {
07929       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
07930       ast_hangup(chan);
07931       goto quit;
07932    }
07933    ast_verb(3, "Starting simple switch on '%s'\n", chan->name);
07934    idx = dahdi_get_index(chan, p, 0);
07935    if (idx < 0) {
07936       ast_hangup(chan);
07937       goto quit;
07938    }
07939    if (p->dsp)
07940       ast_dsp_digitreset(p->dsp);
07941    switch (p->sig) {
07942 #ifdef HAVE_PRI
07943    case SIG_PRI:
07944    case SIG_BRI:
07945    case SIG_BRI_PTMP:
07946       /* Now loop looking for an extension */
07947       ast_copy_string(exten, p->exten, sizeof(exten));
07948       len = strlen(exten);
07949       res = 0;
07950       while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
07951          if (len && !ast_ignore_pattern(chan->context, exten))
07952             tone_zone_play_tone(p->subs[idx].dfd, -1);
07953          else
07954             tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
07955          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
07956             timeout = matchdigittimeout;
07957          else
07958             timeout = gendigittimeout;
07959          res = ast_waitfordigit(chan, timeout);
07960          if (res < 0) {
07961             ast_debug(1, "waitfordigit returned < 0...\n");
07962             ast_hangup(chan);
07963             goto quit;
07964          } else if (res) {
07965             exten[len++] = res;
07966             exten[len] = '\0';
07967          } else
07968             break;
07969       }
07970       /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
07971       if (ast_strlen_zero(exten)) {
07972          ast_verb(3, "Going to extension s|1 because of empty extension received on overlap call\n");
07973          exten[0] = 's';
07974          exten[1] = '\0';
07975       }
07976       tone_zone_play_tone(p->subs[idx].dfd, -1);
07977       if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
07978          /* Start the real PBX */
07979          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
07980          if (p->dsp) {
07981             ast_dsp_digitreset(p->dsp);
07982          }
07983          if (p->pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) {
07984             ast_mutex_lock(&p->lock);
07985             if (p->pri->pri) {      
07986                if (!pri_grab(p, p->pri)) {
07987                   pri_proceeding(p->pri->pri, p->call, PVT_TO_CHANNEL(p), 0);
07988                   p->proceeding = 1;
07989                   pri_rel(p->pri);
07990                } else {
07991                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
07992                }
07993             }
07994             ast_mutex_unlock(&p->lock);
07995          }
07996          dahdi_enable_ec(p);
07997          ast_setstate(chan, AST_STATE_RING);
07998          res = ast_pbx_run(chan);
07999          if (res) {
08000             ast_log(LOG_WARNING, "PBX exited non-zero!\n");
08001          }
08002       } else {
08003          ast_debug(1, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
08004          chan->hangupcause = AST_CAUSE_UNALLOCATED;
08005          ast_hangup(chan);
08006          p->exten[0] = '\0';
08007          /* Since we send release complete here, we won't get one */
08008          p->call = NULL;
08009       }
08010       goto quit;
08011       break;
08012 #endif
08013    case SIG_FEATD:
08014    case SIG_FEATDMF:
08015    case SIG_FEATDMF_TA:
08016    case SIG_E911:
08017    case SIG_FGC_CAMAMF:
08018    case SIG_FEATB:
08019    case SIG_EMWINK:
08020    case SIG_SF_FEATD:
08021    case SIG_SF_FEATDMF:
08022    case SIG_SF_FEATB:
08023    case SIG_SFWINK:
08024       if (dahdi_wink(p, idx))
08025          goto quit;
08026       /* Fall through */
08027    case SIG_EM:
08028    case SIG_EM_E1:
08029    case SIG_SF:
08030    case SIG_FGC_CAMA:
08031       res = tone_zone_play_tone(p->subs[idx].dfd, -1);
08032       if (p->dsp)
08033          ast_dsp_digitreset(p->dsp);
08034       /* set digit mode appropriately */
08035       if (p->dsp) {
08036          if (NEED_MFDETECT(p))
08037             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
08038          else
08039             ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
08040       }
08041       memset(dtmfbuf, 0, sizeof(dtmfbuf));
08042       /* Wait for the first digit only if immediate=no */
08043       if (!p->immediate)
08044          /* Wait for the first digit (up to 5 seconds). */
08045          res = ast_waitfordigit(chan, 5000);
08046       else
08047          res = 0;
08048       if (res > 0) {
08049          /* save first char */
08050          dtmfbuf[0] = res;
08051          switch (p->sig) {
08052          case SIG_FEATD:
08053          case SIG_SF_FEATD:
08054             res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
08055             if (res > 0)
08056                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
08057             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
08058             break;
08059          case SIG_FEATDMF_TA:
08060             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
08061             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
08062             if (dahdi_wink(p, idx)) goto quit;
08063             dtmfbuf[0] = 0;
08064             /* Wait for the first digit (up to 5 seconds). */
08065             res = ast_waitfordigit(chan, 5000);
08066             if (res <= 0) break;
08067             dtmfbuf[0] = res;
08068             /* fall through intentionally */
08069          case SIG_FEATDMF:
08070          case SIG_E911:
08071          case SIG_FGC_CAMAMF:
08072          case SIG_SF_FEATDMF:
08073             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
08074             /* if international caca, do it again to get real ANO */
08075             if ((p->sig == SIG_FEATDMF) && (dtmfbuf[1] != '0') && (strlen(dtmfbuf) != 14))
08076             {
08077                if (dahdi_wink(p, idx)) goto quit;
08078                dtmfbuf[0] = 0;
08079                /* Wait for the first digit (up to 5 seconds). */
08080                res = ast_waitfordigit(chan, 5000);
08081                if (res <= 0) break;
08082                dtmfbuf[0] = res;
08083                res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
08084             }
08085             if (res > 0) {
08086                /* if E911, take off hook */
08087                if (p->sig == SIG_E911)
08088                   dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08089                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
08090             }
08091             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
08092             break;
08093          case SIG_FEATB:
08094          case SIG_SF_FEATB:
08095             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
08096             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
08097             break;
08098          case SIG_EMWINK:
08099             /* if we received a '*', we are actually receiving Feature Group D
08100                dial syntax, so use that mode; otherwise, fall through to normal
08101                mode
08102             */
08103             if (res == '*') {
08104                res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
08105                if (res > 0)
08106                   res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
08107                if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
08108                break;
08109             }
08110          default:
08111             /* If we got the first digit, get the rest */
08112             len = 1;
08113             dtmfbuf[len] = '\0';
08114             while ((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
08115                if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
08116                   timeout = matchdigittimeout;
08117                } else {
08118                   timeout = gendigittimeout;
08119                }
08120                res = ast_waitfordigit(chan, timeout);
08121                if (res < 0) {
08122                   ast_debug(1, "waitfordigit returned < 0...\n");
08123                   ast_hangup(chan);
08124                   goto quit;
08125                } else if (res) {
08126                   dtmfbuf[len++] = res;
08127                   dtmfbuf[len] = '\0';
08128                } else {
08129                   break;
08130                }
08131             }
08132             break;
08133          }
08134       }
08135       if (res == -1) {
08136          ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
08137          ast_hangup(chan);
08138          goto quit;
08139       } else if (res < 0) {
08140          ast_debug(1, "Got hung up before digits finished\n");
08141          ast_hangup(chan);
08142          goto quit;
08143       }
08144 
08145       if (p->sig == SIG_FGC_CAMA) {
08146          char anibuf[100];
08147 
08148          if (ast_safe_sleep(chan,1000) == -1) {
08149             ast_hangup(chan);
08150             goto quit;
08151          }
08152          dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08153          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
08154          res = my_getsigstr(chan, anibuf, "#", 10000);
08155          if ((res > 0) && (strlen(anibuf) > 2)) {
08156             if (anibuf[strlen(anibuf) - 1] == '#')
08157                anibuf[strlen(anibuf) - 1] = 0;
08158             ast_set_callerid(chan, anibuf + 2, NULL, anibuf + 2);
08159          }
08160          ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
08161       }
08162 
08163       ast_copy_string(exten, dtmfbuf, sizeof(exten));
08164       if (ast_strlen_zero(exten))
08165          ast_copy_string(exten, "s", sizeof(exten));
08166       if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
08167          /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
08168          if (exten[0] == '*') {
08169             char *stringp=NULL;
08170             ast_copy_string(exten2, exten, sizeof(exten2));
08171             /* Parse out extension and callerid */
08172             stringp=exten2 +1;
08173             s1 = strsep(&stringp, "*");
08174             s2 = strsep(&stringp, "*");
08175             if (s2) {
08176                if (!ast_strlen_zero(p->cid_num))
08177                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
08178                else
08179                   ast_set_callerid(chan, s1, NULL, s1);
08180                ast_copy_string(exten, s2, sizeof(exten));
08181             } else
08182                ast_copy_string(exten, s1, sizeof(exten));
08183          } else if (p->sig == SIG_FEATD)
08184             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
08185       }
08186       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
08187          if (exten[0] == '*') {
08188             char *stringp=NULL;
08189             ast_copy_string(exten2, exten, sizeof(exten2));
08190             /* Parse out extension and callerid */
08191             stringp=exten2 +1;
08192             s1 = strsep(&stringp, "#");
08193             s2 = strsep(&stringp, "#");
08194             if (s2) {
08195                if (!ast_strlen_zero(p->cid_num))
08196                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
08197                else
08198                   if (*(s1 + 2))
08199                      ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
08200                ast_copy_string(exten, s2 + 1, sizeof(exten));
08201             } else
08202                ast_copy_string(exten, s1 + 2, sizeof(exten));
08203          } else
08204             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
08205       }
08206       if ((p->sig == SIG_E911) || (p->sig == SIG_FGC_CAMAMF)) {
08207          if (exten[0] == '*') {
08208             char *stringp=NULL;
08209             ast_copy_string(exten2, exten, sizeof(exten2));
08210             /* Parse out extension and callerid */
08211             stringp=exten2 +1;
08212             s1 = strsep(&stringp, "#");
08213             s2 = strsep(&stringp, "#");
08214             if (s2 && (*(s2 + 1) == '0')) {
08215                if (*(s2 + 2))
08216                   ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
08217             }
08218             if (s1)  ast_copy_string(exten, s1, sizeof(exten));
08219             else ast_copy_string(exten, "911", sizeof(exten));
08220          } else
08221             ast_log(LOG_WARNING, "Got a non-E911/FGC CAMA input on channel %d.  Assuming E&M Wink instead\n", p->channel);
08222       }
08223       if (p->sig == SIG_FEATB) {
08224          if (exten[0] == '*') {
08225             char *stringp=NULL;
08226             ast_copy_string(exten2, exten, sizeof(exten2));
08227             /* Parse out extension and callerid */
08228             stringp=exten2 +1;
08229             s1 = strsep(&stringp, "#");
08230             ast_copy_string(exten, exten2 + 1, sizeof(exten));
08231          } else
08232             ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
08233       }
08234       if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATDMF_TA)) {
08235          dahdi_wink(p, idx);
08236          /* some switches require a minimum guard time between
08237             the last FGD wink and something that answers
08238             immediately. This ensures it */
08239          if (ast_safe_sleep(chan,100)) goto quit;
08240       }
08241       dahdi_enable_ec(p);
08242       if (NEED_MFDETECT(p)) {
08243          if (p->dsp) {
08244             if (!p->hardwaredtmf)
08245                ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
08246             else {
08247                ast_dsp_free(p->dsp);
08248                p->dsp = NULL;
08249             }
08250          }
08251       }
08252 
08253       if (ast_exists_extension(chan, chan->context, exten, 1, chan->cid.cid_num)) {
08254          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
08255          if (p->dsp) ast_dsp_digitreset(p->dsp);
08256          res = ast_pbx_run(chan);
08257          if (res) {
08258             ast_log(LOG_WARNING, "PBX exited non-zero\n");
08259             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
08260          }
08261          goto quit;
08262       } else {
08263          ast_verb(2, "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
08264          sleep(2);
08265          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_INFO);
08266          if (res < 0)
08267             ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
08268          else
08269             sleep(1);
08270          res = ast_streamfile(chan, "ss-noservice", chan->language);
08271          if (res >= 0)
08272             ast_waitstream(chan, "");
08273          res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
08274          ast_hangup(chan);
08275          goto quit;
08276       }
08277       break;
08278    case SIG_FXOLS:
08279    case SIG_FXOGS:
08280    case SIG_FXOKS:
08281       /* Read the first digit */
08282       timeout = firstdigittimeout;
08283       /* If starting a threeway call, never timeout on the first digit so someone
08284          can use flash-hook as a "hold" feature */
08285       if (p->subs[SUB_THREEWAY].owner)
08286          timeout = 999999;
08287       while (len < AST_MAX_EXTENSION-1) {
08288          /* Read digit unless it's supposed to be immediate, in which case the
08289             only answer is 's' */
08290          if (p->immediate)
08291             res = 's';
08292          else
08293             res = ast_waitfordigit(chan, timeout);
08294          timeout = 0;
08295          if (res < 0) {
08296             ast_debug(1, "waitfordigit returned < 0...\n");
08297             res = tone_zone_play_tone(p->subs[idx].dfd, -1);
08298             ast_hangup(chan);
08299             goto quit;
08300          } else if (res) {
08301             ast_debug(1,"waitfordigit returned '%c' (%d), timeout = %d\n", res, res, timeout);
08302             exten[len++]=res;
08303             exten[len] = '\0';
08304          }
08305          if (!ast_ignore_pattern(chan->context, exten))
08306             tone_zone_play_tone(p->subs[idx].dfd, -1);
08307          else
08308             tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
08309          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
08310             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
08311                if (getforward) {
08312                   /* Record this as the forwarding extension */
08313                   ast_copy_string(p->call_forward, exten, sizeof(p->call_forward));
08314                   ast_verb(3, "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
08315                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08316                   if (res)
08317                      break;
08318                   usleep(500000);
08319                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
08320                   sleep(1);
08321                   memset(exten, 0, sizeof(exten));
08322                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALTONE);
08323                   len = 0;
08324                   getforward = 0;
08325                } else {
08326                   res = tone_zone_play_tone(p->subs[idx].dfd, -1);
08327                   ast_copy_string(chan->exten, exten, sizeof(chan->exten));
08328                   if (!ast_strlen_zero(p->cid_num)) {
08329                      if (!p->hidecallerid)
08330                         ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
08331                      else
08332                         ast_set_callerid(chan, NULL, NULL, p->cid_num);
08333                   }
08334                   if (!ast_strlen_zero(p->cid_name)) {
08335                      if (!p->hidecallerid)
08336                         ast_set_callerid(chan, NULL, p->cid_name, NULL);
08337                   }
08338                   ast_setstate(chan, AST_STATE_RING);
08339                   dahdi_enable_ec(p);
08340                   res = ast_pbx_run(chan);
08341                   if (res) {
08342                      ast_log(LOG_WARNING, "PBX exited non-zero\n");
08343                      res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
08344                   }
08345                   goto quit;
08346                }
08347             } else {
08348                /* It's a match, but they just typed a digit, and there is an ambiguous match,
08349                   so just set the timeout to matchdigittimeout and wait some more */
08350                timeout = matchdigittimeout;
08351             }
08352          } else if (res == 0) {
08353             ast_debug(1, "not enough digits (and no ambiguous match)...\n");
08354             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
08355             dahdi_wait_event(p->subs[idx].dfd);
08356             ast_hangup(chan);
08357             goto quit;
08358          } else if (p->callwaiting && !strcmp(exten, "*70")) {
08359             ast_verb(3, "Disabling call waiting on %s\n", chan->name);
08360             /* Disable call waiting if enabled */
08361             p->callwaiting = 0;
08362             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08363             if (res) {
08364                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
08365                   chan->name, strerror(errno));
08366             }
08367             len = 0;
08368             ioctl(p->subs[idx].dfd,DAHDI_CONFDIAG,&len);
08369             memset(exten, 0, sizeof(exten));
08370             timeout = firstdigittimeout;
08371 
08372          } else if (!strcmp(exten,ast_pickup_ext())) {
08373             /* Scan all channels and see if there are any
08374              * ringing channels that have call groups
08375              * that equal this channels pickup group
08376              */
08377             if (idx == SUB_REAL) {
08378                /* Switch us from Third call to Call Wait */
08379                if (p->subs[SUB_THREEWAY].owner) {
08380                   /* If you make a threeway call and the *8# a call, it should actually
08381                      look like a callwait */
08382                   alloc_sub(p, SUB_CALLWAIT);
08383                   swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
08384                   unalloc_sub(p, SUB_THREEWAY);
08385                }
08386                dahdi_enable_ec(p);
08387                if (ast_pickup_call(chan)) {
08388                   ast_debug(1, "No call pickup possible...\n");
08389                   res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
08390                   dahdi_wait_event(p->subs[idx].dfd);
08391                }
08392                ast_hangup(chan);
08393                goto quit;
08394             } else {
08395                ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
08396                ast_hangup(chan);
08397                goto quit;
08398             }
08399 
08400          } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
08401             ast_verb(3, "Disabling Caller*ID on %s\n", chan->name);
08402             /* Disable Caller*ID if enabled */
08403             p->hidecallerid = 1;
08404             if (chan->cid.cid_num)
08405                ast_free(chan->cid.cid_num);
08406             chan->cid.cid_num = NULL;
08407             if (chan->cid.cid_name)
08408                ast_free(chan->cid.cid_name);
08409             chan->cid.cid_name = NULL;
08410             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08411             if (res) {
08412                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
08413                   chan->name, strerror(errno));
08414             }
08415             len = 0;
08416             memset(exten, 0, sizeof(exten));
08417             timeout = firstdigittimeout;
08418          } else if (p->callreturn && !strcmp(exten, "*69")) {
08419             res = 0;
08420             if (!ast_strlen_zero(p->lastcid_num)) {
08421                res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
08422             }
08423             if (!res)
08424                res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08425             break;
08426          } else if (!strcmp(exten, "*78")) {
08427             dahdi_dnd(p, 1);
08428             /* Do not disturb */
08429             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08430             getforward = 0;
08431             memset(exten, 0, sizeof(exten));
08432             len = 0;
08433          } else if (!strcmp(exten, "*79")) {
08434             dahdi_dnd(p, 0);
08435             /* Do not disturb */
08436             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08437             getforward = 0;
08438             memset(exten, 0, sizeof(exten));
08439             len = 0;
08440          } else if (p->cancallforward && !strcmp(exten, "*72")) {
08441             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08442             getforward = 1;
08443             memset(exten, 0, sizeof(exten));
08444             len = 0;
08445          } else if (p->cancallforward && !strcmp(exten, "*73")) {
08446             ast_verb(3, "Cancelling call forwarding on channel %d\n", p->channel);
08447             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08448             memset(p->call_forward, 0, sizeof(p->call_forward));
08449             getforward = 0;
08450             memset(exten, 0, sizeof(exten));
08451             len = 0;
08452          } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) &&
08453                   p->subs[SUB_THREEWAY].owner &&
08454                   ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
08455             /* This is a three way call, the main call being a real channel,
08456                and we're parking the first call. */
08457             ast_masq_park_call(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), chan, 0, NULL);
08458             ast_verb(3, "Parking call to '%s'\n", chan->name);
08459             break;
08460          } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
08461             ast_verb(3, "Blacklisting number %s\n", p->lastcid_num);
08462             res = ast_db_put("blacklist", p->lastcid_num, "1");
08463             if (!res) {
08464                res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08465                memset(exten, 0, sizeof(exten));
08466                len = 0;
08467             }
08468          } else if (p->hidecallerid && !strcmp(exten, "*82")) {
08469             ast_verb(3, "Enabling Caller*ID on %s\n", chan->name);
08470             /* Enable Caller*ID if enabled */
08471             p->hidecallerid = 0;
08472             if (chan->cid.cid_num)
08473                ast_free(chan->cid.cid_num);
08474             chan->cid.cid_num = NULL;
08475             if (chan->cid.cid_name)
08476                ast_free(chan->cid.cid_name);
08477             chan->cid.cid_name = NULL;
08478             ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
08479             res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_DIALRECALL);
08480             if (res) {
08481                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n",
08482                   chan->name, strerror(errno));
08483             }
08484             len = 0;
08485             memset(exten, 0, sizeof(exten));
08486             timeout = firstdigittimeout;
08487          } else if (!strcmp(exten, "*0")) {
08488             struct ast_channel *nbridge =
08489                p->subs[SUB_THREEWAY].owner;
08490             struct dahdi_pvt *pbridge = NULL;
08491             /* set up the private struct of the bridged one, if any */
08492             if (nbridge && ast_bridged_channel(nbridge))
08493                pbridge = ast_bridged_channel(nbridge)->tech_pvt;
08494             if (nbridge && pbridge &&
08495                (nbridge->tech == &dahdi_tech) &&
08496                (ast_bridged_channel(nbridge)->tech == &dahdi_tech) &&
08497                ISTRUNK(pbridge)) {
08498                int func = DAHDI_FLASH;
08499                /* Clear out the dial buffer */
08500                p->dop.dialstr[0] = '\0';
08501                /* flash hookswitch */
08502                if ((ioctl(pbridge->subs[SUB_REAL].dfd,DAHDI_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
08503                   ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n",
08504                      nbridge->name, strerror(errno));
08505                }
08506                swap_subs(p, SUB_REAL, SUB_THREEWAY);
08507                unalloc_sub(p, SUB_THREEWAY);
08508                p->owner = p->subs[SUB_REAL].owner;
08509                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
08510                   ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
08511                ast_hangup(chan);
08512                goto quit;
08513             } else {
08514                tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
08515                dahdi_wait_event(p->subs[idx].dfd);
08516                tone_zone_play_tone(p->subs[idx].dfd, -1);
08517                swap_subs(p, SUB_REAL, SUB_THREEWAY);
08518                unalloc_sub(p, SUB_THREEWAY);
08519                p->owner = p->subs[SUB_REAL].owner;
08520                ast_hangup(chan);
08521                goto quit;
08522             }
08523          } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
08524                      ((exten[0] != '*') || (strlen(exten) > 2))) {
08525             ast_debug(1, "Can't match %s from '%s' in context %s\n", exten, chan->cid.cid_num ? chan->cid.cid_num : "<Unknown Caller>", chan->context);
08526             break;
08527          }
08528          if (!timeout)
08529             timeout = gendigittimeout;
08530          if (len && !ast_ignore_pattern(chan->context, exten))
08531             tone_zone_play_tone(p->subs[idx].dfd, -1);
08532       }
08533       break;
08534    case SIG_FXSLS:
08535    case SIG_FXSGS:
08536    case SIG_FXSKS:
08537 #ifdef HAVE_PRI
08538       if (p->pri) {
08539          /* This is a GR-303 trunk actually.  Wait for the first ring... */
08540          struct ast_frame *f;
08541          int res;
08542          time_t start;
08543 
08544          time(&start);
08545          ast_setstate(chan, AST_STATE_RING);
08546          while (time(NULL) < start + 3) {
08547             res = ast_waitfor(chan, 1000);
08548             if (res) {
08549                f = ast_read(chan);
08550                if (!f) {
08551                   ast_log(LOG_WARNING, "Whoa, hangup while waiting for first ring!\n");
08552                   ast_hangup(chan);
08553                   goto quit;
08554                } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RING)) {
08555                   res = 1;
08556                } else
08557                   res = 0;
08558                ast_frfree(f);
08559                if (res) {
08560                   ast_debug(1, "Got ring!\n");
08561                   res = 0;
08562                   break;
08563                }
08564             }
08565          }
08566       }
08567 #endif
08568       /* check for SMDI messages */
08569       if (p->use_smdi && p->smdi_iface) {
08570          smdi_msg = ast_smdi_md_message_wait(p->smdi_iface, SMDI_MD_WAIT_TIMEOUT);
08571 
08572          if (smdi_msg != NULL) {
08573             ast_copy_string(chan->exten, smdi_msg->fwd_st, sizeof(chan->exten));
08574 
08575             if (smdi_msg->type == 'B')
08576                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "b");
08577             else if (smdi_msg->type == 'N')
08578                pbx_builtin_setvar_helper(chan, "_SMDI_VM_TYPE", "u");
08579 
08580             ast_debug(1, "Received SMDI message on %s\n", chan->name);
08581          } else {
08582             ast_log(LOG_WARNING, "SMDI enabled but no SMDI message present\n");
08583          }
08584       }
08585 
08586       if (p->use_callerid && (p->cid_signalling == CID_SIG_SMDI && smdi_msg)) {
08587          number = smdi_msg->calling_st;
08588 
08589       /* If we want caller id, we're in a prering state due to a polarity reversal
08590        * and we're set to use a polarity reversal to trigger the start of caller id,
08591        * grab the caller id and wait for ringing to start... */
08592       } else if (p->use_callerid && (chan->_state == AST_STATE_PRERING && (p->cid_start == CID_START_POLARITY || p->cid_start == CID_START_POLARITY_IN))) {
08593          /* If set to use DTMF CID signalling, listen for DTMF */
08594          if (p->cid_signalling == CID_SIG_DTMF) {
08595             int k = 0;
08596             cs = NULL;
08597             ast_debug(1, "Receiving DTMF cid on channel %s\n", chan->name);
08598             dahdi_setlinear(p->subs[idx].dfd, 0);
08599             /*
08600              * We are the only party interested in the Rx stream since
08601              * we have not answered yet.  We don't need or even want DTMF
08602              * emulation.  The DTMF digits can come so fast that emulation
08603              * can drop some of them.
08604              */
08605             ast_set_flag(chan, AST_FLAG_END_DTMF_ONLY);
08606             res = 4000;/* This is a typical OFF time between rings. */
08607             for (;;) {
08608                struct ast_frame *f;
08609                res = ast_waitfor(chan, res);
08610                if (res <= 0) {
08611                   /*
08612                    * We do not need to restore the dahdi_setlinear()
08613                    * or AST_FLAG_END_DTMF_ONLY flag settings since we
08614                    * are hanging up the channel.
08615                    */
08616                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
08617                      "Exiting simple switch\n");
08618                   ast_hangup(chan);
08619                   goto quit;
08620                }
08621                f = ast_read(chan);
08622                if (!f)
08623                   break;
08624                if (f->frametype == AST_FRAME_DTMF) {
08625                   if (k < ARRAY_LEN(dtmfbuf) - 1) {
08626                      dtmfbuf[k++] = f->subclass;
08627                   }
08628                   ast_debug(1, "CID got digit '%c'\n", f->subclass);
08629                   res = 4000;/* This is a typical OFF time between rings. */
08630                }
08631                ast_frfree(f);
08632                if (chan->_state == AST_STATE_RING ||
08633                   chan->_state == AST_STATE_RINGING)
08634                   break; /* Got ring */
08635             }
08636             ast_clear_flag(chan, AST_FLAG_END_DTMF_ONLY);
08637             dtmfbuf[k] = '\0';
08638             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08639             /* Got cid and ring. */
08640             ast_debug(1, "CID got string '%s'\n", dtmfbuf);
08641             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
08642             ast_debug(1, "CID is '%s', flags %d\n", dtmfcid, flags);
08643             /* If first byte is NULL, we have no cid */
08644             if (!ast_strlen_zero(dtmfcid))
08645                number = dtmfcid;
08646             else
08647                number = NULL;
08648          /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
08649          } else if ((p->cid_signalling == CID_SIG_V23) || (p->cid_signalling == CID_SIG_V23_JP)) {
08650             cs = callerid_new(p->cid_signalling);
08651             if (cs) {
08652                samples = 0;
08653 #if 1
08654                bump_gains(p);
08655 #endif
08656                /* Take out of linear mode for Caller*ID processing */
08657                dahdi_setlinear(p->subs[idx].dfd, 0);
08658 
08659                /* First we wait and listen for the Caller*ID */
08660                for (;;) {
08661                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
08662                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
08663                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
08664                      callerid_free(cs);
08665                      ast_hangup(chan);
08666                      goto quit;
08667                   }
08668                   if (i & DAHDI_IOMUX_SIGEVENT) {
08669                      res = dahdi_get_event(p->subs[idx].dfd);
08670                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
08671                      if (res == DAHDI_EVENT_NOALARM) {
08672                         p->inalarm = 0;
08673                      }
08674 
08675                      if (p->cid_signalling == CID_SIG_V23_JP) {
08676                         if (res == DAHDI_EVENT_RINGBEGIN) {
08677                            res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
08678                            usleep(1);
08679                         }
08680                      } else {
08681                         res = 0;
08682                         break;
08683                      }
08684                   } else if (i & DAHDI_IOMUX_READ) {
08685                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
08686                      if (res < 0) {
08687                         if (errno != ELAST) {
08688                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
08689                            callerid_free(cs);
08690                            ast_hangup(chan);
08691                            goto quit;
08692                         }
08693                         break;
08694                      }
08695                      samples += res;
08696 
08697                      if (p->cid_signalling == CID_SIG_V23_JP) {
08698                         res = callerid_feed_jp(cs, buf, res, AST_LAW(p));
08699                      } else {
08700                         res = callerid_feed(cs, buf, res, AST_LAW(p));
08701                      }
08702                      if (res < 0) {
08703                         /*
08704                          * The previous diagnostic message output likely
08705                          * explains why it failed.
08706                          */
08707                         ast_log(LOG_WARNING,
08708                            "Failed to decode CallerID on channel '%s'\n",
08709                            chan->name);
08710                         break;
08711                      } else if (res)
08712                         break;
08713                      else if (samples > (8000 * 10))
08714                         break;
08715                   }
08716                }
08717                if (res == 1) {
08718                   callerid_get(cs, &name, &number, &flags);
08719                   ast_log(LOG_NOTICE, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
08720                }
08721 
08722                if (p->cid_signalling == CID_SIG_V23_JP) {
08723                   res = dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
08724                   usleep(1);
08725                }
08726 
08727                /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */
08728                res = 4000;/* This is a typical OFF time between rings. */
08729                for (;;) {
08730                   struct ast_frame *f;
08731                   res = ast_waitfor(chan, res);
08732                   if (res <= 0) {
08733                      ast_log(LOG_WARNING, "CID timed out waiting for ring. "
08734                         "Exiting simple switch\n");
08735                      ast_hangup(chan);
08736                      goto quit;
08737                   }
08738                   if (!(f = ast_read(chan))) {
08739                      ast_log(LOG_WARNING, "Hangup received waiting for ring. Exiting simple switch\n");
08740                      ast_hangup(chan);
08741                      goto quit;
08742                   }
08743                   ast_frfree(f);
08744                   if (chan->_state == AST_STATE_RING ||
08745                      chan->_state == AST_STATE_RINGING)
08746                      break; /* Got ring */
08747                }
08748 
08749                /* We must have a ring by now, so, if configured, lets try to listen for
08750                 * distinctive ringing */
08751                if (p->usedistinctiveringdetection) {
08752                   len = 0;
08753                   distMatches = 0;
08754                   /* Clear the current ring data array so we dont have old data in it. */
08755                   for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
08756                      curRingData[receivedRingT] = 0;
08757                   receivedRingT = 0;
08758                   counter = 0;
08759                   counter1 = 0;
08760                   /* Check to see if context is what it should be, if not set to be. */
08761                   if (strcmp(p->context,p->defcontext) != 0) {
08762                      ast_copy_string(p->context, p->defcontext, sizeof(p->context));
08763                      ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
08764                   }
08765 
08766                   for (;;) {
08767                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
08768                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
08769                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
08770                         callerid_free(cs);
08771                         ast_hangup(chan);
08772                         goto quit;
08773                      }
08774                      if (i & DAHDI_IOMUX_SIGEVENT) {
08775                         res = dahdi_get_event(p->subs[idx].dfd);
08776                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
08777                         if (res == DAHDI_EVENT_NOALARM) {
08778                            p->inalarm = 0;
08779                         }
08780                         res = 0;
08781                         /* Let us detect distinctive ring */
08782 
08783                         curRingData[receivedRingT] = p->ringt;
08784 
08785                         if (p->ringt < p->ringt_base/2)
08786                            break;
08787                         /* Increment the ringT counter so we can match it against
08788                            values in chan_dahdi.conf for distinctive ring */
08789                         if (++receivedRingT == ARRAY_LEN(curRingData))
08790                            break;
08791                      } else if (i & DAHDI_IOMUX_READ) {
08792                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
08793                         if (res < 0) {
08794                            if (errno != ELAST) {
08795                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
08796                               callerid_free(cs);
08797                               ast_hangup(chan);
08798                               goto quit;
08799                            }
08800                            break;
08801                         }
08802                         if (p->ringt)
08803                            p->ringt--;
08804                         if (p->ringt == 1) {
08805                            res = -1;
08806                            break;
08807                         }
08808                      }
08809                   }
08810                      /* this only shows up if you have n of the dring patterns filled in */
08811                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
08812                   for (counter = 0; counter < 3; counter++) {
08813                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
08814                      channel */
08815                      distMatches = 0;
08816                      for (counter1 = 0; counter1 < 3; counter1++) {
08817                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
08818                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
08819                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
08820                            curRingData[counter1]);
08821                            distMatches++;
08822                         } else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
08823                               curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
08824                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
08825                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
08826                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
08827                            distMatches++;
08828                         }
08829                      }
08830 
08831                      if (distMatches == 3) {
08832                         /* The ring matches, set the context to whatever is for distinctive ring.. */
08833                         ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
08834                         ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
08835                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
08836                         break;
08837                      }
08838                   }
08839                }
08840                /* Restore linear mode (if appropriate) for Caller*ID processing */
08841                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08842 #if 1
08843                restore_gains(p);
08844 #endif
08845             } else
08846                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
08847          } else {
08848             ast_log(LOG_WARNING, "Channel %s in prering "
08849                "state, but I have nothing to do. "
08850                "Terminating simple switch, should be "
08851                "restarted by the actual ring.\n",
08852                chan->name);
08853             ast_hangup(chan);
08854             goto quit;
08855          }
08856       } else if (p->use_callerid && p->cid_start == CID_START_RING) {
08857          if (p->cid_signalling == CID_SIG_DTMF) {
08858             int k = 0;
08859             cs = NULL;
08860             dahdi_setlinear(p->subs[idx].dfd, 0);
08861             res = 2000;
08862             for (;;) {
08863                struct ast_frame *f;
08864                res = ast_waitfor(chan, res);
08865                if (res <= 0) {
08866                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
08867                      "Exiting simple switch\n");
08868                   ast_hangup(chan);
08869                   return NULL;
08870                }
08871                f = ast_read(chan);
08872                if (f->frametype == AST_FRAME_DTMF) {
08873                   dtmfbuf[k++] = f->subclass;
08874                   ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass);
08875                   res = 2000;
08876                }
08877                ast_frfree(f);
08878 
08879                if (p->ringt_base == p->ringt)
08880                   break;
08881             }
08882             dtmfbuf[k] = '\0';
08883             dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
08884             /* Got cid and ring. */
08885             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
08886             ast_log(LOG_DEBUG, "CID is '%s', flags %d\n",
08887                dtmfcid, flags);
08888             /* If first byte is NULL, we have no cid */
08889             if (!ast_strlen_zero(dtmfcid))
08890                number = dtmfcid;
08891             else
08892                number = NULL;
08893             /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
08894          } else {
08895             /* FSK Bell202 callerID */
08896             cs = callerid_new(p->cid_signalling);
08897             if (cs) {
08898 #if 1
08899                bump_gains(p);
08900 #endif
08901                samples = 0;
08902                len = 0;
08903                distMatches = 0;
08904                /* Clear the current ring data array so we dont have old data in it. */
08905                for (receivedRingT = 0; receivedRingT < ARRAY_LEN(curRingData); receivedRingT++)
08906                   curRingData[receivedRingT] = 0;
08907                receivedRingT = 0;
08908                counter = 0;
08909                counter1 = 0;
08910                /* Check to see if context is what it should be, if not set to be. */
08911                if (strcmp(p->context,p->defcontext) != 0) {
08912                   ast_copy_string(p->context, p->defcontext, sizeof(p->context));
08913                   ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
08914                }
08915 
08916                /* Take out of linear mode for Caller*ID processing */
08917                dahdi_setlinear(p->subs[idx].dfd, 0);
08918                for (;;) {
08919                   i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
08920                   if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
08921                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
08922                      callerid_free(cs);
08923                      ast_hangup(chan);
08924                      goto quit;
08925                   }
08926                   if (i & DAHDI_IOMUX_SIGEVENT) {
08927                      res = dahdi_get_event(p->subs[idx].dfd);
08928                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
08929                      if (res == DAHDI_EVENT_NOALARM) {
08930                         p->inalarm = 0;
08931                      }
08932                      /* If we get a PR event, they hung up while processing calerid */
08933                      if ( res == DAHDI_EVENT_POLARITY && p->hanguponpolarityswitch && p->polarity == POLARITY_REV) {
08934                         ast_log(LOG_DEBUG, "Hanging up due to polarity reversal on channel %d while detecting callerid\n", p->channel);
08935                         p->polarity = POLARITY_IDLE;
08936                         callerid_free(cs);
08937                         ast_hangup(chan);
08938                         goto quit;
08939                      }
08940                      res = 0;
08941                      /* Let us detect callerid when the telco uses distinctive ring */
08942 
08943                      curRingData[receivedRingT] = p->ringt;
08944 
08945                      if (p->ringt < p->ringt_base/2)
08946                         break;
08947                      /* Increment the ringT counter so we can match it against
08948                         values in chan_dahdi.conf for distinctive ring */
08949                      if (++receivedRingT == ARRAY_LEN(curRingData))
08950                         break;
08951                   } else if (i & DAHDI_IOMUX_READ) {
08952                      res = read(p->subs[idx].dfd, buf, sizeof(buf));
08953                      if (res < 0) {
08954                         if (errno != ELAST) {
08955                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
08956                            callerid_free(cs);
08957                            ast_hangup(chan);
08958                            goto quit;
08959                         }
08960                         break;
08961                      }
08962                      if (p->ringt)
08963                         p->ringt--;
08964                      if (p->ringt == 1) {
08965                         res = -1;
08966                         break;
08967                      }
08968                      samples += res;
08969                      res = callerid_feed(cs, buf, res, AST_LAW(p));
08970                      if (res < 0) {
08971                         /*
08972                          * The previous diagnostic message output likely
08973                          * explains why it failed.
08974                          */
08975                         ast_log(LOG_WARNING,
08976                            "Failed to decode CallerID on channel '%s'\n",
08977                            chan->name);
08978                         break;
08979                      } else if (res)
08980                         break;
08981                      else if (samples > (8000 * 10))
08982                         break;
08983                   }
08984                }
08985                if (res == 1) {
08986                   callerid_get(cs, &name, &number, &flags);
08987                   ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
08988                }
08989                if (distinctiveringaftercid == 1) {
08990                   /* Clear the current ring data array so we dont have old data in it. */
08991                   for (receivedRingT = 0; receivedRingT < 3; receivedRingT++) {
08992                      curRingData[receivedRingT] = 0;
08993                   }
08994                   receivedRingT = 0;
08995                   ast_verb(3, "Detecting post-CID distinctive ring\n");
08996                   for (;;) {
08997                      i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
08998                      if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
08999                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
09000                         callerid_free(cs);
09001                         ast_hangup(chan);
09002                         goto quit;
09003                      }
09004                      if (i & DAHDI_IOMUX_SIGEVENT) {
09005                         res = dahdi_get_event(p->subs[idx].dfd);
09006                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
09007                         if (res == DAHDI_EVENT_NOALARM) {
09008                            p->inalarm = 0;
09009                         }
09010                         res = 0;
09011                         /* Let us detect callerid when the telco uses distinctive ring */
09012 
09013                         curRingData[receivedRingT] = p->ringt;
09014 
09015                         if (p->ringt < p->ringt_base/2)
09016                            break;
09017                         /* Increment the ringT counter so we can match it against
09018                            values in chan_dahdi.conf for distinctive ring */
09019                         if (++receivedRingT == ARRAY_LEN(curRingData))
09020                            break;
09021                      } else if (i & DAHDI_IOMUX_READ) {
09022                         res = read(p->subs[idx].dfd, buf, sizeof(buf));
09023                         if (res < 0) {
09024                            if (errno != ELAST) {
09025                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
09026                               callerid_free(cs);
09027                               ast_hangup(chan);
09028                               goto quit;
09029                            }
09030                            break;
09031                         }
09032                      if (p->ringt)
09033                         p->ringt--;
09034                         if (p->ringt == 1) {
09035                            res = -1;
09036                            break;
09037                         }
09038                      }
09039                   }
09040                }
09041                if (p->usedistinctiveringdetection) {
09042                   /* this only shows up if you have n of the dring patterns filled in */
09043                   ast_verb(3, "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
09044 
09045                   for (counter = 0; counter < 3; counter++) {
09046                      /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this
09047                      channel */
09048                      /* this only shows up if you have n of the dring patterns filled in */
09049                      ast_verb(3, "Checking %d,%d,%d\n",
09050                            p->drings.ringnum[counter].ring[0],
09051                            p->drings.ringnum[counter].ring[1],
09052                            p->drings.ringnum[counter].ring[2]);
09053                      distMatches = 0;
09054                      for (counter1 = 0; counter1 < 3; counter1++) {
09055                         ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
09056                         if (p->drings.ringnum[counter].ring[counter1] == -1) {
09057                            ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
09058                            curRingData[counter1]);
09059                            distMatches++;
09060                         }
09061                         else if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
09062                            curRingData[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
09063                            ast_verb(3, "Ring pattern matched in range: %d to %d\n",
09064                            (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
09065                            (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
09066                            distMatches++;
09067                         }
09068                      }
09069                      if (distMatches == 3) {
09070                         /* The ring matches, set the context to whatever is for distinctive ring.. */
09071                         ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
09072                         ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
09073                         ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
09074                         break;
09075                      }
09076                   }
09077                }
09078                /* Restore linear mode (if appropriate) for Caller*ID processing */
09079                dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
09080 #if 1
09081                restore_gains(p);
09082 #endif
09083                if (res < 0) {
09084                   ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
09085                }
09086             } else
09087                ast_log(LOG_WARNING, "Unable to get caller ID space\n");
09088          }
09089       } else
09090          cs = NULL;
09091 
09092       if (number)
09093          ast_shrink_phone_number(number);
09094       ast_set_callerid(chan, number, name, number);
09095 
09096       if (smdi_msg)
09097          ASTOBJ_UNREF(smdi_msg, ast_smdi_md_message_destroy);
09098 
09099       if (cs)
09100          callerid_free(cs);
09101       /* If the CID had Message waiting payload, assume that this for MWI only and hangup the call */
09102       if (flags & CID_MSGWAITING) {
09103          ast_log(LOG_NOTICE, "MWI: Channel %d message waiting!\n", p->channel);
09104          notify_message(p->mailbox, 1);
09105          /* If generated using Ring Pulse Alert, then ring has been answered as a call and needs to be hungup */
09106          if (p->mwimonitor_rpas) {
09107             ast_hangup(chan);
09108             return NULL;
09109          }
09110       } else if (flags & CID_NOMSGWAITING) {
09111          ast_log(LOG_NOTICE, "MWI: Channel %d no message waiting!\n", p->channel);
09112          notify_message(p->mailbox, 0);
09113          /* If generated using Ring Pulse Alert, then ring has been answered as a call and needs to be hungup */
09114          if (p->mwimonitor_rpas) {
09115             ast_hangup(chan);
09116             return NULL;
09117          }
09118       }
09119 
09120       ast_setstate(chan, AST_STATE_RING);
09121       chan->rings = 1;
09122       p->ringt = p->ringt_base;
09123       res = ast_pbx_run(chan);
09124       if (res) {
09125          ast_hangup(chan);
09126          ast_log(LOG_WARNING, "PBX exited non-zero\n");
09127       }
09128       goto quit;
09129    default:
09130       ast_log(LOG_WARNING, "Don't know how to handle simple switch with signalling %s on channel %d\n", sig2str(p->sig), p->channel);
09131       res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09132       if (res < 0)
09133             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
09134    }
09135    res = tone_zone_play_tone(p->subs[idx].dfd, DAHDI_TONE_CONGESTION);
09136    if (res < 0)
09137          ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", p->channel);
09138    ast_hangup(chan);
09139 quit:
09140    ast_mutex_lock(&ss_thread_lock);
09141    ss_thread_count--;
09142    ast_cond_signal(&ss_thread_complete);
09143    ast_mutex_unlock(&ss_thread_lock);
09144    return NULL;
09145 }
09146 
09147 struct mwi_thread_data {
09148    struct dahdi_pvt *pvt;
09149    unsigned char buf[READ_SIZE];
09150    size_t len;
09151 };
09152 
09153 static int calc_energy(const unsigned char *buf, int len, int law)
09154 {
09155    int x;
09156    int sum = 0;
09157 
09158    if (!len)
09159       return 0;
09160 
09161    for (x = 0; x < len; x++)
09162       sum += abs(law == AST_FORMAT_ULAW ? AST_MULAW(buf[x]) : AST_ALAW(buf[x]));
09163 
09164    return sum / len;
09165 }
09166 
09167 static void *mwi_thread(void *data)
09168 {
09169    struct mwi_thread_data *mtd = data;
09170    struct callerid_state *cs;
09171    pthread_t threadid;
09172    int samples = 0;
09173    char *name, *number;
09174    int flags;
09175    int i, res;
09176    unsigned int spill_done = 0;
09177    int spill_result = -1;
09178 
09179    if (!(cs = callerid_new(mtd->pvt->cid_signalling))) {
09180       mtd->pvt->mwimonitoractive = 0;
09181 
09182       return NULL;
09183    }
09184 
09185    callerid_feed(cs, mtd->buf, mtd->len, AST_LAW(mtd->pvt));
09186 
09187    bump_gains(mtd->pvt);
09188 
09189    for (;;) {
09190       i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
09191       if ((res = ioctl(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_IOMUX, &i))) {
09192          ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
09193          goto quit;
09194       }
09195 
09196       if (i & DAHDI_IOMUX_SIGEVENT) {
09197          struct ast_channel *chan;
09198 
09199          /* If we get an event, screen out events that we do not act on.
09200           * Otherwise, cancel and go to the simple switch to let it deal with it.
09201           */
09202          res = dahdi_get_event(mtd->pvt->subs[SUB_REAL].dfd);
09203 
09204          switch (res) {
09205          case DAHDI_EVENT_NEONMWI_ACTIVE:
09206          case DAHDI_EVENT_NEONMWI_INACTIVE:
09207          case DAHDI_EVENT_NONE:
09208          case DAHDI_EVENT_BITSCHANGED:
09209             break;
09210          case DAHDI_EVENT_NOALARM:
09211             mtd->pvt->inalarm = 0;
09212             ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", mtd->pvt->channel);
09213             manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
09214                "Channel: %d\r\n", mtd->pvt->channel);
09215             break;
09216          case DAHDI_EVENT_ALARM:
09217             mtd->pvt->inalarm = 1;
09218             res = get_alarms(mtd->pvt);
09219             handle_alarms(mtd->pvt, res);
09220             break; /* What to do on channel alarm ???? -- fall thru intentionally?? */
09221          default:
09222             ast_log(LOG_NOTICE, "Got event %d (%s)...  Passing along to ss_thread\n", res, event2str(res));
09223             callerid_free(cs);
09224 
09225             restore_gains(mtd->pvt);
09226             mtd->pvt->ringt = mtd->pvt->ringt_base;
09227 
09228             if ((chan = dahdi_new(mtd->pvt, AST_STATE_RING, 0, SUB_REAL, 0, 0))) {
09229                if (ast_pthread_create_detached(&threadid, NULL, ss_thread, chan)) {
09230                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", mtd->pvt->channel);
09231                   res = tone_zone_play_tone(mtd->pvt->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
09232                   if (res < 0)
09233                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", mtd->pvt->channel);
09234                   ast_hangup(chan);
09235                   goto quit;
09236                }
09237                goto quit_no_clean;
09238 
09239             } else {
09240                ast_log(LOG_WARNING, "Could not create channel to handle call\n");
09241             }
09242          }
09243       } else if (i & DAHDI_IOMUX_READ) {
09244          if ((res = read(mtd->pvt->subs[SUB_REAL].dfd, mtd->buf, sizeof(mtd->buf))) < 0) {
09245             if (errno != ELAST) {
09246                ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
09247                goto quit;
09248             }
09249             break;
09250          }
09251          samples += res;
09252          if (!spill_done) {
09253             if ((spill_result = callerid_feed(cs, mtd->buf, res, AST_LAW(mtd->pvt))) < 0) {
09254                /*
09255                 * The previous diagnostic message output likely
09256                 * explains why it failed.
09257                 */
09258                ast_log(LOG_WARNING, "Failed to decode CallerID\n");
09259                break;
09260             } else if (spill_result) {
09261                spill_done = 1;
09262             }
09263          } else {
09264             /* keep reading data until the energy level drops below the threshold
09265                so we don't get another 'trigger' on the remaining carrier signal
09266             */
09267             if (calc_energy(mtd->buf, res, AST_LAW(mtd->pvt)) <= mwilevel)
09268                break;
09269          }
09270          if (samples > (8000 * 4)) /*Termination case - time to give up*/
09271             break;
09272       }
09273    }
09274 
09275    if (spill_result == 1) {
09276       callerid_get(cs, &name, &number, &flags);
09277       if (flags & CID_MSGWAITING) {
09278          ast_log(LOG_NOTICE, "mwi: Have Messages on channel %d\n", mtd->pvt->channel);
09279          notify_message(mtd->pvt->mailbox, 1);
09280       } else if (flags & CID_NOMSGWAITING) {
09281          ast_log(LOG_NOTICE, "mwi: No Messages on channel %d\n", mtd->pvt->channel);
09282          notify_message(mtd->pvt->mailbox, 0);
09283       } else {
09284          ast_log(LOG_NOTICE, "mwi: Status unknown on channel %d\n", mtd->pvt->channel);
09285       }
09286    }
09287 
09288 
09289 quit:
09290    callerid_free(cs);
09291 
09292    restore_gains(mtd->pvt);
09293 
09294 quit_no_clean:
09295    mtd->pvt->mwimonitoractive = 0;
09296 
09297    ast_free(mtd);
09298 
09299    return NULL;
09300 }
09301 
09302 /*
09303 * The following three functions (mwi_send_init, mwi_send_process_buffer,
09304 * mwi_send_process_event) work with the do_monitor thread to generate mwi spills
09305 * that are sent out via FXA port on voicemail state change.  The execution of
09306 * the mwi send is state driven and can either generate a ring pulse prior to
09307 * sending the fsk spill or simply send an fsk spill.
09308 */
09309 static int mwi_send_init(struct dahdi_pvt * pvt)
09310 {
09311    int x, res;
09312 
09313 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
09314    /* Determine how this spill is to be sent */
09315    if (pvt->mwisend_rpas) {
09316       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
09317       pvt->mwisendactive = 1;
09318    } else if (pvt->mwisend_fsk) {
09319       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
09320       pvt->mwisendactive = 1;
09321    } else {
09322       pvt->mwisendactive = 0;
09323       return 0;
09324    }
09325 #else
09326    if (mwisend_rpas) {
09327       pvt->mwisend_data.mwisend_current = MWI_SEND_SA;
09328    } else {
09329       pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
09330    }
09331    pvt->mwisendactive = 1;
09332 #endif
09333 
09334    if (pvt->cidspill) {
09335       ast_log(LOG_WARNING, "cidspill already exists when trying to send FSK MWI\n");
09336       ast_free(pvt->cidspill);
09337       pvt->cidspill = NULL;
09338       pvt->cidpos = 0;
09339       pvt->cidlen = 0;
09340    }
09341    pvt->cidspill = ast_calloc(1, MAX_CALLERID_SIZE);
09342    if (!pvt->cidspill) {
09343       pvt->mwisendactive = 0;
09344       return -1;
09345    }
09346    x = DAHDI_FLUSH_BOTH;
09347    res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
09348    x = 3000;
09349    ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_ONHOOKTRANSFER, &x);
09350 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
09351    if (pvt->mwisend_fsk) {
09352 #endif
09353       pvt->cidlen = vmwi_generate(pvt->cidspill, has_voicemail(pvt), CID_MWI_TYPE_MDMF_FULL,
09354                         AST_LAW(pvt), pvt->cid_name, pvt->cid_num, 0);
09355       pvt->cidpos = 0;
09356 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
09357    }
09358 #endif
09359    return 0;
09360 }
09361 
09362 static int mwi_send_process_buffer(struct dahdi_pvt * pvt, int num_read)
09363 {
09364    struct timeval    now;
09365    int         res;
09366 
09367    /* sanity check to catch if this had been interrupted previously
09368    *  i.e. state says there is more to do but there is no spill allocated
09369    */
09370    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current && !pvt->cidspill) {
09371       pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
09372    } else if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
09373       /* Normal processing -- Perform mwi send action */
09374       switch ( pvt->mwisend_data.mwisend_current) {
09375       case MWI_SEND_SA:
09376          /* Send the Ring Pulse Signal Alert */
09377          res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &AS_RP_cadence);
09378          if (res) {
09379             ast_log(LOG_WARNING, "Unable to set RP-AS ring cadence: %s\n", strerror(errno));
09380             goto quit;
09381          }
09382          res = dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RING);
09383          pvt->mwisend_data.mwisend_current = MWI_SEND_SA_WAIT;
09384          break;
09385       case MWI_SEND_SA_WAIT:  /* do nothing until I get RINGEROFF event */
09386          break;
09387       case MWI_SEND_PAUSE:  /* Wait between alert and spill - min of 500 mS*/
09388 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
09389          if (pvt->mwisend_fsk) {
09390 #endif
09391             gettimeofday(&now, NULL);
09392             if ((int)(now.tv_sec - pvt->mwisend_data.pause.tv_sec) * 1000000 + (int)now.tv_usec - (int)pvt->mwisend_data.pause.tv_usec > 500000) {
09393                pvt->mwisend_data.mwisend_current = MWI_SEND_SPILL;
09394             }
09395 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
09396          } else { /* support for mwisendtype=nofsk */
09397             pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
09398          }
09399 #endif
09400          break;
09401       case MWI_SEND_SPILL:
09402          /* We read some number of bytes.  Write an equal amount of data */
09403          if(0 < num_read) {
09404             if (num_read > pvt->cidlen - pvt->cidpos)
09405                num_read = pvt->cidlen - pvt->cidpos;
09406             res = write(pvt->subs[SUB_REAL].dfd, pvt->cidspill + pvt->cidpos, num_read);
09407             if (res > 0) {
09408                pvt->cidpos += res;
09409                if (pvt->cidpos >= pvt->cidlen) {
09410                   pvt->mwisend_data.mwisend_current = MWI_SEND_CLEANUP;
09411                }
09412             } else {
09413                ast_log(LOG_WARNING, "MWI FSK Send Write failed: %s\n", strerror(errno));
09414                goto quit;
09415             }
09416          }
09417          break;
09418       case MWI_SEND_CLEANUP:
09419          /* For now, do nothing */
09420          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
09421          break;
09422       default:
09423          /* Should not get here, punt*/
09424          goto quit;
09425       }
09426    }
09427 
09428    if (MWI_SEND_DONE == pvt->mwisend_data.mwisend_current) {
09429       if (pvt->cidspill) {
09430          ast_free(pvt->cidspill);
09431          pvt->cidspill = NULL;
09432          pvt->cidpos = 0;
09433          pvt->cidlen = 0;
09434       }
09435       pvt->mwisendactive = 0;
09436    }
09437    return 0;
09438 quit:
09439    if (pvt->cidspill) {
09440       ast_free(pvt->cidspill);
09441       pvt->cidspill = NULL;
09442       pvt->cidpos = 0;
09443       pvt->cidlen = 0;
09444    }
09445    pvt->mwisendactive = 0;
09446    return -1;
09447 }
09448 
09449 static int mwi_send_process_event(struct dahdi_pvt * pvt, int event)
09450 {
09451    int handled = 0;
09452 
09453    if (MWI_SEND_DONE != pvt->mwisend_data.mwisend_current) {
09454       switch (event) {
09455       case DAHDI_EVENT_RINGEROFF:
09456          if(pvt->mwisend_data.mwisend_current == MWI_SEND_SA_WAIT) {
09457             handled = 1;
09458 
09459             if (dahdi_set_hook(pvt->subs[SUB_REAL].dfd, DAHDI_RINGOFF) ) {
09460                ast_log(LOG_WARNING, "Unable to finsh RP-AS: %s mwi send aborted\n", strerror(errno));
09461                if(pvt->cidspill) {
09462                   ast_free(pvt->cidspill);
09463                   pvt->cidspill = NULL;
09464                }
09465                pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
09466                pvt->mwisendactive = 0;
09467             } else {
09468                pvt->mwisend_data.mwisend_current = MWI_SEND_PAUSE;
09469                gettimeofday(&pvt->mwisend_data.pause, NULL);
09470             }
09471          }
09472          break;
09473       /* Going off hook, I need to punt this spill */
09474       case DAHDI_EVENT_RINGOFFHOOK:
09475          if (pvt->cidspill) {
09476             ast_free(pvt->cidspill);
09477             pvt->cidspill = NULL;
09478             pvt->cidpos = 0;
09479             pvt->cidlen = 0;
09480          }
09481          pvt->mwisend_data.mwisend_current = MWI_SEND_DONE;
09482          pvt->mwisendactive = 0;
09483          break;
09484       case DAHDI_EVENT_RINGERON:
09485       case DAHDI_EVENT_HOOKCOMPLETE:
09486          break;
09487       default:
09488          break;
09489       }
09490    }
09491    return handled;
09492 }
09493 
09494 /* destroy a DAHDI channel, identified by its number */
09495 static int dahdi_destroy_channel_bynum(int channel)
09496 {
09497    struct dahdi_pvt *tmp = NULL;
09498    struct dahdi_pvt *prev = NULL;
09499 
09500    tmp = iflist;
09501    while (tmp) {
09502       if (tmp->channel == channel) {
09503          int x = DAHDI_FLASH;
09504          ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_HOOK, &x); /* important to create an event for dahdi_wait_event to register so that all ss_threads terminate */
09505          destroy_channel(prev, tmp, 1);
09506          ast_module_unref(ast_module_info->self);
09507          return RESULT_SUCCESS;
09508       }
09509       prev = tmp;
09510       tmp = tmp->next;
09511    }
09512    return RESULT_FAILURE;
09513 }
09514 
09515 static struct dahdi_pvt *handle_init_event(struct dahdi_pvt *i, int event)
09516 {
09517    int res;
09518    pthread_t threadid;
09519    struct ast_channel *chan;
09520 
09521    /* Handle an event on a given channel for the monitor thread. */
09522 
09523    switch (event) {
09524    case DAHDI_EVENT_NONE:
09525    case DAHDI_EVENT_BITSCHANGED:
09526       break;
09527    case DAHDI_EVENT_WINKFLASH:
09528    case DAHDI_EVENT_RINGOFFHOOK:
09529       if (i->inalarm) break;
09530       if (i->radio) break;
09531       /* Got a ring/answer.  What kind of channel are we? */
09532       switch (i->sig) {
09533       case SIG_FXOLS:
09534       case SIG_FXOGS:
09535       case SIG_FXOKS:
09536          res = dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
09537          i->fxsoffhookstate = 1;
09538          if (res && (errno == EBUSY))
09539             break;
09540          if (i->cidspill) {
09541             /* Cancel VMWI spill */
09542             ast_free(i->cidspill);
09543             i->cidspill = NULL;
09544          }
09545          if (i->immediate) {
09546             dahdi_enable_ec(i);
09547             /* The channel is immediately up.  Start right away */
09548             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_RINGTONE);
09549             chan = dahdi_new(i, AST_STATE_RING, 1, SUB_REAL, 0, 0);
09550             if (!chan) {
09551                ast_log(LOG_WARNING, "Unable to start PBX on channel %d\n", i->channel);
09552                res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
09553                if (res < 0)
09554                   ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
09555             }
09556          } else {
09557             /* Check for callerid, digits, etc */
09558             chan = dahdi_new(i, AST_STATE_RESERVED, 0, SUB_REAL, 0, 0);
09559             if (chan) {
09560                if (has_voicemail(i))
09561                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_STUTTER);
09562                else
09563                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_DIALTONE);
09564                if (res < 0)
09565                   ast_log(LOG_WARNING, "Unable to play dialtone on channel %d, do you have defaultzone and loadzone defined?\n", i->channel);
09566                if (ast_pthread_create_detached(&threadid, NULL, ss_thread, chan)) {
09567                   ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
09568                   res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
09569                   if (res < 0)
09570                      ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
09571                   ast_hangup(chan);
09572                }
09573             } else
09574                ast_log(LOG_WARNING, "Unable to create channel\n");
09575          }
09576          break;
09577       case SIG_FXSLS:
09578       case SIG_FXSGS:
09579       case SIG_FXSKS:
09580             i->ringt = i->ringt_base;
09581             /* Fall through */
09582       case SIG_EMWINK:
09583       case SIG_FEATD:
09584       case SIG_FEATDMF:
09585       case SIG_FEATDMF_TA:
09586       case SIG_E911:
09587       case SIG_FGC_CAMA:
09588       case SIG_FGC_CAMAMF:
09589       case SIG_FEATB:
09590       case SIG_EM:
09591       case SIG_EM_E1:
09592       case SIG_SFWINK:
09593       case SIG_SF_FEATD:
09594       case SIG_SF_FEATDMF:
09595       case SIG_SF_FEATB:
09596       case SIG_SF:
09597          /* Check for callerid, digits, etc */
09598          if (i->cid_start == CID_START_POLARITY_IN) {
09599             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, 0);
09600          } else {
09601             chan = dahdi_new(i, AST_STATE_RING, 0, SUB_REAL, 0, 0);
09602          }
09603 
09604          if (!chan) {
09605             ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
09606          } else if (ast_pthread_create_detached(&threadid, NULL, ss_thread, chan)) {
09607             ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
09608             res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
09609             if (res < 0) {
09610                ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
09611             }
09612             ast_hangup(chan);
09613          }
09614          break;
09615       default:
09616          ast_log(LOG_WARNING, "Don't know how to handle ring/answer with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
09617          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, DAHDI_TONE_CONGESTION);
09618          if (res < 0)
09619             ast_log(LOG_WARNING, "Unable to play congestion tone on channel %d\n", i->channel);
09620          return NULL;
09621       }
09622       break;
09623    case DAHDI_EVENT_NOALARM:
09624       i->inalarm = 0;
09625       ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", i->channel);
09626       manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
09627          "Channel: %d\r\n", i->channel);
09628       break;
09629    case DAHDI_EVENT_ALARM:
09630       i->inalarm = 1;
09631       res = get_alarms(i);
09632       handle_alarms(i, res);
09633       /* fall thru intentionally */
09634    case DAHDI_EVENT_ONHOOK:
09635       if (i->radio)
09636          break;
09637       /* Back on hook.  Hang up. */
09638       switch (i->sig) {
09639       case SIG_FXOLS:
09640       case SIG_FXOGS:
09641       case SIG_FEATD:
09642       case SIG_FEATDMF:
09643       case SIG_FEATDMF_TA:
09644       case SIG_E911:
09645       case SIG_FGC_CAMA:
09646       case SIG_FGC_CAMAMF:
09647       case SIG_FEATB:
09648       case SIG_EM:
09649       case SIG_EM_E1:
09650       case SIG_EMWINK:
09651       case SIG_SF_FEATD:
09652       case SIG_SF_FEATDMF:
09653       case SIG_SF_FEATB:
09654       case SIG_SF:
09655       case SIG_SFWINK:
09656       case SIG_FXSLS:
09657       case SIG_FXSGS:
09658       case SIG_FXSKS:
09659       case SIG_GR303FXSKS:
09660          dahdi_disable_ec(i);
09661          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
09662          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
09663          break;
09664       case SIG_GR303FXOKS:
09665       case SIG_FXOKS:
09666          dahdi_disable_ec(i);
09667          /* Diddle the battery for the zhone */
09668 #ifdef ZHONE_HACK
09669          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
09670          usleep(1);
09671 #endif
09672          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
09673          dahdi_set_hook(i->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
09674          break;
09675       case SIG_PRI:
09676       case SIG_SS7:
09677       case SIG_BRI:
09678       case SIG_BRI_PTMP:
09679          dahdi_disable_ec(i);
09680          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
09681          break;
09682       default:
09683          ast_log(LOG_WARNING, "Don't know how to handle on hook with signalling %s on channel %d\n", sig2str(i->sig), i->channel);
09684          res = tone_zone_play_tone(i->subs[SUB_REAL].dfd, -1);
09685          return NULL;
09686       }
09687       if (i->sig & __DAHDI_SIG_FXO) {
09688          i->fxsoffhookstate = 0;
09689       }
09690       break;
09691    case DAHDI_EVENT_POLARITY:
09692       switch (i->sig) {
09693       case SIG_FXSLS:
09694       case SIG_FXSKS:
09695       case SIG_FXSGS:
09696          /* We have already got a PR before the channel was
09697             created, but it wasn't handled. We need polarity
09698             to be REV for remote hangup detection to work.
09699             At least in Spain */
09700          if (i->hanguponpolarityswitch)
09701             i->polarity = POLARITY_REV;
09702          if (i->cid_start == CID_START_POLARITY || i->cid_start == CID_START_POLARITY_IN) {
09703             i->polarity = POLARITY_REV;
09704             ast_verb(2, "Starting post polarity "
09705                "CID detection on channel %d\n",
09706                i->channel);
09707             chan = dahdi_new(i, AST_STATE_PRERING, 0, SUB_REAL, 0, 0);
09708             if (!chan) {
09709                ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", i->channel);
09710             } else if (ast_pthread_create_detached(&threadid, NULL, ss_thread, chan)) {
09711                ast_log(LOG_WARNING, "Unable to start simple switch thread on channel %d\n", i->channel);
09712             }
09713          }
09714          break;
09715       default:
09716          ast_log(LOG_WARNING, "handle_init_event detected "
09717             "polarity reversal on non-FXO (SIG_FXS) "
09718             "interface %d\n", i->channel);
09719       }
09720       break;
09721    case DAHDI_EVENT_REMOVED: /* destroy channel, will actually do so in do_monitor */
09722       ast_log(LOG_NOTICE,
09723             "Got DAHDI_EVENT_REMOVED. Destroying channel %d\n",
09724             i->channel);
09725       return i;
09726    case DAHDI_EVENT_NEONMWI_ACTIVE:
09727       if (i->mwimonitor_neon) {
09728          notify_message(i->mailbox, 1);
09729          ast_log(LOG_NOTICE, "NEON MWI set for channel %d, mailbox %s \n", i->channel, i->mailbox);
09730       }
09731       break;
09732    case DAHDI_EVENT_NEONMWI_INACTIVE:
09733       if (i->mwimonitor_neon) {
09734          notify_message(i->mailbox, 0);
09735          ast_log(LOG_NOTICE, "NEON MWI cleared for channel %d, mailbox %s\n", i->channel, i->mailbox);
09736       }
09737       break;
09738    }
09739    return NULL;
09740 }
09741 
09742 static void *do_monitor(void *data)
09743 {
09744    int count, res, res2, spoint, pollres=0;
09745    struct dahdi_pvt *i;
09746    struct dahdi_pvt *last = NULL;
09747    struct dahdi_pvt *doomed;
09748    time_t thispass = 0, lastpass = 0;
09749    int found;
09750    char buf[1024];
09751    struct pollfd *pfds=NULL;
09752    int lastalloc = -1;
09753    /* This thread monitors all the frame relay interfaces which are not yet in use
09754       (and thus do not have a separate thread) indefinitely */
09755    /* From here on out, we die whenever asked */
09756 #if 0
09757    if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
09758       ast_log(LOG_WARNING, "Unable to set cancel type to asynchronous\n");
09759       return NULL;
09760    }
09761    ast_debug(1, "Monitor starting...\n");
09762 #endif
09763    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
09764 
09765    for (;;) {
09766       /* Lock the interface list */
09767       ast_mutex_lock(&iflock);
09768       if (!pfds || (lastalloc != ifcount)) {
09769          if (pfds) {
09770             ast_free(pfds);
09771             pfds = NULL;
09772          }
09773          if (ifcount) {
09774             if (!(pfds = ast_calloc(1, ifcount * sizeof(*pfds)))) {
09775                ast_mutex_unlock(&iflock);
09776                return NULL;
09777             }
09778          }
09779          lastalloc = ifcount;
09780       }
09781       /* Build the stuff we're going to poll on, that is the socket of every
09782          dahdi_pvt that does not have an associated owner channel */
09783       count = 0;
09784       i = iflist;
09785       while (i) {
09786          if ((i->subs[SUB_REAL].dfd > -1) && i->sig && (!i->radio) && !(i->sig & SIG_MFCR2)) {
09787             if (!i->owner && !i->subs[SUB_REAL].owner && !i->mwimonitoractive ) {
09788                /* This needs to be watched, as it lacks an owner */
09789                pfds[count].fd = i->subs[SUB_REAL].dfd;
09790                pfds[count].events = POLLPRI;
09791                pfds[count].revents = 0;
09792                /* If we are monitoring for VMWI or sending CID, we need to
09793                   read from the channel as well */
09794                if (i->cidspill || i->mwisendactive || i->mwimonitor_fsk)
09795                   pfds[count].events |= POLLIN;
09796                count++;
09797             }
09798          }
09799          i = i->next;
09800       }
09801       /* Okay, now that we know what to do, release the interface lock */
09802       ast_mutex_unlock(&iflock);
09803 
09804       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
09805       pthread_testcancel();
09806       /* Wait at least a second for something to happen */
09807       res = poll(pfds, count, 1000);
09808       pthread_testcancel();
09809       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
09810 
09811       /* Okay, poll has finished.  Let's see what happened.  */
09812       if (res < 0) {
09813          if ((errno != EAGAIN) && (errno != EINTR))
09814             ast_log(LOG_WARNING, "poll return %d: %s\n", res, strerror(errno));
09815          continue;
09816       }
09817       /* Alright, lock the interface list again, and let's look and see what has
09818          happened */
09819       ast_mutex_lock(&iflock);
09820       found = 0;
09821       spoint = 0;
09822       lastpass = thispass;
09823       thispass = time(NULL);
09824       i = iflist;
09825       doomed = NULL;
09826       for (i = iflist;; i = i->next) {
09827          if (doomed) {
09828             int res;
09829             res = dahdi_destroy_channel_bynum(doomed->channel);
09830             if (!res) {
09831                ast_log(LOG_WARNING, "Couldn't find channel to destroy, hopefully another destroy operation just happened.\n");
09832             }
09833             doomed = NULL;
09834          }
09835          if (!i) {
09836             break;
09837          }
09838 
09839          if (thispass != lastpass) {
09840             if (!found && ((i == last) || ((i == iflist) && !last))) {
09841                last = i;
09842                if (last) {
09843                   /* Only allow MWI to be initiated on a quiescent fxs port */
09844                   if (!last->mwisendactive
09845                      && (last->sig & __DAHDI_SIG_FXO)
09846                      && !last->fxsoffhookstate
09847                      && !last->owner
09848                      && !ast_strlen_zero(last->mailbox)
09849                      && (thispass - last->onhooktime > 3)) {
09850                      res = has_voicemail(last);
09851                      if (last->msgstate != res) {
09852                         /* Set driver resources for signalling VMWI */
09853                         res2 = ioctl(last->subs[SUB_REAL].dfd, DAHDI_VMWI, &res);
09854                         if (res2) {
09855                            /* TODO: This message will ALWAYS be generated on some cards; any way to restrict it to those cards where it is interesting? */
09856                            ast_debug(3, "Unable to control message waiting led on channel %d: %s\n", last->channel, strerror(errno));
09857                         }
09858                         /* If enabled for FSK spill then initiate it */
09859                         if (mwi_send_init(last)) {
09860                            ast_log(LOG_WARNING, "Unable to initiate mwi send sequence on channel %d\n", last->channel);
09861                         }
09862                         last->msgstate = res;
09863                         found ++;
09864                      }
09865                   }
09866                   last = last->next;
09867                }
09868             }
09869          }
09870          if ((i->subs[SUB_REAL].dfd > -1) && i->sig) {
09871             if (i->radio && !i->owner)
09872             {
09873                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
09874                if (res)
09875                {
09876                   ast_debug(1, "Monitor doohicky got event %s on radio channel %d\n", event2str(res), i->channel);
09877                   /* Don't hold iflock while handling init events */
09878                   ast_mutex_unlock(&iflock);
09879                   doomed = handle_init_event(i, res);
09880                   ast_mutex_lock(&iflock);
09881                }
09882                continue;
09883             }
09884             pollres = ast_fdisset(pfds, i->subs[SUB_REAL].dfd, count, &spoint);
09885             if (pollres & POLLIN) {
09886                if (i->owner || i->subs[SUB_REAL].owner) {
09887 #ifdef HAVE_PRI
09888                   if (!i->pri)
09889 #endif
09890                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d) in read...\n", i->subs[SUB_REAL].dfd);
09891                   continue;
09892                }
09893                if (!i->mwimonitor_fsk && !i->mwisendactive) {
09894                   ast_log(LOG_WARNING, "Whoa....  I'm not looking for MWI or sending MWI but am reading (%d)...\n", i->subs[SUB_REAL].dfd);
09895                   continue;
09896                }
09897                res = read(i->subs[SUB_REAL].dfd, buf, sizeof(buf));
09898                if (res > 0) {
09899                   if (i->mwimonitor_fsk) {
09900                      if (calc_energy((unsigned char *) buf, res, AST_LAW(i)) > mwilevel) {
09901                         pthread_attr_t attr;
09902                         pthread_t threadid;
09903                         struct mwi_thread_data *mtd;
09904 
09905                         pthread_attr_init(&attr);
09906                         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
09907 
09908                         ast_log(LOG_DEBUG, "Maybe some MWI on port %d!\n", i->channel);
09909                         if ((mtd = ast_calloc(1, sizeof(*mtd)))) {
09910                            mtd->pvt = i;
09911                            memcpy(mtd->buf, buf, res);
09912                            mtd->len = res;
09913                            if (ast_pthread_create_background(&threadid, &attr, mwi_thread, mtd)) {
09914                               ast_log(LOG_WARNING, "Unable to start mwi thread on channel %d\n", i->channel);
09915                               ast_free(mtd);
09916                            }
09917                            i->mwimonitoractive = 1;
09918                         }
09919                      }
09920                   }
09921                   if (i->mwisendactive) {
09922                      mwi_send_process_buffer(i, res);
09923                   }
09924                } else {
09925                   ast_log(LOG_WARNING, "Read failed with %d: %s\n", res, strerror(errno));
09926                }
09927             }
09928             if (pollres & POLLPRI) {
09929                if (i->owner || i->subs[SUB_REAL].owner) {
09930 #ifdef HAVE_PRI
09931                   if (!i->pri)
09932 #endif
09933                      ast_log(LOG_WARNING, "Whoa....  I'm owned but found (%d)...\n", i->subs[SUB_REAL].dfd);
09934                   continue;
09935                }
09936                res = dahdi_get_event(i->subs[SUB_REAL].dfd);
09937                ast_debug(1, "Monitor doohicky got event %s on channel %d\n", event2str(res), i->channel);
09938                /* Don't hold iflock while handling init events */
09939                ast_mutex_unlock(&iflock);
09940                if (0 == i->mwisendactive || 0 == mwi_send_process_event(i, res)) {
09941                   doomed = handle_init_event(i, res);
09942                }
09943                ast_mutex_lock(&iflock);
09944             }
09945          }
09946       }
09947       ast_mutex_unlock(&iflock);
09948    }
09949    /* Never reached */
09950    return NULL;
09951 
09952 }
09953 
09954 static int restart_monitor(void)
09955 {
09956    /* If we're supposed to be stopped -- stay stopped */
09957    if (monitor_thread == AST_PTHREADT_STOP)
09958       return 0;
09959    ast_mutex_lock(&monlock);
09960    if (monitor_thread == pthread_self()) {
09961       ast_mutex_unlock(&monlock);
09962       ast_log(LOG_WARNING, "Cannot kill myself\n");
09963       return -1;
09964    }
09965    if (monitor_thread != AST_PTHREADT_NULL) {
09966       /* Wake up the thread */
09967       pthread_kill(monitor_thread, SIGURG);
09968    } else {
09969       /* Start a new monitor */
09970       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
09971          ast_mutex_unlock(&monlock);
09972          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
09973          return -1;
09974       }
09975    }
09976    ast_mutex_unlock(&monlock);
09977    return 0;
09978 }
09979 
09980 #if defined(HAVE_PRI)
09981 static int pri_resolve_span(int *span, int channel, int offset, struct dahdi_spaninfo *si)
09982 {
09983    int x;
09984    int trunkgroup;
09985    /* Get appropriate trunk group if there is one */
09986    trunkgroup = pris[*span].mastertrunkgroup;
09987    if (trunkgroup) {
09988       /* Select a specific trunk group */
09989       for (x = 0; x < NUM_SPANS; x++) {
09990          if (pris[x].trunkgroup == trunkgroup) {
09991             *span = x;
09992             return 0;
09993          }
09994       }
09995       ast_log(LOG_WARNING, "Channel %d on span %d configured to use nonexistent trunk group %d\n", channel, *span, trunkgroup);
09996       *span = -1;
09997    } else {
09998       if (pris[*span].trunkgroup) {
09999          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is trunk group %d (please use spanmap)\n", *span, pris[*span].trunkgroup);
10000          *span = -1;
10001       } else if (pris[*span].mastertrunkgroup) {
10002          ast_log(LOG_WARNING, "Unable to use span %d implicitly since it is already part of trunk group %d\n", *span, pris[*span].mastertrunkgroup);
10003          *span = -1;
10004       } else {
10005          if (si->totalchans == 31) {
10006             /* E1 */
10007             pris[*span].dchannels[0] = 16 + offset;
10008          } else if (si->totalchans == 24) {
10009             /* T1 or J1 */
10010             pris[*span].dchannels[0] = 24 + offset;
10011          } else if (si->totalchans == 3) {
10012             /* BRI */
10013             pris[*span].dchannels[0] = 3 + offset;
10014          } else {
10015             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);
10016             *span = -1;
10017             return 0;
10018          }
10019          pris[*span].dchanavail[0] |= DCHAN_PROVISIONED;
10020          pris[*span].offset = offset;
10021          pris[*span].span = *span + 1;
10022       }
10023    }
10024    return 0;
10025 }
10026 #endif   /* defined(HAVE_PRI) */
10027 
10028 #if defined(HAVE_PRI)
10029 static int pri_create_trunkgroup(int trunkgroup, int *channels)
10030 {
10031    struct dahdi_spaninfo si;
10032    struct dahdi_params p;
10033    int fd;
10034    int span;
10035    int ospan=0;
10036    int x,y;
10037    for (x = 0; x < NUM_SPANS; x++) {
10038       if (pris[x].trunkgroup == trunkgroup) {
10039          ast_log(LOG_WARNING, "Trunk group %d already exists on span %d, Primary d-channel %d\n", trunkgroup, x + 1, pris[x].dchannels[0]);
10040          return -1;
10041       }
10042    }
10043    for (y = 0; y < NUM_DCHANS; y++) {
10044       if (!channels[y])
10045          break;
10046       memset(&si, 0, sizeof(si));
10047       memset(&p, 0, sizeof(p));
10048       fd = open("/dev/dahdi/channel", O_RDWR);
10049       if (fd < 0) {
10050          ast_log(LOG_WARNING, "Failed to open channel: %s\n", strerror(errno));
10051          return -1;
10052       }
10053       x = channels[y];
10054       if (ioctl(fd, DAHDI_SPECIFY, &x)) {
10055          ast_log(LOG_WARNING, "Failed to specify channel %d: %s\n", channels[y], strerror(errno));
10056          close(fd);
10057          return -1;
10058       }
10059       if (ioctl(fd, DAHDI_GET_PARAMS, &p)) {
10060          ast_log(LOG_WARNING, "Failed to get channel parameters for channel %d: %s\n", channels[y], strerror(errno));
10061          return -1;
10062       }
10063       if (ioctl(fd, DAHDI_SPANSTAT, &si)) {
10064          ast_log(LOG_WARNING, "Failed go get span information on channel %d (span %d): %s\n", channels[y], p.spanno, strerror(errno));
10065          close(fd);
10066          return -1;
10067       }
10068       span = p.spanno - 1;
10069       if (pris[span].trunkgroup) {
10070          ast_log(LOG_WARNING, "Span %d is already provisioned for trunk group %d\n", span + 1, pris[span].trunkgroup);
10071          close(fd);
10072          return -1;
10073       }
10074       if (pris[span].pvts[0]) {
10075          ast_log(LOG_WARNING, "Span %d is already provisioned with channels (implicit PRI maybe?)\n", span + 1);
10076          close(fd);
10077          return -1;
10078       }
10079       if (!y) {
10080          pris[span].trunkgroup = trunkgroup;
10081          pris[span].offset = channels[y] - p.chanpos;
10082          ospan = span;
10083       }
10084       pris[ospan].dchannels[y] = channels[y];
10085       pris[ospan].dchanavail[y] |= DCHAN_PROVISIONED;
10086       pris[span].span = span + 1;
10087       close(fd);
10088    }
10089    return 0;
10090 }
10091 #endif   /* defined(HAVE_PRI) */
10092 
10093 #if defined(HAVE_PRI)
10094 static int pri_create_spanmap(int span, int trunkgroup, int logicalspan)
10095 {
10096    if (pris[span].mastertrunkgroup) {
10097       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);
10098       return -1;
10099    }
10100    pris[span].mastertrunkgroup = trunkgroup;
10101    pris[span].prilogicalspan = logicalspan;
10102    return 0;
10103 }
10104 #endif   /* defined(HAVE_PRI) */
10105 
10106 #if defined(HAVE_SS7)
10107 static unsigned int parse_pointcode(const char *pcstring)
10108 {
10109    unsigned int code1, code2, code3;
10110    int numvals;
10111 
10112    numvals = sscanf(pcstring, "%30d-%30d-%30d", &code1, &code2, &code3);
10113    if (numvals == 1)
10114       return code1;
10115    if (numvals == 3)
10116       return (code1 << 16) | (code2 << 8) | code3;
10117 
10118    return 0;
10119 }
10120 #endif   /* defined(HAVE_SS7) */
10121 
10122 #if defined(HAVE_SS7)
10123 static struct dahdi_ss7 * ss7_resolve_linkset(int linkset)
10124 {
10125    if ((linkset < 0) || (linkset >= NUM_SPANS))
10126       return NULL;
10127    else
10128       return &linksets[linkset - 1];
10129 }
10130 #endif   /* defined(HAVE_SS7) */
10131 
10132 #ifdef HAVE_OPENR2
10133 static void dahdi_r2_destroy_links(void)
10134 {
10135    int i = 0;
10136    if (!r2links) {
10137       return;
10138    }
10139    for (; i < r2links_count; i++) {
10140       if (r2links[i]->r2master != AST_PTHREADT_NULL) {
10141          pthread_cancel(r2links[i]->r2master);
10142          pthread_join(r2links[i]->r2master, NULL);
10143          openr2_context_delete(r2links[i]->protocol_context);
10144       }
10145       ast_free(r2links[i]);
10146    }
10147    ast_free(r2links);
10148    r2links = NULL;
10149    r2links_count = 0;
10150 }
10151 
10152 #define R2_LINK_CAPACITY 10
10153 static struct dahdi_mfcr2 *dahdi_r2_get_link(void)
10154 {
10155    struct dahdi_mfcr2 *new_r2link = NULL;
10156    struct dahdi_mfcr2 **new_r2links = NULL;
10157    /* this function is called just when starting up and no monitor threads have been launched,
10158       no need to lock monitored_count member */
10159    if (!r2links_count || (r2links[r2links_count - 1]->monitored_count == R2_LINK_CAPACITY)) {
10160       new_r2link = ast_calloc(1, sizeof(**r2links));
10161       if (!new_r2link) {
10162          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
10163          return NULL;
10164       }
10165       new_r2links = ast_realloc(r2links, ((r2links_count + 1) * sizeof(*r2links)));
10166       if (!new_r2links) {
10167          ast_log(LOG_ERROR, "Cannot allocate R2 link!\n");
10168          ast_free(new_r2link);
10169          return NULL;
10170       }
10171       r2links = new_r2links;
10172       new_r2link->r2master = AST_PTHREADT_NULL;
10173       r2links[r2links_count] = new_r2link;
10174       r2links_count++;
10175       ast_log(LOG_DEBUG, "Created new R2 link!\n");
10176    }
10177    return r2links[r2links_count - 1];
10178 }
10179 
10180 static int dahdi_r2_set_context(struct dahdi_mfcr2 *r2_link, const struct dahdi_chan_conf *conf)
10181 {
10182    char tmplogdir[] = "/tmp";
10183    char logdir[OR2_MAX_PATH];
10184    int threshold = 0;
10185    int snres = 0;
10186    r2_link->protocol_context = openr2_context_new(NULL, &dahdi_r2_event_iface,
10187          &dahdi_r2_transcode_iface, conf->mfcr2.variant, conf->mfcr2.max_ani,
10188          conf->mfcr2.max_dnis);
10189    if (!r2_link->protocol_context) {
10190       return -1;
10191    }
10192    openr2_context_set_log_level(r2_link->protocol_context, conf->mfcr2.loglevel);
10193    openr2_context_set_ani_first(r2_link->protocol_context, conf->mfcr2.get_ani_first);
10194 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
10195    openr2_context_set_skip_category_request(r2_link->protocol_context, conf->mfcr2.skip_category_request);
10196 #endif
10197    openr2_context_set_mf_threshold(r2_link->protocol_context, threshold);
10198    openr2_context_set_mf_back_timeout(r2_link->protocol_context, conf->mfcr2.mfback_timeout);
10199    openr2_context_set_metering_pulse_timeout(r2_link->protocol_context, conf->mfcr2.metering_pulse_timeout);
10200    openr2_context_set_double_answer(r2_link->protocol_context, conf->mfcr2.double_answer);
10201    openr2_context_set_immediate_accept(r2_link->protocol_context, conf->mfcr2.immediate_accept);
10202    if (ast_strlen_zero(conf->mfcr2.logdir)) {
10203       if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
10204          ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
10205       }
10206    } else {
10207       snres = snprintf(logdir, sizeof(logdir), "%s/%s/%s", ast_config_AST_LOG_DIR, "mfcr2", conf->mfcr2.logdir);
10208       if (snres >= sizeof(logdir)) {
10209          ast_log(LOG_ERROR, "MFC/R2 logging directory truncated, using %s\n", tmplogdir);
10210          if (openr2_context_set_log_directory(r2_link->protocol_context, tmplogdir)) {
10211             ast_log(LOG_ERROR, "Failed setting default MFC/R2 log directory %s\n", tmplogdir);
10212          }
10213       } else {
10214          if (openr2_context_set_log_directory(r2_link->protocol_context, logdir)) {
10215             ast_log(LOG_ERROR, "Failed setting MFC/R2 log directory %s\n", logdir);
10216          }
10217       }
10218    }
10219    if (!ast_strlen_zero(conf->mfcr2.r2proto_file)) {
10220       if (openr2_context_configure_from_advanced_file(r2_link->protocol_context, conf->mfcr2.r2proto_file)) {
10221          ast_log(LOG_ERROR, "Failed to configure r2context from advanced configuration file %s\n", conf->mfcr2.r2proto_file);
10222       }
10223    }
10224    r2_link->monitored_count = 0;
10225    return 0;
10226 }
10227 #endif
10228 
10229 /* converts a DAHDI sigtype to signalling as can be configured from
10230  * chan_dahdi.conf.
10231  * While both have basically the same values, this will later be the
10232  * place to add filters and sanity checks
10233  */
10234 static int sigtype_to_signalling(int sigtype)
10235 {
10236    return sigtype;
10237 }
10238 
10239 static struct dahdi_pvt *mkintf(int channel, const struct dahdi_chan_conf *conf, struct dahdi_pri *pri, int reloading)
10240 {
10241    /* Make a dahdi_pvt structure for this interface (or CRV if "pri" is specified) */
10242    struct dahdi_pvt *tmp = NULL, *tmp2, *prev = NULL;
10243    char fn[80];
10244    struct dahdi_bufferinfo bi;
10245 
10246    int res;
10247    int span = 0;
10248    int here = 0;
10249    int x;
10250    struct dahdi_pvt **wlist;
10251    struct dahdi_pvt **wend;
10252    struct dahdi_params p;
10253 
10254    wlist = &iflist;
10255    wend = &ifend;
10256 
10257 #ifdef HAVE_PRI
10258    if (pri) {
10259       wlist = &pri->crvs;
10260       wend = &pri->crvend;
10261    }
10262 #endif
10263 
10264    tmp2 = *wlist;
10265    prev = NULL;
10266 
10267    while (tmp2) {
10268       if (!tmp2->destroy) {
10269          if (tmp2->channel == channel) {
10270             tmp = tmp2;
10271             here = 1;
10272             break;
10273          }
10274          if (tmp2->channel > channel) {
10275             break;
10276          }
10277       }
10278       prev = tmp2;
10279       tmp2 = tmp2->next;
10280    }
10281 
10282    if (!here && reloading != 1) {
10283       if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
10284          if (tmp)
10285             free(tmp);
10286          return NULL;
10287       }
10288       ast_mutex_init(&tmp->lock);
10289       ifcount++;
10290       for (x = 0; x < 3; x++)
10291          tmp->subs[x].dfd = -1;
10292       tmp->channel = channel;
10293       tmp->priindication_oob = conf->chan.priindication_oob;
10294    }
10295 
10296    if (tmp) {
10297       int chan_sig = conf->chan.sig;
10298       if (!here) {
10299          if ((channel != CHAN_PSEUDO) && !pri) {
10300             int count = 0;
10301             snprintf(fn, sizeof(fn), "%d", channel);
10302             /* Open non-blocking */
10303             tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
10304             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 */
10305                usleep(1);
10306                tmp->subs[SUB_REAL].dfd = dahdi_open(fn);
10307                count++;
10308             }
10309             /* Allocate a DAHDI structure */
10310             if (tmp->subs[SUB_REAL].dfd < 0) {
10311                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);
10312                destroy_dahdi_pvt(&tmp);
10313                return NULL;
10314             }
10315             memset(&p, 0, sizeof(p));
10316             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
10317             if (res < 0) {
10318                ast_log(LOG_ERROR, "Unable to get parameters: %s\n", strerror(errno));
10319                destroy_dahdi_pvt(&tmp);
10320                return NULL;
10321             }
10322             if (conf->is_sig_auto)
10323                chan_sig = sigtype_to_signalling(p.sigtype);
10324             if (p.sigtype != (chan_sig & 0x3ffff)) {
10325                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));
10326                destroy_dahdi_pvt(&tmp);
10327                return NULL;
10328             }
10329             tmp->law = p.curlaw;
10330             tmp->span = p.spanno;
10331             span = p.spanno - 1;
10332          } else {
10333             if (channel == CHAN_PSEUDO)
10334                chan_sig = 0;
10335             else if ((chan_sig != SIG_FXOKS) && (chan_sig != SIG_FXSKS)) {
10336                ast_log(LOG_ERROR, "CRV's must use FXO/FXS Kewl Start (fxo_ks/fxs_ks) signalling only.\n");
10337                return NULL;
10338             }
10339          }
10340          tmp->outsigmod = conf->chan.outsigmod;
10341 
10342 #ifdef HAVE_SS7
10343          if (chan_sig == SIG_SS7) {
10344             struct dahdi_ss7 *ss7;
10345             int clear = 0;
10346             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &clear)) {
10347                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
10348                destroy_dahdi_pvt(&tmp);
10349                return NULL;
10350             }
10351 
10352             ss7 = ss7_resolve_linkset(cur_linkset);
10353             if (!ss7) {
10354                ast_log(LOG_ERROR, "Unable to find linkset %d\n", cur_linkset);
10355                destroy_dahdi_pvt(&tmp);
10356                return NULL;
10357             }
10358             if (cur_cicbeginswith < 0) {
10359                ast_log(LOG_ERROR, "Need to set cicbeginswith for the channels!\n");
10360                destroy_dahdi_pvt(&tmp);
10361                return NULL;
10362             }
10363 
10364             tmp->cic = cur_cicbeginswith++;
10365 
10366             /* DB: Add CIC's DPC information */
10367             tmp->dpc = cur_defaultdpc;
10368 
10369             tmp->ss7 = ss7;
10370             tmp->ss7call = NULL;
10371             ss7->pvts[ss7->numchans++] = tmp;
10372 
10373             ast_copy_string(ss7->internationalprefix, conf->ss7.internationalprefix, sizeof(ss7->internationalprefix));
10374             ast_copy_string(ss7->nationalprefix, conf->ss7.nationalprefix, sizeof(ss7->nationalprefix));
10375             ast_copy_string(ss7->subscriberprefix, conf->ss7.subscriberprefix, sizeof(ss7->subscriberprefix));
10376             ast_copy_string(ss7->unknownprefix, conf->ss7.unknownprefix, sizeof(ss7->unknownprefix));
10377 
10378             ss7->called_nai = conf->ss7.called_nai;
10379             ss7->calling_nai = conf->ss7.calling_nai;
10380          }
10381 #endif
10382 #ifdef HAVE_OPENR2
10383          if (chan_sig == SIG_MFCR2 && reloading != 1) {
10384             struct dahdi_mfcr2 *r2_link;
10385             r2_link = dahdi_r2_get_link();
10386             if (!r2_link) {
10387                ast_log(LOG_WARNING, "Cannot get another R2 DAHDI context!\n");
10388                destroy_dahdi_pvt(&tmp);
10389                return NULL;
10390             }
10391             if (!r2_link->protocol_context && dahdi_r2_set_context(r2_link, conf)) {
10392                ast_log(LOG_ERROR, "Cannot create OpenR2 protocol context.\n");
10393                destroy_dahdi_pvt(&tmp);
10394                return NULL;
10395             }
10396             if (r2_link->numchans == (sizeof(r2_link->pvts)/sizeof(r2_link->pvts[0]))) {
10397                ast_log(LOG_ERROR, "Cannot add more channels to this link!\n");
10398                destroy_dahdi_pvt(&tmp);
10399                return NULL;
10400             }
10401             r2_link->pvts[r2_link->numchans++] = tmp;
10402             tmp->r2chan = openr2_chan_new_from_fd(r2_link->protocol_context,
10403                                         tmp->subs[SUB_REAL].dfd,
10404                                         NULL, NULL);
10405             if (!tmp->r2chan) {
10406                openr2_liberr_t err = openr2_context_get_last_error(r2_link->protocol_context);
10407                ast_log(LOG_ERROR, "Cannot create OpenR2 channel: %s\n", openr2_context_error_string(err));
10408                destroy_dahdi_pvt(&tmp);
10409                return NULL;
10410             }
10411             tmp->mfcr2 = r2_link;
10412             if (conf->mfcr2.call_files) {
10413                openr2_chan_enable_call_files(tmp->r2chan);
10414             }
10415             openr2_chan_set_client_data(tmp->r2chan, tmp);
10416             /* cast seems to be needed to get rid of the annoying warning regarding format attribute  */
10417             openr2_chan_set_logging_func(tmp->r2chan, (openr2_logging_func_t)dahdi_r2_on_chan_log);
10418             openr2_chan_set_log_level(tmp->r2chan, conf->mfcr2.loglevel);
10419             tmp->mfcr2_category = conf->mfcr2.category;
10420             tmp->mfcr2_charge_calls = conf->mfcr2.charge_calls;
10421             tmp->mfcr2_allow_collect_calls = conf->mfcr2.allow_collect_calls;
10422             tmp->mfcr2_forced_release = conf->mfcr2.forced_release;
10423             tmp->mfcr2_accept_on_offer = conf->mfcr2.accept_on_offer;
10424             tmp->mfcr2call = 0;
10425             tmp->mfcr2_dnis_index = 0;
10426             tmp->mfcr2_ani_index = 0;
10427             r2_link->monitored_count++;
10428          }
10429 #endif
10430 #ifdef HAVE_PRI
10431          if ((chan_sig == SIG_PRI) || (chan_sig == SIG_BRI) || (chan_sig == SIG_BRI_PTMP) || (chan_sig == SIG_GR303FXOKS) || (chan_sig == SIG_GR303FXSKS)) {
10432             int offset;
10433             int myswitchtype;
10434             int matchesdchan;
10435             int x,y;
10436             offset = 0;
10437             if (((chan_sig == SIG_PRI) || (chan_sig == SIG_BRI) || (chan_sig == SIG_BRI_PTMP))
10438                   && ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &offset)) {
10439                ast_log(LOG_ERROR, "Unable to set clear mode on clear channel %d of span %d: %s\n", channel, p.spanno, strerror(errno));
10440                destroy_dahdi_pvt(&tmp);
10441                return NULL;
10442             }
10443             if (span >= NUM_SPANS) {
10444                ast_log(LOG_ERROR, "Channel %d does not lie on a span I know of (%d)\n", channel, span);
10445                destroy_dahdi_pvt(&tmp);
10446                return NULL;
10447             } else {
10448                struct dahdi_spaninfo si;
10449                si.spanno = 0;
10450                if (ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SPANSTAT,&si) == -1) {
10451                   ast_log(LOG_ERROR, "Unable to get span status: %s\n", strerror(errno));
10452                   destroy_dahdi_pvt(&tmp);
10453                   return NULL;
10454                }
10455                /* Store the logical span first based upon the real span */
10456                tmp->logicalspan = pris[span].prilogicalspan;
10457                pri_resolve_span(&span, channel, (channel - p.chanpos), &si);
10458                if (span < 0) {
10459                   ast_log(LOG_WARNING, "Channel %d: Unable to find locate channel/trunk group!\n", channel);
10460                   destroy_dahdi_pvt(&tmp);
10461                   return NULL;
10462                }
10463                if ((chan_sig == SIG_PRI) ||
10464                      (chan_sig == SIG_BRI) ||
10465                      (chan_sig == SIG_BRI_PTMP))
10466                   myswitchtype = conf->pri.switchtype;
10467                else
10468                   myswitchtype = PRI_SWITCH_GR303_TMC;
10469                /* Make sure this isn't a d-channel */
10470                matchesdchan=0;
10471                for (x = 0; x < NUM_SPANS; x++) {
10472                   for (y = 0; y < NUM_DCHANS; y++) {
10473                      if (pris[x].dchannels[y] == tmp->channel) {
10474                         matchesdchan = 1;
10475                         break;
10476                      }
10477                   }
10478                }
10479                offset = p.chanpos;
10480                if (!matchesdchan) {
10481                   if (pris[span].nodetype && (pris[span].nodetype != conf->pri.nodetype)) {
10482                      ast_log(LOG_ERROR, "Span %d is already a %s node\n", span + 1, pri_node2str(pris[span].nodetype));
10483                      destroy_dahdi_pvt(&tmp);
10484                      return NULL;
10485                   }
10486                   if (pris[span].switchtype && (pris[span].switchtype != myswitchtype)) {
10487                      ast_log(LOG_ERROR, "Span %d is already a %s switch\n", span + 1, pri_switch2str(pris[span].switchtype));
10488                      destroy_dahdi_pvt(&tmp);
10489                      return NULL;
10490                   }
10491                   if ((pris[span].dialplan) && (pris[span].dialplan != conf->pri.dialplan)) {
10492                      ast_log(LOG_ERROR, "Span %d is already a %s dialing plan\n", span + 1, dialplan2str(pris[span].dialplan));
10493                      destroy_dahdi_pvt(&tmp);
10494                      return NULL;
10495                   }
10496                   if (!ast_strlen_zero(pris[span].idledial) && strcmp(pris[span].idledial, conf->pri.idledial)) {
10497                      ast_log(LOG_ERROR, "Span %d already has idledial '%s'.\n", span + 1, conf->pri.idledial);
10498                      destroy_dahdi_pvt(&tmp);
10499                      return NULL;
10500                   }
10501                   if (!ast_strlen_zero(pris[span].idleext) && strcmp(pris[span].idleext, conf->pri.idleext)) {
10502                      ast_log(LOG_ERROR, "Span %d already has idleext '%s'.\n", span + 1, conf->pri.idleext);
10503                      destroy_dahdi_pvt(&tmp);
10504                      return NULL;
10505                   }
10506                   if (pris[span].minunused && (pris[span].minunused != conf->pri.minunused)) {
10507                      ast_log(LOG_ERROR, "Span %d already has minunused of %d.\n", span + 1, conf->pri.minunused);
10508                      destroy_dahdi_pvt(&tmp);
10509                      return NULL;
10510                   }
10511                   if (pris[span].minidle && (pris[span].minidle != conf->pri.minidle)) {
10512                      ast_log(LOG_ERROR, "Span %d already has minidle of %d.\n", span + 1, conf->pri.minidle);
10513                      destroy_dahdi_pvt(&tmp);
10514                      return NULL;
10515                   }
10516                   if (pris[span].numchans >= MAX_CHANNELS) {
10517                      ast_log(LOG_ERROR, "Unable to add channel %d: Too many channels in trunk group %d!\n", channel,
10518                         pris[span].trunkgroup);
10519                      destroy_dahdi_pvt(&tmp);
10520                      return NULL;
10521                   }
10522 
10523                   pris[span].sig = chan_sig;
10524                   pris[span].nodetype = conf->pri.nodetype;
10525                   pris[span].switchtype = myswitchtype;
10526                   pris[span].nsf = conf->pri.nsf;
10527                   pris[span].dialplan = conf->pri.dialplan;
10528                   pris[span].localdialplan = conf->pri.localdialplan;
10529                   pris[span].pvts[pris[span].numchans++] = tmp;
10530                   pris[span].minunused = conf->pri.minunused;
10531                   pris[span].minidle = conf->pri.minidle;
10532                   pris[span].overlapdial = conf->pri.overlapdial;
10533                   pris[span].qsigchannelmapping = conf->pri.qsigchannelmapping;
10534                   pris[span].discardremoteholdretrieval = conf->pri.discardremoteholdretrieval;
10535 #ifdef HAVE_PRI_INBANDDISCONNECT
10536                   pris[span].inbanddisconnect = conf->pri.inbanddisconnect;
10537 #endif
10538                   pris[span].facilityenable = conf->pri.facilityenable;
10539                   ast_copy_string(pris[span].idledial, conf->pri.idledial, sizeof(pris[span].idledial));
10540                   ast_copy_string(pris[span].idleext, conf->pri.idleext, sizeof(pris[span].idleext));
10541                   ast_copy_string(pris[span].internationalprefix, conf->pri.internationalprefix, sizeof(pris[span].internationalprefix));
10542                   ast_copy_string(pris[span].nationalprefix, conf->pri.nationalprefix, sizeof(pris[span].nationalprefix));
10543                   ast_copy_string(pris[span].localprefix, conf->pri.localprefix, sizeof(pris[span].localprefix));
10544                   ast_copy_string(pris[span].privateprefix, conf->pri.privateprefix, sizeof(pris[span].privateprefix));
10545                   ast_copy_string(pris[span].unknownprefix, conf->pri.unknownprefix, sizeof(pris[span].unknownprefix));
10546                   pris[span].resetinterval = conf->pri.resetinterval;
10547 
10548                   tmp->pri = &pris[span];
10549                   tmp->prioffset = offset;
10550                   tmp->call = NULL;
10551 
10552                   tmp->priexclusive = conf->chan.priexclusive;
10553                } else {
10554                   ast_log(LOG_ERROR, "Channel %d is reserved for D-channel.\n", offset);
10555                   destroy_dahdi_pvt(&tmp);
10556                   return NULL;
10557                }
10558             }
10559          } else {
10560             tmp->prioffset = 0;
10561          }
10562 #endif
10563       } else {
10564          chan_sig = tmp->sig;
10565          if (tmp->subs[SUB_REAL].dfd > -1) {
10566             memset(&p, 0, sizeof(p));
10567             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
10568          }
10569       }
10570       /* Adjust starttime on loopstart and kewlstart trunks to reasonable values */
10571       switch (chan_sig) {
10572       case SIG_FXSKS:
10573       case SIG_FXSLS:
10574       case SIG_EM:
10575       case SIG_EM_E1:
10576       case SIG_EMWINK:
10577       case SIG_FEATD:
10578       case SIG_FEATDMF:
10579       case SIG_FEATDMF_TA:
10580       case SIG_FEATB:
10581       case SIG_E911:
10582       case SIG_SF:
10583       case SIG_SFWINK:
10584       case SIG_FGC_CAMA:
10585       case SIG_FGC_CAMAMF:
10586       case SIG_SF_FEATD:
10587       case SIG_SF_FEATDMF:
10588       case SIG_SF_FEATB:
10589          p.starttime = 250;
10590          break;
10591       }
10592 
10593       if (tmp->radio) {
10594          /* XXX Waiting to hear back from Jim if these should be adjustable XXX */
10595          p.channo = channel;
10596          p.rxwinktime = 1;
10597          p.rxflashtime = 1;
10598          p.starttime = 1;
10599          p.debouncetime = 5;
10600       }
10601       if (!tmp->radio) {
10602          p.channo = channel;
10603          /* Override timing settings based on config file */
10604          if (conf->timing.prewinktime >= 0)
10605             p.prewinktime = conf->timing.prewinktime;
10606          if (conf->timing.preflashtime >= 0)
10607             p.preflashtime = conf->timing.preflashtime;
10608          if (conf->timing.winktime >= 0)
10609             p.winktime = conf->timing.winktime;
10610          if (conf->timing.flashtime >= 0)
10611             p.flashtime = conf->timing.flashtime;
10612          if (conf->timing.starttime >= 0)
10613             p.starttime = conf->timing.starttime;
10614          if (conf->timing.rxwinktime >= 0)
10615             p.rxwinktime = conf->timing.rxwinktime;
10616          if (conf->timing.rxflashtime >= 0)
10617             p.rxflashtime = conf->timing.rxflashtime;
10618          if (conf->timing.debouncetime >= 0)
10619             p.debouncetime = conf->timing.debouncetime;
10620       }
10621 
10622       /* dont set parms on a pseudo-channel (or CRV) */
10623       if (tmp->subs[SUB_REAL].dfd >= 0)
10624       {
10625          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_PARAMS, &p);
10626          if (res < 0) {
10627             ast_log(LOG_ERROR, "Unable to set parameters: %s\n", strerror(errno));
10628             destroy_dahdi_pvt(&tmp);
10629             return NULL;
10630          }
10631       }
10632 #if 1
10633       if (!here && (tmp->subs[SUB_REAL].dfd > -1)) {
10634          memset(&bi, 0, sizeof(bi));
10635          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
10636          if (!res) {
10637             bi.txbufpolicy = conf->chan.buf_policy;
10638             bi.rxbufpolicy = conf->chan.buf_policy;
10639             bi.numbufs = conf->chan.buf_no;
10640             res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
10641             if (res < 0) {
10642                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", channel, strerror(errno));
10643             }
10644          } else {
10645             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", channel, strerror(errno));
10646          }
10647          tmp->buf_policy = conf->chan.buf_policy;
10648          tmp->buf_no = conf->chan.buf_no;
10649          tmp->usefaxbuffers = conf->chan.usefaxbuffers;
10650          tmp->faxbuf_policy = conf->chan.faxbuf_policy;
10651          tmp->faxbuf_no = conf->chan.faxbuf_no;
10652          /* This is not as gnarly as it may first appear.  If the ioctl above failed, we'd be setting
10653           * tmp->bufsize to zero which would cause subsequent faxbuffer-related ioctl calls to fail.
10654           * The reason the ioctl call above failed should to be determined before worrying about the
10655           * faxbuffer-related ioctl calls */
10656          tmp->bufsize = bi.bufsize;
10657       }
10658 #endif
10659       tmp->immediate = conf->chan.immediate;
10660       tmp->transfertobusy = conf->chan.transfertobusy;
10661       if (chan_sig & __DAHDI_SIG_FXS) {
10662          tmp->mwimonitor_fsk = conf->chan.mwimonitor_fsk;
10663          tmp->mwimonitor_neon = conf->chan.mwimonitor_neon;
10664          tmp->mwimonitor_rpas = conf->chan.mwimonitor_rpas;
10665       }
10666       tmp->sig = chan_sig;
10667       tmp->ringt_base = ringt_base;
10668       tmp->firstradio = 0;
10669       if ((chan_sig == SIG_FXOKS) || (chan_sig == SIG_FXOLS) || (chan_sig == SIG_FXOGS))
10670          tmp->permcallwaiting = conf->chan.callwaiting;
10671       else
10672          tmp->permcallwaiting = 0;
10673       /* Flag to destroy the channel must be cleared on new mkif.  Part of changes for reload to work */
10674       tmp->destroy = 0;
10675       tmp->drings = conf->chan.drings;
10676 
10677       /* 10 is a nice default. */
10678       if (tmp->drings.ringnum[0].range == 0)
10679          tmp->drings.ringnum[0].range = 10;
10680       if (tmp->drings.ringnum[1].range == 0)
10681          tmp->drings.ringnum[1].range = 10;
10682       if (tmp->drings.ringnum[2].range == 0)
10683          tmp->drings.ringnum[2].range = 10;
10684 
10685       tmp->usedistinctiveringdetection = usedistinctiveringdetection;
10686       tmp->callwaitingcallerid = conf->chan.callwaitingcallerid;
10687       tmp->threewaycalling = conf->chan.threewaycalling;
10688       tmp->adsi = conf->chan.adsi;
10689       tmp->use_smdi = conf->chan.use_smdi;
10690       tmp->permhidecallerid = conf->chan.hidecallerid;
10691       tmp->hidecalleridname = conf->chan.hidecalleridname;
10692       tmp->callreturn = conf->chan.callreturn;
10693       tmp->echocancel = conf->chan.echocancel;
10694       tmp->echotraining = conf->chan.echotraining;
10695       tmp->pulse = conf->chan.pulse;
10696       if (tmp->echocancel.head.tap_length) {
10697          tmp->echocanbridged = conf->chan.echocanbridged;
10698       } else {
10699          if (conf->chan.echocanbridged)
10700             ast_log(LOG_NOTICE, "echocancelwhenbridged requires echocancel to be enabled; ignoring\n");
10701          tmp->echocanbridged = 0;
10702       }
10703       tmp->busydetect = conf->chan.busydetect;
10704       tmp->busycount = conf->chan.busycount;
10705       tmp->busy_tonelength = conf->chan.busy_tonelength;
10706       tmp->busy_quietlength = conf->chan.busy_quietlength;
10707       tmp->callprogress = conf->chan.callprogress;
10708       tmp->waitfordialtone = conf->chan.waitfordialtone;
10709       tmp->cancallforward = conf->chan.cancallforward;
10710       tmp->dtmfrelax = conf->chan.dtmfrelax;
10711       tmp->callwaiting = tmp->permcallwaiting;
10712       tmp->hidecallerid = tmp->permhidecallerid;
10713       tmp->channel = channel;
10714       tmp->stripmsd = conf->chan.stripmsd;
10715       tmp->use_callerid = conf->chan.use_callerid;
10716       tmp->cid_signalling = conf->chan.cid_signalling;
10717       tmp->cid_start = conf->chan.cid_start;
10718       tmp->dahditrcallerid = conf->chan.dahditrcallerid;
10719       tmp->restrictcid = conf->chan.restrictcid;
10720       tmp->use_callingpres = conf->chan.use_callingpres;
10721       if (tmp->usedistinctiveringdetection) {
10722          if (!tmp->use_callerid) {
10723             ast_log(LOG_NOTICE, "Distinctive Ring detect requires 'usecallerid' be on\n");
10724             tmp->use_callerid = 1;
10725          }
10726       }
10727 
10728       if (tmp->cid_signalling == CID_SIG_SMDI) {
10729          if (!tmp->use_smdi) {
10730             ast_log(LOG_WARNING, "SMDI callerid requires SMDI to be enabled, enabling...\n");
10731             tmp->use_smdi = 1;
10732          }
10733       }
10734       if (tmp->use_smdi) {
10735          tmp->smdi_iface = ast_smdi_interface_find(conf->smdi_port);
10736          if (!(tmp->smdi_iface)) {
10737             ast_log(LOG_ERROR, "Invalid SMDI port specfied, disabling SMDI support\n");
10738             tmp->use_smdi = 0;
10739          }
10740       }
10741 
10742       ast_copy_string(tmp->accountcode, conf->chan.accountcode, sizeof(tmp->accountcode));
10743       tmp->amaflags = conf->chan.amaflags;
10744       if (!here) {
10745          tmp->confno = -1;
10746          tmp->propconfno = -1;
10747       }
10748       tmp->canpark = conf->chan.canpark;
10749       tmp->transfer = conf->chan.transfer;
10750       ast_copy_string(tmp->defcontext,conf->chan.context,sizeof(tmp->defcontext));
10751       ast_copy_string(tmp->language, conf->chan.language, sizeof(tmp->language));
10752       ast_copy_string(tmp->mohinterpret, conf->chan.mohinterpret, sizeof(tmp->mohinterpret));
10753       ast_copy_string(tmp->mohsuggest, conf->chan.mohsuggest, sizeof(tmp->mohsuggest));
10754       ast_copy_string(tmp->context, conf->chan.context, sizeof(tmp->context));
10755       ast_copy_string(tmp->parkinglot, conf->chan.parkinglot, sizeof(tmp->parkinglot));
10756       tmp->cid_ton = 0;
10757       switch (tmp->sig) {
10758       case SIG_PRI:
10759       case SIG_BRI:
10760       case SIG_BRI_PTMP:
10761       case SIG_SS7:
10762       case SIG_MFCR2:
10763          tmp->cid_num[0] = '\0';
10764          tmp->cid_name[0] = '\0';
10765          break;
10766       default:
10767          ast_copy_string(tmp->cid_num, conf->chan.cid_num, sizeof(tmp->cid_num));
10768          ast_copy_string(tmp->cid_name, conf->chan.cid_name, sizeof(tmp->cid_name));
10769          break;
10770       }
10771       ast_copy_string(tmp->mailbox, conf->chan.mailbox, sizeof(tmp->mailbox));
10772       if (channel != CHAN_PSEUDO && !ast_strlen_zero(tmp->mailbox)) {
10773          char *mailbox, *context;
10774          mailbox = context = ast_strdupa(tmp->mailbox);
10775          strsep(&context, "@");
10776          if (ast_strlen_zero(context))
10777             context = "default";
10778          tmp->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, NULL,
10779             AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
10780             AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
10781             AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
10782             AST_EVENT_IE_END);
10783       }
10784       tmp->msgstate = -1;
10785 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10786       tmp->mwisend_setting = conf->chan.mwisend_setting;
10787       tmp->mwisend_fsk  = conf->chan.mwisend_fsk;
10788       tmp->mwisend_rpas = conf->chan.mwisend_rpas;
10789 #endif
10790       if (chan_sig & __DAHDI_SIG_FXO) {
10791          memset(&p, 0, sizeof(p));
10792          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &p);
10793          if (!res) {
10794             tmp->fxsoffhookstate = p.rxisoffhook;
10795          }
10796 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
10797          res = ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_VMWI_CONFIG, &tmp->mwisend_setting);
10798 #endif
10799       }
10800       tmp->onhooktime = time(NULL);
10801       tmp->group = conf->chan.group;
10802       tmp->callgroup = conf->chan.callgroup;
10803       tmp->pickupgroup= conf->chan.pickupgroup;
10804       if (conf->chan.vars) {
10805          struct ast_variable *v, *tmpvar;
10806                    for (v = conf->chan.vars ; v ; v = v->next) {
10807                          if ((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
10808                                   tmpvar->next = tmp->vars;
10809                                    tmp->vars = tmpvar;
10810                            }
10811                   }
10812       }
10813       tmp->cid_rxgain = conf->chan.cid_rxgain;
10814       tmp->rxgain = conf->chan.rxgain;
10815       tmp->txgain = conf->chan.txgain;
10816       tmp->tonezone = conf->chan.tonezone;
10817       if (tmp->subs[SUB_REAL].dfd > -1) {
10818          set_actual_gain(tmp->subs[SUB_REAL].dfd, 0, tmp->rxgain, tmp->txgain, tmp->law);
10819          if (tmp->dsp)
10820             ast_dsp_set_digitmode(tmp->dsp, DSP_DIGITMODE_DTMF | tmp->dtmfrelax);
10821          update_conf(tmp);
10822          if (!here) {
10823             if ((chan_sig != SIG_BRI) && (chan_sig != SIG_BRI_PTMP) && (chan_sig != SIG_PRI)
10824                 && (chan_sig != SIG_SS7) && (chan_sig != SIG_MFCR2))
10825                /* Hang it up to be sure it's good */
10826                dahdi_set_hook(tmp->subs[SUB_REAL].dfd, DAHDI_ONHOOK);
10827          }
10828          ioctl(tmp->subs[SUB_REAL].dfd,DAHDI_SETTONEZONE,&tmp->tonezone);
10829 #ifdef HAVE_PRI
10830          /* the dchannel is down so put the channel in alarm */
10831          if (tmp->pri && !pri_is_up(tmp->pri))
10832             tmp->inalarm = 1;
10833 #endif
10834          if ((res = get_alarms(tmp)) != DAHDI_ALARM_NONE) {
10835             tmp->inalarm = 1;
10836             handle_alarms(tmp, res);
10837          }
10838       }
10839 
10840       tmp->polarityonanswerdelay = conf->chan.polarityonanswerdelay;
10841       tmp->answeronpolarityswitch = conf->chan.answeronpolarityswitch;
10842       tmp->hanguponpolarityswitch = conf->chan.hanguponpolarityswitch;
10843       tmp->sendcalleridafter = conf->chan.sendcalleridafter;
10844       if (!here) {
10845          tmp->locallyblocked = tmp->remotelyblocked = 0;
10846          if ((chan_sig == SIG_PRI) || (chan_sig == SIG_BRI) || (chan_sig == SIG_BRI_PTMP) || (chan_sig == SIG_SS7))
10847             tmp->inservice = 0;
10848          else /* We default to in service on protocols that don't have a reset */
10849             tmp->inservice = 1;
10850       }
10851    }
10852    if (tmp && !here) {
10853       /* nothing on the iflist */
10854       if (!*wlist) {
10855          *wlist = tmp;
10856          tmp->prev = NULL;
10857          tmp->next = NULL;
10858          *wend = tmp;
10859       } else {
10860          /* at least one member on the iflist */
10861          struct dahdi_pvt *working = *wlist;
10862 
10863          /* check if we maybe have to put it on the begining */
10864          if (working->channel > tmp->channel) {
10865             tmp->next = *wlist;
10866             tmp->prev = NULL;
10867             (*wlist)->prev = tmp;
10868             *wlist = tmp;
10869          } else {
10870          /* go through all the members and put the member in the right place */
10871             while (working) {
10872                /* in the middle */
10873                if (working->next) {
10874                   if (working->channel < tmp->channel && working->next->channel > tmp->channel) {
10875                      tmp->next = working->next;
10876                      tmp->prev = working;
10877                      working->next->prev = tmp;
10878                      working->next = tmp;
10879                      break;
10880                   }
10881                } else {
10882                /* the last */
10883                   if (working->channel < tmp->channel) {
10884                      working->next = tmp;
10885                      tmp->next = NULL;
10886                      tmp->prev = working;
10887                      *wend = tmp;
10888                      break;
10889                   }
10890                }
10891                working = working->next;
10892             }
10893          }
10894       }
10895    }
10896    return tmp;
10897 }
10898 
10899 static inline int available(struct dahdi_pvt *p, int channelmatch, ast_group_t groupmatch, int *busy, int *channelmatched, int *groupmatched)
10900 {
10901    int res;
10902    struct dahdi_params par;
10903 
10904    /* First, check group matching */
10905    if (groupmatch) {
10906       if ((p->group & groupmatch) != groupmatch)
10907          return 0;
10908       *groupmatched = 1;
10909    }
10910    /* Check to see if we have a channel match */
10911    if (channelmatch != -1) {
10912       if (p->channel != channelmatch)
10913          return 0;
10914       *channelmatched = 1;
10915    }
10916    /* We're at least busy at this point */
10917    if (busy) {
10918       if ((p->sig == SIG_FXOKS) || (p->sig == SIG_FXOLS) || (p->sig == SIG_FXOGS))
10919          *busy = 1;
10920    }
10921    /* If do not disturb, definitely not */
10922    if (p->dnd)
10923       return 0;
10924    /* If guard time, definitely not */
10925    if (p->guardtime && (time(NULL) < p->guardtime))
10926       return 0;
10927 
10928    if (p->locallyblocked || p->remotelyblocked)
10929       return 0;
10930 
10931    /* If no owner definitely available */
10932    if (!p->owner) {
10933 #ifdef HAVE_PRI
10934       /* Trust PRI */
10935       if (p->pri) {
10936          if (p->resetting || p->call)
10937             return 0;
10938          else
10939             return 1;
10940       }
10941 #endif
10942 #ifdef HAVE_SS7
10943       /* Trust SS7 */
10944       if (p->ss7) {
10945          if (p->ss7call)
10946             return 0;
10947          else
10948             return 1;
10949       }
10950 #endif
10951 #ifdef HAVE_OPENR2
10952       /* Trust MFC/R2 */
10953       if (p->mfcr2) {
10954          if (p->mfcr2call)
10955             return 0;
10956          else
10957             return 1;
10958       }
10959 #endif
10960 
10961       /* Trust hook state */
10962       if (p->sig && !(p->radio || (p->oprmode < 0)))
10963       {
10964          /* Check hook state */
10965          if (p->subs[SUB_REAL].dfd > -1) {
10966             memset(&par, 0, sizeof(par));
10967             res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
10968          } else {
10969             /* Assume not off hook on CVRS */
10970             res = 0;
10971             par.rxisoffhook = 0;
10972          }
10973 
10974          if (res) {
10975             ast_log(LOG_WARNING, "Unable to check hook state on channel %d: %s\n", p->channel, strerror(errno));
10976          }
10977          else if ((p->sig != SIG_FXSKS) && (p->sig != SIG_FXSGS) && (p->sig != SIG_FXSLS)) {
10978             if (par.rxisoffhook) {
10979                ast_debug(1, "Channel %d off hook, can't use\n", p->channel);
10980                /* Not available when the other end is off hook */
10981                return 0;
10982             }
10983          }
10984 #ifdef DAHDI_CHECK_HOOKSTATE
10985          } else { /* FXO channel case (SIG_FXS--) */
10986             /* Channel bank (using CAS), "onhook" does not necessarily means out of service, so return 1 */
10987             if (par.rxbits > -1)
10988                return 1;
10989             /* TDM FXO card, "onhook" means out of service (no battery on the line) */
10990             if (par.rxisoffhook)
10991                return 1;
10992             else
10993                return 0;
10994 #endif
10995       }
10996 
10997       return 1;
10998    }
10999 
11000    /* If it's not an FXO, forget about call wait */
11001    if ((p->sig != SIG_FXOKS) && (p->sig != SIG_FXOLS) && (p->sig != SIG_FXOGS))
11002       return 0;
11003 
11004    if (!p->callwaiting) {
11005       /* If they don't have call waiting enabled, then for sure they're unavailable at this point */
11006       return 0;
11007    }
11008 
11009    if (p->subs[SUB_CALLWAIT].dfd > -1) {
11010       /* If there is already a call waiting call, then we can't take a second one */
11011       return 0;
11012    }
11013 
11014    if ((p->owner->_state != AST_STATE_UP) &&
11015       ((p->owner->_state != AST_STATE_RINGING) || p->outgoing)) {
11016       /* If the current call is not up, then don't allow the call */
11017       return 0;
11018    }
11019    if ((p->subs[SUB_THREEWAY].owner) && (!p->subs[SUB_THREEWAY].inthreeway)) {
11020       /* Can't take a call wait when the three way calling hasn't been merged yet. */
11021       return 0;
11022    }
11023    /* We're cool */
11024    return 1;
11025 }
11026 
11027 /* This function can *ONLY* be used for copying pseudo (CHAN_PSEUDO) private
11028    structures; it makes no attempt to safely copy regular channel private
11029    structures that might contain reference-counted object pointers and other
11030    scary bits
11031 */
11032 static struct dahdi_pvt *duplicate_pseudo(struct dahdi_pvt *src)
11033 {
11034    struct dahdi_pvt *p;
11035    struct dahdi_bufferinfo bi;
11036    int res;
11037 
11038    if ((p = ast_malloc(sizeof(*p)))) {
11039       memcpy(p, src, sizeof(struct dahdi_pvt));
11040       ast_mutex_init(&p->lock);
11041       p->subs[SUB_REAL].dfd = dahdi_open("/dev/dahdi/pseudo");
11042       if (p->subs[SUB_REAL].dfd < 0) {
11043          ast_log(LOG_ERROR, "Unable to dup channel: %s\n", strerror(errno));
11044          destroy_dahdi_pvt(&p);
11045          return NULL;
11046       }
11047       res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_BUFINFO, &bi);
11048       if (!res) {
11049          bi.txbufpolicy = src->buf_policy;
11050          bi.rxbufpolicy = src->buf_policy;
11051          bi.numbufs = src->buf_no;
11052          res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SET_BUFINFO, &bi);
11053          if (res < 0) {
11054             ast_log(LOG_WARNING, "Unable to set buffer policy on dup channel: %s\n", strerror(errno));
11055          }
11056       } else
11057          ast_log(LOG_WARNING, "Unable to check buffer policy on dup channel: %s\n", strerror(errno));
11058    }
11059    p->destroy = 1;
11060    p->next = iflist;
11061    p->prev = NULL;
11062    iflist = p;
11063    if (iflist->next)
11064       iflist->next->prev = p;
11065    return p;
11066 }
11067 
11068 #if defined(HAVE_PRI)
11069 static int pri_find_empty_chan(struct dahdi_pri *pri, int backwards)
11070 {
11071    int x;
11072    if (backwards)
11073       x = pri->numchans;
11074    else
11075       x = 0;
11076    for (;;) {
11077       if (backwards && (x < 0))
11078          break;
11079       if (!backwards && (x >= pri->numchans))
11080          break;
11081       if (pri->pvts[x] && !pri->pvts[x]->inalarm && !pri->pvts[x]->owner) {
11082          ast_debug(1, "Found empty available channel %d/%d\n",
11083             pri->pvts[x]->logicalspan, pri->pvts[x]->prioffset);
11084          return x;
11085       }
11086       if (backwards)
11087          x--;
11088       else
11089          x++;
11090    }
11091    return -1;
11092 }
11093 #endif   /* defined(HAVE_PRI) */
11094 
11095 static struct ast_channel *dahdi_request(const char *type, int format, void *data, int *cause)
11096 {
11097    ast_group_t groupmatch = 0;
11098    int channelmatch = -1;
11099    int roundrobin = 0;
11100    int callwait = 0;
11101    int busy = 0;
11102    struct dahdi_pvt *p;
11103    struct ast_channel *tmp = NULL;
11104    char *dest=NULL;
11105    int x;
11106    char *s;
11107    char opt=0;
11108    int res=0, y=0;
11109    int backwards = 0;
11110 #ifdef HAVE_PRI
11111    int crv;
11112    int bearer = -1;
11113    int trunkgroup;
11114    struct dahdi_pri *pri=NULL;
11115 #endif
11116    struct dahdi_pvt *exitpvt, *start, *end;
11117    ast_mutex_t *lock;
11118    int channelmatched = 0;
11119    int groupmatched = 0;
11120 
11121    /*
11122     * data is ---v
11123     * Dial(DAHDI/pseudo[/extension])
11124     * Dial(DAHDI/<channel#>[c|r<cadance#>|d][/extension])
11125     * Dial(DAHDI/<trunk_group#>:<crv#>[c|r<cadance#>|d][/extension])
11126     * Dial(DAHDI/(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension])
11127     *
11128     * g - channel group allocation search forward
11129     * G - channel group allocation search backward
11130     * r - channel group allocation round robin search forward
11131     * R - channel group allocation round robin search backward
11132     *
11133     * c - Wait for DTMF digit to confirm answer
11134     * r<cadance#> - Set distintive ring cadance number
11135     * d - Force bearer capability for ISDN/SS7 call to digital.
11136     */
11137 
11138    /* Assume we're locking the iflock */
11139    lock = &iflock;
11140    start = iflist;
11141    end = ifend;
11142    if (data) {
11143       dest = ast_strdupa((char *)data);
11144    } else {
11145       ast_log(LOG_WARNING, "Channel requested with no data\n");
11146       return NULL;
11147    }
11148    if (toupper(dest[0]) == 'G' || toupper(dest[0])=='R') {
11149       /* Retrieve the group number */
11150       char *stringp;
11151 
11152       stringp = dest + 1;
11153       s = strsep(&stringp, "/");
11154       if ((res = sscanf(s, "%30d%1c%30d", &x, &opt, &y)) < 1) {
11155          ast_log(LOG_WARNING, "Unable to determine group for data %s\n", (char *)data);
11156          return NULL;
11157       }
11158       groupmatch = ((ast_group_t) 1 << x);
11159       if (toupper(dest[0]) == 'G') {
11160          if (dest[0] == 'G') {
11161             backwards = 1;
11162             p = ifend;
11163          } else
11164             p = iflist;
11165       } else {
11166          if (dest[0] == 'R') {
11167             backwards = 1;
11168             p = round_robin[x]?round_robin[x]->prev:ifend;
11169             if (!p)
11170                p = ifend;
11171          } else {
11172             p = round_robin[x]?round_robin[x]->next:iflist;
11173             if (!p)
11174                p = iflist;
11175          }
11176          roundrobin = 1;
11177       }
11178    } else {
11179       char *stringp;
11180 
11181       stringp = dest;
11182       s = strsep(&stringp, "/");
11183       p = iflist;
11184       if (!strcasecmp(s, "pseudo")) {
11185          /* Special case for pseudo */
11186          x = CHAN_PSEUDO;
11187          channelmatch = x;
11188       }
11189 #ifdef HAVE_PRI
11190       else if ((res = sscanf(s, "%30d:%30d%1c%30d", &trunkgroup, &crv, &opt, &y)) > 1) {
11191          if ((trunkgroup < 1) || (crv < 1)) {
11192             ast_log(LOG_WARNING, "Unable to determine trunk group and CRV for data %s\n", (char *)data);
11193             return NULL;
11194          }
11195          res--;
11196          for (x = 0; x < NUM_SPANS; x++) {
11197             if (pris[x].trunkgroup == trunkgroup) {
11198                pri = pris + x;
11199                lock = &pri->lock;
11200                start = pri->crvs;
11201                end = pri->crvend;
11202                break;
11203             }
11204          }
11205          if (!pri) {
11206             ast_log(LOG_WARNING, "Unable to find trunk group %d\n", trunkgroup);
11207             return NULL;
11208          }
11209          channelmatch = crv;
11210          p = pris[x].crvs;
11211       }
11212 #endif
11213       else if ((res = sscanf(s, "%30d%1c%30d", &x, &opt, &y)) < 1) {
11214          ast_log(LOG_WARNING, "Unable to determine channel for data %s\n", (char *)data);
11215          return NULL;
11216       } else {
11217          channelmatch = x;
11218       }
11219    }
11220    /* Search for an unowned channel */
11221    ast_mutex_lock(lock);
11222    exitpvt = p;
11223    while (p && !tmp) {
11224       if (roundrobin)
11225          round_robin[x] = p;
11226 #if 0
11227       ast_verbose("name = %s, %d, %d, %llu\n",p->owner ? p->owner->name : "<none>", p->channel, channelmatch, groupmatch);
11228 #endif
11229 
11230       if (p && available(p, channelmatch, groupmatch, &busy, &channelmatched, &groupmatched)) {
11231          ast_debug(1, "Using channel %d\n", p->channel);
11232          if (p->inalarm)
11233             goto next;
11234 
11235          callwait = (p->owner != NULL);
11236 #ifdef HAVE_PRI
11237          if (pri && (p->subs[SUB_REAL].dfd < 0)) {
11238             if (p->sig != SIG_FXSKS) {
11239                /* Gotta find an actual channel to use for this
11240                   CRV if this isn't a callwait */
11241                bearer = pri_find_empty_chan(pri, 0);
11242                if (bearer < 0) {
11243                   ast_log(LOG_NOTICE, "Out of bearer channels on span %d for call to CRV %d:%d\n", pri->span, trunkgroup, crv);
11244                   p = NULL;
11245                   break;
11246                }
11247                pri_assign_bearer(p, pri, pri->pvts[bearer]);
11248             } else {
11249                if (alloc_sub(p, 0)) {
11250                   ast_log(LOG_NOTICE, "Failed to allocate place holder pseudo channel!\n");
11251                   p = NULL;
11252                   break;
11253                } else
11254                   ast_debug(1, "Allocated placeholder pseudo channel\n");
11255 
11256                p->pri = pri;
11257             }
11258          }
11259 #endif
11260 #ifdef HAVE_OPENR2
11261          if (p->mfcr2) {
11262             ast_mutex_lock(&p->lock);
11263             if (p->mfcr2call) {
11264                ast_mutex_unlock(&p->lock);
11265                ast_log(LOG_DEBUG, "Yay!, someone just beat us in the race for channel %d.\n", p->channel);
11266                goto next;
11267             }
11268             p->mfcr2call = 1;
11269             ast_mutex_unlock(&p->lock);
11270          }
11271 #endif
11272          if (p->channel == CHAN_PSEUDO) {
11273             p = duplicate_pseudo(p);
11274             if (!p) {
11275                break;
11276             }
11277          }
11278          if (p->owner) {
11279             if (alloc_sub(p, SUB_CALLWAIT)) {
11280                p = NULL;
11281                break;
11282             }
11283          }
11284          p->outgoing = 1;
11285          tmp = dahdi_new(p, AST_STATE_RESERVED, 0, p->owner ? SUB_CALLWAIT : SUB_REAL, 0, 0);
11286          if (!tmp) {
11287             p->outgoing = 0;
11288          }
11289 #ifdef HAVE_PRI
11290          if (p->bearer) {
11291             /* Log owner to bearer channel, too */
11292             p->bearer->owner = tmp;
11293          }
11294 #endif
11295          /* Make special notes */
11296          if (res > 1) {
11297             if (opt == 'c') {
11298                /* Confirm answer */
11299                p->confirmanswer = 1;
11300             } else if (opt == 'r') {
11301                /* Distinctive ring */
11302                if (res < 3)
11303                   ast_log(LOG_WARNING, "Distinctive ring missing identifier in '%s'\n", (char *)data);
11304                else
11305                   p->distinctivering = y;
11306             } else if (opt == 'd') {
11307                /* If this is an ISDN call, make it digital */
11308                p->digital = 1;
11309                if (tmp)
11310                   tmp->transfercapability = AST_TRANS_CAP_DIGITAL;
11311             } else {
11312                ast_log(LOG_WARNING, "Unknown option '%c' in '%s'\n", opt, (char *)data);
11313             }
11314          }
11315          /* Note if the call is a call waiting call */
11316          if (tmp && callwait)
11317             tmp->cdrflags |= AST_CDR_CALLWAIT;
11318          break;
11319       }
11320 next:
11321       if (backwards) {
11322          p = p->prev;
11323          if (!p)
11324             p = end;
11325       } else {
11326          p = p->next;
11327          if (!p)
11328             p = start;
11329       }
11330       /* stop when you roll to the one that we started from */
11331       if (p == exitpvt)
11332          break;
11333    }
11334    ast_mutex_unlock(lock);
11335    restart_monitor();
11336    if (callwait)
11337       *cause = AST_CAUSE_BUSY;
11338    else if (!tmp) {
11339       if (channelmatched) {
11340          if (busy)
11341             *cause = AST_CAUSE_BUSY;
11342       } else if (groupmatched) {
11343          *cause = AST_CAUSE_CONGESTION;
11344       }
11345    }
11346 
11347    return tmp;
11348 }
11349 
11350 #if defined(HAVE_PRI) || defined(HAVE_SS7)
11351 static int dahdi_setlaw(int dfd, int law)
11352 {
11353    return ioctl(dfd, DAHDI_SETLAW, &law);
11354 }
11355 #endif   /* defined(HAVE_PRI) || defined(HAVE_SS7) */
11356 
11357 #if defined(HAVE_SS7)
11358 static int ss7_find_cic(struct dahdi_ss7 *linkset, int cic, unsigned int dpc)
11359 {
11360    int i;
11361    int winner = -1;
11362    for (i = 0; i < linkset->numchans; i++) {
11363       if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && linkset->pvts[i]->cic == cic)) {
11364          winner = i;
11365          break;
11366       }
11367    }
11368    return winner;
11369 }
11370 #endif   /* defined(HAVE_SS7) */
11371 
11372 #if defined(HAVE_SS7)
11373 static void ss7_handle_cqm(struct dahdi_ss7 *linkset, int startcic, int endcic, unsigned int dpc)
11374 {
11375    unsigned char status[32];
11376    struct dahdi_pvt *p = NULL;
11377    int i, offset;
11378 
11379    for (i = 0; i < linkset->numchans; i++) {
11380       if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic)))) {
11381          p = linkset->pvts[i];
11382          offset = p->cic - startcic;
11383          status[offset] = 0;
11384          if (p->locallyblocked)
11385             status[offset] |= (1 << 0) | (1 << 4);
11386          if (p->remotelyblocked)
11387             status[offset] |= (1 << 1) | (1 << 5);
11388          if (p->ss7call) {
11389             if (p->outgoing)
11390                status[offset] |= (1 << 3);
11391             else
11392                status[offset] |= (1 << 2);
11393          } else
11394             status[offset] |= 0x3 << 2;
11395       }
11396    }
11397 
11398    if (p)
11399       isup_cqr(linkset->ss7, startcic, endcic, dpc, status);
11400    else
11401       ast_log(LOG_WARNING, "Could not find any equipped circuits within CQM CICs\n");
11402 
11403 }
11404 #endif   /* defined(HAVE_SS7) */
11405 
11406 #if defined(HAVE_SS7)
11407 static inline void ss7_hangup_cics(struct dahdi_ss7 *linkset, int startcic, int endcic, unsigned int dpc)
11408 {
11409    int i;
11410 
11411    for (i = 0; i < linkset->numchans; i++) {
11412       if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic)))) {
11413          ast_mutex_lock(&linkset->pvts[i]->lock);
11414          if (linkset->pvts[i]->owner)
11415             linkset->pvts[i]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
11416          ast_mutex_unlock(&linkset->pvts[i]->lock);
11417       }
11418    }
11419 }
11420 #endif   /* defined(HAVE_SS7) */
11421 
11422 #if defined(HAVE_SS7)
11423 static inline void ss7_block_cics(struct dahdi_ss7 *linkset, int startcic, int endcic, unsigned int dpc, unsigned char state[], int block)
11424 {
11425    int i;
11426 
11427    for (i = 0; i < linkset->numchans; i++) {
11428       if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic)))) {
11429          if (state) {
11430             if (state[i])
11431                linkset->pvts[i]->remotelyblocked = block;
11432          } else
11433             linkset->pvts[i]->remotelyblocked = block;
11434       }
11435    }
11436 }
11437 #endif   /* defined(HAVE_SS7) */
11438 
11439 #if defined(HAVE_SS7)
11440 static void ss7_inservice(struct dahdi_ss7 *linkset, int startcic, int endcic, unsigned int dpc)
11441 {
11442    int i;
11443 
11444    for (i = 0; i < linkset->numchans; i++) {
11445       if (linkset->pvts[i] && (linkset->pvts[i]->dpc == dpc && ((linkset->pvts[i]->cic >= startcic) && (linkset->pvts[i]->cic <= endcic))))
11446          linkset->pvts[i]->inservice = 1;
11447    }
11448 }
11449 #endif   /* defined(HAVE_SS7) */
11450 
11451 #if defined(HAVE_SS7)
11452 static void ss7_reset_linkset(struct dahdi_ss7 *linkset)
11453 {
11454    int i, startcic = -1, endcic, dpc;
11455 
11456    if (linkset->numchans <= 0)
11457       return;
11458 
11459    startcic = linkset->pvts[0]->cic;
11460    /* DB: CIC's DPC fix */
11461    dpc = linkset->pvts[0]->dpc;
11462 
11463    for (i = 0; i < linkset->numchans; i++) {
11464       if (linkset->pvts[i+1] && linkset->pvts[i+1]->dpc == dpc && ((linkset->pvts[i+1]->cic - linkset->pvts[i]->cic) == 1) && (linkset->pvts[i]->cic - startcic < 31)) {
11465          continue;
11466       } else {
11467          endcic = linkset->pvts[i]->cic;
11468          ast_verbose("Resetting CICs %d to %d\n", startcic, endcic);
11469          isup_grs(linkset->ss7, startcic, endcic, dpc);
11470 
11471          /* DB: CIC's DPC fix */
11472          if (linkset->pvts[i+1]) {
11473             startcic = linkset->pvts[i+1]->cic;
11474             dpc = linkset->pvts[i+1]->dpc;
11475          }
11476       }
11477    }
11478 }
11479 #endif   /* defined(HAVE_SS7) */
11480 
11481 #if defined(HAVE_SS7)
11482 static void dahdi_loopback(struct dahdi_pvt *p, int enable)
11483 {
11484    if (p->loopedback != enable) {
11485       if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
11486          ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel, strerror(errno));
11487          return;
11488       }
11489       p->loopedback = enable;
11490    }
11491 }
11492 #endif   /* defined(HAVE_SS7) */
11493 
11494 #if defined(HAVE_SS7)
11495 /* XXX: This function is assumed to be called with the private channel lock and linkset lock held */
11496 static void ss7_start_call(struct dahdi_pvt *p, struct dahdi_ss7 *linkset)
11497 {
11498    struct ss7 *ss7 = linkset->ss7;
11499    int res;
11500    int law = 1;
11501    struct ast_channel *c;
11502    char tmp[256];
11503 
11504    if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &law) == -1)
11505       ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", p->channel, law, strerror(errno));
11506 
11507    if (linkset->type == SS7_ITU)
11508       law = DAHDI_LAW_ALAW;
11509    else
11510       law = DAHDI_LAW_MULAW;
11511 
11512    res = dahdi_setlaw(p->subs[SUB_REAL].dfd, law);
11513    if (res < 0)
11514       ast_log(LOG_WARNING, "Unable to set law on channel %d\n", p->channel);
11515 
11516    if (!(linkset->flags & LINKSET_FLAG_EXPLICITACM)) {
11517       p->proceeding = 1;
11518       isup_acm(ss7, p->ss7call);
11519    }
11520 
11521    ast_mutex_unlock(&linkset->lock);
11522    c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, law, 0);
11523 
11524    if (!c) {
11525       ast_log(LOG_WARNING, "Unable to start PBX on CIC %d\n", p->cic);
11526       /* Holding this lock is assumed entering the function */
11527       ast_mutex_lock(&linkset->lock);
11528       return;
11529    } else
11530       ast_verb(3, "Accepting call to '%s' on CIC %d\n", p->exten, p->cic);
11531 
11532    dahdi_enable_ec(p);
11533 
11534    /* We only reference these variables in the context of the ss7_linkset function
11535     * when receiving either and IAM or a COT message.  Since they are only accessed
11536     * from this context, we should be safe to unlock around them */
11537 
11538    ast_mutex_unlock(&p->lock);
11539 
11540    if (!ast_strlen_zero(p->charge_number)) {
11541       pbx_builtin_setvar_helper(c, "SS7_CHARGE_NUMBER", p->charge_number);
11542       /* Clear this after we set it */
11543       p->charge_number[0] = 0;
11544    }
11545    if (!ast_strlen_zero(p->gen_add_number)) {
11546       pbx_builtin_setvar_helper(c, "SS7_GENERIC_ADDRESS", p->gen_add_number);
11547       /* Clear this after we set it */
11548       p->gen_add_number[0] = 0;
11549    }
11550    if (!ast_strlen_zero(p->jip_number)) {
11551       pbx_builtin_setvar_helper(c, "SS7_JIP", p->jip_number);
11552       /* Clear this after we set it */
11553       p->jip_number[0] = 0;
11554    }
11555    if (!ast_strlen_zero(p->gen_dig_number)) {
11556       pbx_builtin_setvar_helper(c, "SS7_GENERIC_DIGITS", p->gen_dig_number);
11557       /* Clear this after we set it */
11558       p->gen_dig_number[0] = 0;
11559    }
11560    if (!ast_strlen_zero(p->orig_called_num)) {
11561       pbx_builtin_setvar_helper(c, "SS7_ORIG_CALLED_NUM", p->orig_called_num);
11562       /* Clear this after we set it */
11563       p->orig_called_num[0] = 0;
11564    }
11565 
11566    snprintf(tmp, sizeof(tmp), "%d", p->gen_dig_type);
11567    pbx_builtin_setvar_helper(c, "SS7_GENERIC_DIGTYPE", tmp);
11568    /* Clear this after we set it */
11569    p->gen_dig_type = 0;
11570 
11571    snprintf(tmp, sizeof(tmp), "%d", p->gen_dig_scheme);
11572    pbx_builtin_setvar_helper(c, "SS7_GENERIC_DIGSCHEME", tmp);
11573    /* Clear this after we set it */
11574    p->gen_dig_scheme = 0;
11575 
11576    if (!ast_strlen_zero(p->lspi_ident)) {
11577       pbx_builtin_setvar_helper(c, "SS7_LSPI_IDENT", p->lspi_ident);
11578       /* Clear this after we set it */
11579       p->lspi_ident[0] = 0;
11580    }
11581 
11582    snprintf(tmp, sizeof(tmp), "%d", p->call_ref_ident);
11583    pbx_builtin_setvar_helper(c, "SS7_CALLREF_IDENT", tmp);
11584    /* Clear this after we set it */
11585    p->call_ref_ident = 0;
11586 
11587    snprintf(tmp, sizeof(tmp), "%d", p->call_ref_pc);
11588    pbx_builtin_setvar_helper(c, "SS7_CALLREF_PC", tmp);
11589    /* Clear this after we set it */
11590    p->call_ref_pc = 0;
11591 
11592    snprintf(tmp, sizeof(tmp), "%d", p->calling_party_cat);
11593    pbx_builtin_setvar_helper(c, "SS7_CALLING_PARTY_CATEGORY", tmp);
11594    /* Clear this after we set it */
11595    p->calling_party_cat = 0;
11596 
11597    if (!ast_strlen_zero(p->redirecting_num)) {
11598       pbx_builtin_setvar_helper(c, "SS7_REDIRECTING_NUMBER", p->redirecting_num);
11599       /* Clear this after we set it */
11600       p->redirecting_num[0] = 0;
11601    }
11602    if (!ast_strlen_zero(p->generic_name)) {
11603       pbx_builtin_setvar_helper(c, "SS7_GENERIC_NAME", p->generic_name);
11604       /* Clear this after we set it */
11605       p->generic_name[0] = 0;
11606    }
11607 
11608    ast_mutex_lock(&p->lock);
11609    ast_mutex_lock(&linkset->lock);
11610 }
11611 #endif   /* defined(HAVE_SS7) */
11612 
11613 #if defined(HAVE_SS7)
11614 static void ss7_apply_plan_to_number(char *buf, size_t size, const struct dahdi_ss7 *ss7, const char *number, const unsigned nai)
11615 {
11616    if (ast_strlen_zero(number)) { /* make sure a number exists so prefix isn't placed on an empty string */
11617       if (size) {
11618          *buf = '\0';
11619       }
11620       return;
11621    }
11622    switch (nai) {
11623    case SS7_NAI_INTERNATIONAL:
11624       snprintf(buf, size, "%s%s", ss7->internationalprefix, number);
11625       break;
11626    case SS7_NAI_NATIONAL:
11627       snprintf(buf, size, "%s%s", ss7->nationalprefix, number);
11628       break;
11629    case SS7_NAI_SUBSCRIBER:
11630       snprintf(buf, size, "%s%s", ss7->subscriberprefix, number);
11631       break;
11632    case SS7_NAI_UNKNOWN:
11633       snprintf(buf, size, "%s%s", ss7->unknownprefix, number);
11634       break;
11635    default:
11636       snprintf(buf, size, "%s", number);
11637       break;
11638    }
11639 }
11640 #endif   /* defined(HAVE_SS7) */
11641 
11642 #if defined(HAVE_SS7)
11643 static int ss7_pres_scr2cid_pres(char presentation_ind, char screening_ind)
11644 {
11645    return ((presentation_ind & 0x3) << 5) | (screening_ind & 0x3);
11646 }
11647 #endif   /* defined(HAVE_SS7) */
11648 
11649 #if defined(HAVE_SS7)
11650 static void *ss7_linkset(void *data)
11651 {
11652    int res, i;
11653    struct timeval *next = NULL, tv;
11654    struct dahdi_ss7 *linkset = (struct dahdi_ss7 *) data;
11655    struct ss7 *ss7 = linkset->ss7;
11656    ss7_event *e = NULL;
11657    struct dahdi_pvt *p;
11658    int chanpos;
11659    struct pollfd pollers[NUM_DCHANS];
11660    int cic;
11661    unsigned int dpc;
11662    int nextms = 0;
11663 
11664    ss7_start(ss7);
11665 
11666    while(1) {
11667       ast_mutex_lock(&linkset->lock);
11668       if ((next = ss7_schedule_next(ss7))) {
11669          tv = ast_tvnow();
11670          tv.tv_sec = next->tv_sec - tv.tv_sec;
11671          tv.tv_usec = next->tv_usec - tv.tv_usec;
11672          if (tv.tv_usec < 0) {
11673             tv.tv_usec += 1000000;
11674             tv.tv_sec -= 1;
11675          }
11676          if (tv.tv_sec < 0) {
11677             tv.tv_sec = 0;
11678             tv.tv_usec = 0;
11679          }
11680          nextms = tv.tv_sec * 1000;
11681          nextms += tv.tv_usec / 1000;
11682       }
11683       ast_mutex_unlock(&linkset->lock);
11684 
11685       for (i = 0; i < linkset->numsigchans; i++) {
11686          pollers[i].fd = linkset->fds[i];
11687          pollers[i].events = ss7_pollflags(ss7, linkset->fds[i]);
11688          pollers[i].revents = 0;
11689       }
11690 
11691       res = poll(pollers, linkset->numsigchans, nextms);
11692       if ((res < 0) && (errno != EINTR)) {
11693          ast_log(LOG_ERROR, "poll(%s)\n", strerror(errno));
11694       } else if (!res) {
11695          ast_mutex_lock(&linkset->lock);
11696          ss7_schedule_run(ss7);
11697          ast_mutex_unlock(&linkset->lock);
11698          continue;
11699       }
11700 
11701       ast_mutex_lock(&linkset->lock);
11702       for (i = 0; i < linkset->numsigchans; i++) {
11703          if (pollers[i].revents & POLLPRI) {
11704             int x;
11705             if (ioctl(pollers[i].fd, DAHDI_GETEVENT, &x)) {
11706                ast_log(LOG_ERROR, "Error in exception retrieval!\n");
11707             }
11708             switch (x) {
11709             case DAHDI_EVENT_OVERRUN:
11710                ast_debug(1, "Overrun detected!\n");
11711                break;
11712             case DAHDI_EVENT_BADFCS:
11713                ast_debug(1, "Bad FCS\n");
11714                break;
11715             case DAHDI_EVENT_ABORT:
11716                ast_debug(1, "HDLC Abort\n");
11717                break;
11718             case DAHDI_EVENT_ALARM:
11719                ast_log(LOG_ERROR, "Alarm on link!\n");
11720                linkset->linkstate[i] |= (LINKSTATE_DOWN | LINKSTATE_INALARM);
11721                linkset->linkstate[i] &= ~LINKSTATE_UP;
11722                ss7_link_alarm(ss7, pollers[i].fd);
11723                break;
11724             case DAHDI_EVENT_NOALARM:
11725                ast_log(LOG_ERROR, "Alarm cleared on link\n");
11726                linkset->linkstate[i] &= ~(LINKSTATE_INALARM | LINKSTATE_DOWN);
11727                linkset->linkstate[i] |= LINKSTATE_STARTING;
11728                ss7_link_noalarm(ss7, pollers[i].fd);
11729                break;
11730             default:
11731                ast_log(LOG_ERROR, "Got exception %d!\n", x);
11732                break;
11733             }
11734          }
11735 
11736          if (pollers[i].revents & POLLIN) {
11737             res = ss7_read(ss7, pollers[i].fd);
11738          }
11739 
11740          if (pollers[i].revents & POLLOUT) {
11741             res = ss7_write(ss7, pollers[i].fd);
11742             if (res < 0) {
11743                ast_debug(1, "Error in write %s\n", strerror(errno));
11744             }
11745          }
11746       }
11747 
11748       while ((e = ss7_check_event(ss7))) {
11749          switch (e->e) {
11750          case SS7_EVENT_UP:
11751             if (linkset->state != LINKSET_STATE_UP) {
11752                ast_verbose("--- SS7 Up ---\n");
11753                ss7_reset_linkset(linkset);
11754             }
11755             linkset->state = LINKSET_STATE_UP;
11756             break;
11757          case SS7_EVENT_DOWN:
11758             ast_verbose("--- SS7 Down ---\n");
11759             linkset->state = LINKSET_STATE_DOWN;
11760             for (i = 0; i < linkset->numchans; i++) {
11761                struct dahdi_pvt *p = linkset->pvts[i];
11762                if (p)
11763                   p->inalarm = 1;
11764             }
11765             break;
11766          case MTP2_LINK_UP:
11767             ast_verbose("MTP2 link up (SLC %d)\n", e->gen.data);
11768             break;
11769          case MTP2_LINK_DOWN:
11770             ast_log(LOG_WARNING, "MTP2 link down (SLC %d)\n", e->gen.data);
11771             break;
11772          case ISUP_EVENT_CPG:
11773             chanpos = ss7_find_cic(linkset, e->cpg.cic, e->cpg.opc);
11774             if (chanpos < 0) {
11775                ast_log(LOG_WARNING, "CPG on unconfigured CIC %d\n", e->cpg.cic);
11776                break;
11777             }
11778             p = linkset->pvts[chanpos];
11779             ast_mutex_lock(&p->lock);
11780             switch (e->cpg.event) {
11781             case CPG_EVENT_ALERTING:
11782                p->alerting = 1;
11783                p->subs[SUB_REAL].needringing = 1;
11784                break;
11785             case CPG_EVENT_PROGRESS:
11786             case CPG_EVENT_INBANDINFO:
11787                {
11788                   struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
11789                   ast_debug(1, "Queuing frame PROGRESS on CIC %d\n", p->cic);
11790                   dahdi_queue_frame(p, &f, linkset);
11791                   p->progress = 1;
11792                   p->dialing = 0;
11793                   if (p->dsp && p->dsp_features) {
11794                      ast_dsp_set_features(p->dsp, p->dsp_features);
11795                      p->dsp_features = 0;
11796                   }
11797                }
11798                break;
11799             default:
11800                ast_debug(1, "Do not handle CPG with event type 0x%x\n", e->cpg.event);
11801             }
11802 
11803             ast_mutex_unlock(&p->lock);
11804             break;
11805          case ISUP_EVENT_RSC:
11806             ast_verbose("Resetting CIC %d\n", e->rsc.cic);
11807             chanpos = ss7_find_cic(linkset, e->rsc.cic, e->rsc.opc);
11808             if (chanpos < 0) {
11809                ast_log(LOG_WARNING, "RSC on unconfigured CIC %d\n", e->rsc.cic);
11810                break;
11811             }
11812             p = linkset->pvts[chanpos];
11813             ast_mutex_lock(&p->lock);
11814             p->inservice = 1;
11815             p->remotelyblocked = 0;
11816             dpc = p->dpc;
11817             isup_set_call_dpc(e->rsc.call, dpc);
11818             if (p->ss7call)
11819                p->ss7call = NULL;
11820             if (p->owner)
11821                p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
11822             ast_mutex_unlock(&p->lock);
11823             isup_rlc(ss7, e->rsc.call);
11824             break;
11825          case ISUP_EVENT_GRS:
11826             ast_debug(1, "Got Reset for CICs %d to %d: Acknowledging\n", e->grs.startcic, e->grs.endcic);
11827             chanpos = ss7_find_cic(linkset, e->grs.startcic, e->grs.opc);
11828             if (chanpos < 0) {
11829                ast_log(LOG_WARNING, "GRS on unconfigured CIC %d\n", e->grs.startcic);
11830                break;
11831             }
11832             p = linkset->pvts[chanpos];
11833             isup_gra(ss7, e->grs.startcic, e->grs.endcic, e->grs.opc);
11834             ss7_block_cics(linkset, e->grs.startcic, e->grs.endcic, e->grs.opc, NULL, 0);
11835             ss7_hangup_cics(linkset, e->grs.startcic, e->grs.endcic, e->grs.opc);
11836             break;
11837          case ISUP_EVENT_CQM:
11838             ast_debug(1, "Got Circuit group query message from CICs %d to %d\n", e->cqm.startcic, e->cqm.endcic);
11839             ss7_handle_cqm(linkset, e->cqm.startcic, e->cqm.endcic, e->cqm.opc);
11840             break;
11841          case ISUP_EVENT_GRA:
11842             ast_verbose("Got reset acknowledgement from CIC %d to %d.\n", e->gra.startcic, e->gra.endcic);
11843             ss7_inservice(linkset, e->gra.startcic, e->gra.endcic, e->gra.opc);
11844             ss7_block_cics(linkset, e->gra.startcic, e->gra.endcic, e->gra.opc, e->gra.status, 1);
11845             break;
11846          case ISUP_EVENT_IAM:
11847             ast_debug(1, "Got IAM for CIC %d and called number %s, calling number %s\n", e->iam.cic, e->iam.called_party_num, e->iam.calling_party_num);
11848             chanpos = ss7_find_cic(linkset, e->iam.cic, e->iam.opc);
11849             if (chanpos < 0) {
11850                ast_log(LOG_WARNING, "IAM on unconfigured CIC %d\n", e->iam.cic);
11851                isup_rel(ss7, e->iam.call, -1);
11852                break;
11853             }
11854             p = linkset->pvts[chanpos];
11855             ast_mutex_lock(&p->lock);
11856             if (p->owner) {
11857                if (p->ss7call == e->iam.call) {
11858                   ast_mutex_unlock(&p->lock);
11859                   ast_log(LOG_WARNING, "Duplicate IAM requested on CIC %d\n", e->iam.cic);
11860                   break;
11861                } else {
11862                   ast_mutex_unlock(&p->lock);
11863                   ast_log(LOG_WARNING, "Ring requested on CIC %d already in use!\n", e->iam.cic);
11864                   break;
11865                }
11866             }
11867 
11868             dpc = p->dpc;
11869             p->ss7call = e->iam.call;
11870             isup_set_call_dpc(p->ss7call, dpc);
11871 
11872             if ((p->use_callerid) && (!ast_strlen_zero(e->iam.calling_party_num))) {
11873                ss7_apply_plan_to_number(p->cid_num, sizeof(p->cid_num), linkset, e->iam.calling_party_num, e->iam.calling_nai);
11874                p->callingpres = ss7_pres_scr2cid_pres(e->iam.presentation_ind, e->iam.screening_ind);
11875             } else
11876                p->cid_num[0] = 0;
11877 
11878             if (p->immediate) {
11879                p->exten[0] = 's';
11880                p->exten[1] = '\0';
11881             } else if (!ast_strlen_zero(e->iam.called_party_num)) {
11882                char *st;
11883                ss7_apply_plan_to_number(p->exten, sizeof(p->exten), linkset, e->iam.called_party_num, e->iam.called_nai);
11884                st = strchr(p->exten, '#');
11885                if (st)
11886                   *st = '\0';
11887                } else
11888                   p->exten[0] = '\0';
11889 
11890             p->cid_ani[0] = '\0';
11891             if ((p->use_callerid) && (!ast_strlen_zero(e->iam.generic_name)))
11892                ast_copy_string(p->cid_name, e->iam.generic_name, sizeof(p->cid_name));
11893             else
11894                p->cid_name[0] = '\0';
11895 
11896             p->cid_ani2 = e->iam.oli_ani2;
11897             p->cid_ton = 0;
11898             ast_copy_string(p->charge_number, e->iam.charge_number, sizeof(p->charge_number));
11899             ast_copy_string(p->gen_add_number, e->iam.gen_add_number, sizeof(p->gen_add_number));
11900             p->gen_add_type = e->iam.gen_add_type;
11901             p->gen_add_nai = e->iam.gen_add_nai;
11902             p->gen_add_pres_ind = e->iam.gen_add_pres_ind;
11903             p->gen_add_num_plan = e->iam.gen_add_num_plan;
11904             ast_copy_string(p->gen_dig_number, e->iam.gen_dig_number, sizeof(p->gen_dig_number));
11905             p->gen_dig_type = e->iam.gen_dig_type;
11906             p->gen_dig_scheme = e->iam.gen_dig_scheme;
11907             ast_copy_string(p->jip_number, e->iam.jip_number, sizeof(p->jip_number));
11908             ast_copy_string(p->orig_called_num, e->iam.orig_called_num, sizeof(p->orig_called_num));
11909             ast_copy_string(p->redirecting_num, e->iam.redirecting_num, sizeof(p->redirecting_num));
11910             ast_copy_string(p->generic_name, e->iam.generic_name, sizeof(p->generic_name));
11911             p->calling_party_cat = e->iam.calling_party_cat;
11912 
11913             /* Set DNID */
11914             if (!ast_strlen_zero(e->iam.called_party_num))
11915                ss7_apply_plan_to_number(p->dnid, sizeof(p->dnid), linkset, e->iam.called_party_num, e->iam.called_nai);
11916 
11917             if (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
11918 
11919                if (e->iam.cot_check_required) {
11920                   dahdi_loopback(p, 1);
11921                } else
11922                   ss7_start_call(p, linkset);
11923             } else {
11924                ast_debug(1, "Call on CIC for unconfigured extension %s\n", p->exten);
11925                p->alreadyhungup = 1;
11926                isup_rel(ss7, e->iam.call, AST_CAUSE_UNALLOCATED);
11927             }
11928             ast_mutex_unlock(&p->lock);
11929             break;
11930          case ISUP_EVENT_COT:
11931             chanpos = ss7_find_cic(linkset, e->cot.cic, e->cot.opc);
11932             if (chanpos < 0) {
11933                ast_log(LOG_WARNING, "COT on unconfigured CIC %d\n", e->cot.cic);
11934                isup_rel(ss7, e->cot.call, -1);
11935                break;
11936             }
11937             p = linkset->pvts[chanpos];
11938 
11939             ast_mutex_lock(&p->lock);
11940 
11941             if (p->loopedback) {
11942                dahdi_loopback(p, 0);
11943                ss7_start_call(p, linkset);
11944             }
11945 
11946             ast_mutex_unlock(&p->lock);
11947 
11948             break;
11949          case ISUP_EVENT_CCR:
11950             ast_debug(1, "Got CCR request on CIC %d\n", e->ccr.cic);
11951             chanpos = ss7_find_cic(linkset, e->ccr.cic, e->ccr.opc);
11952             if (chanpos < 0) {
11953                ast_log(LOG_WARNING, "CCR on unconfigured CIC %d\n", e->ccr.cic);
11954                break;
11955             }
11956 
11957             p = linkset->pvts[chanpos];
11958 
11959             ast_mutex_lock(&p->lock);
11960             dahdi_loopback(p, 1);
11961             ast_mutex_unlock(&p->lock);
11962 
11963             isup_lpa(linkset->ss7, e->ccr.cic, p->dpc);
11964             break;
11965          case ISUP_EVENT_CVT:
11966             ast_debug(1, "Got CVT request on CIC %d\n", e->cvt.cic);
11967             chanpos = ss7_find_cic(linkset, e->cvt.cic, e->cvt.opc);
11968             if (chanpos < 0) {
11969                ast_log(LOG_WARNING, "CVT on unconfigured CIC %d\n", e->cvt.cic);
11970                break;
11971             }
11972 
11973             p = linkset->pvts[chanpos];
11974 
11975             ast_mutex_lock(&p->lock);
11976             dahdi_loopback(p, 1);
11977             ast_mutex_unlock(&p->lock);
11978 
11979             isup_cvr(linkset->ss7, e->cvt.cic, p->dpc);
11980             break;
11981          case ISUP_EVENT_REL:
11982             chanpos = ss7_find_cic(linkset, e->rel.cic, e->rel.opc);
11983             if (chanpos < 0) {
11984                ast_log(LOG_WARNING, "REL on unconfigured CIC %d\n", e->rel.cic);
11985                break;
11986             }
11987             p = linkset->pvts[chanpos];
11988             ast_mutex_lock(&p->lock);
11989             if (p->owner) {
11990                p->owner->hangupcause = e->rel.cause;
11991                p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
11992             } else if (!p->restartpending)
11993                ast_log(LOG_WARNING, "REL on channel (CIC %d) without owner!\n", p->cic);
11994 
11995             /* End the loopback if we have one */
11996             dahdi_loopback(p, 0);
11997 
11998             isup_rlc(ss7, e->rel.call);
11999             p->ss7call = NULL;
12000 
12001             ast_mutex_unlock(&p->lock);
12002             break;
12003          case ISUP_EVENT_ACM:
12004             chanpos = ss7_find_cic(linkset, e->acm.cic, e->acm.opc);
12005             if (chanpos < 0) {
12006                ast_log(LOG_WARNING, "ACM on unconfigured CIC %d\n", e->acm.cic);
12007                isup_rel(ss7, e->acm.call, -1);
12008                break;
12009             } else {
12010                struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
12011 
12012                p = linkset->pvts[chanpos];
12013 
12014                ast_debug(1, "Queueing frame from SS7_EVENT_ACM on CIC %d\n", p->cic);
12015 
12016                if (e->acm.call_ref_ident > 0) {
12017                   p->rlt = 1; /* Setting it but not using it here*/
12018                }
12019 
12020                ast_mutex_lock(&p->lock);
12021                dahdi_queue_frame(p, &f, linkset);
12022                p->proceeding = 1;
12023                p->dialing = 0;
12024                /* Send alerting if subscriber is free */
12025                if (e->acm.called_party_status_ind == 1) {
12026                   p->alerting = 1;
12027                   p->subs[SUB_REAL].needringing = 1;
12028                }
12029                ast_mutex_unlock(&p->lock);
12030             }
12031             break;
12032          case ISUP_EVENT_CGB:
12033             chanpos = ss7_find_cic(linkset, e->cgb.startcic, e->cgb.opc);
12034             if (chanpos < 0) {
12035                ast_log(LOG_WARNING, "CGB on unconfigured CIC %d\n", e->cgb.startcic);
12036                break;
12037             }
12038             p = linkset->pvts[chanpos];
12039             ss7_block_cics(linkset, e->cgb.startcic, e->cgb.endcic, e->cgb.opc, e->cgb.status, 1);
12040             isup_cgba(linkset->ss7, e->cgb.startcic, e->cgb.endcic, e->cgb.opc, e->cgb.status, e->cgb.type);
12041             break;
12042          case ISUP_EVENT_CGU:
12043             chanpos = ss7_find_cic(linkset, e->cgu.startcic, e->cgu.opc);
12044             if (chanpos < 0) {
12045                ast_log(LOG_WARNING, "CGU on unconfigured CIC %d\n", e->cgu.startcic);
12046                break;
12047             }
12048             p = linkset->pvts[chanpos];
12049             ss7_block_cics(linkset, e->cgu.startcic, e->cgu.endcic, e->cgu.opc, e->cgu.status, 0);
12050             isup_cgua(linkset->ss7, e->cgu.startcic, e->cgu.endcic, e->cgu.opc, e->cgu.status, e->cgu.type);
12051             break;
12052          case ISUP_EVENT_UCIC:
12053             chanpos = ss7_find_cic(linkset, e->ucic.cic, e->ucic.opc);
12054             if (chanpos < 0) {
12055                ast_log(LOG_WARNING, "UCIC on unconfigured CIC %d\n", e->ucic.cic);
12056                break;
12057             }
12058             p = linkset->pvts[chanpos];
12059             ast_debug(1, "Unequiped Circuit Id Code on CIC %d\n", e->ucic.cic);
12060             ast_mutex_lock(&p->lock);
12061             p->remotelyblocked = 1;
12062             p->inservice = 0;
12063             ast_mutex_unlock(&p->lock);         //doesn't require a SS7 acknowledgement
12064             break;
12065          case ISUP_EVENT_BLO:
12066             chanpos = ss7_find_cic(linkset, e->blo.cic, e->blo.opc);
12067             if (chanpos < 0) {
12068                ast_log(LOG_WARNING, "BLO on unconfigured CIC %d\n", e->blo.cic);
12069                break;
12070             }
12071             p = linkset->pvts[chanpos];
12072             ast_debug(1, "Blocking CIC %d\n", e->blo.cic);
12073             ast_mutex_lock(&p->lock);
12074             p->remotelyblocked = 1;
12075             ast_mutex_unlock(&p->lock);
12076             isup_bla(linkset->ss7, e->blo.cic, p->dpc);
12077             break;
12078          case ISUP_EVENT_BLA:
12079             chanpos = ss7_find_cic(linkset, e->bla.cic, e->bla.opc);
12080             if (chanpos < 0) {
12081                ast_log(LOG_WARNING, "BLA on unconfigured CIC %d\n", e->bla.cic);
12082                break;
12083             }
12084             ast_debug(1, "Blocking CIC %d\n", e->bla.cic);
12085             p = linkset->pvts[chanpos];
12086             ast_mutex_lock(&p->lock);
12087             p->locallyblocked = 1;
12088             ast_mutex_unlock(&p->lock);
12089             break;
12090          case ISUP_EVENT_UBL:
12091             chanpos = ss7_find_cic(linkset, e->ubl.cic, e->ubl.opc);
12092             if (chanpos < 0) {
12093                ast_log(LOG_WARNING, "UBL on unconfigured CIC %d\n", e->ubl.cic);
12094                break;
12095             }
12096             p = linkset->pvts[chanpos];
12097             ast_debug(1, "Unblocking CIC %d\n", e->ubl.cic);
12098             ast_mutex_lock(&p->lock);
12099             p->remotelyblocked = 0;
12100             ast_mutex_unlock(&p->lock);
12101             isup_uba(linkset->ss7, e->ubl.cic, p->dpc);
12102             break;
12103          case ISUP_EVENT_UBA:
12104             chanpos = ss7_find_cic(linkset, e->uba.cic, e->uba.opc);
12105             if (chanpos < 0) {
12106                ast_log(LOG_WARNING, "UBA on unconfigured CIC %d\n", e->uba.cic);
12107                break;
12108             }
12109             p = linkset->pvts[chanpos];
12110             ast_debug(1, "Unblocking CIC %d\n", e->uba.cic);
12111             ast_mutex_lock(&p->lock);
12112             p->locallyblocked = 0;
12113             ast_mutex_unlock(&p->lock);
12114             break;
12115          case ISUP_EVENT_CON:
12116          case ISUP_EVENT_ANM:
12117             if (e->e == ISUP_EVENT_CON)
12118                cic = e->con.cic;
12119             else
12120                cic = e->anm.cic;
12121 
12122             chanpos = ss7_find_cic(linkset, cic, (e->e == ISUP_EVENT_ANM) ? e->anm.opc : e->con.opc);
12123             if (chanpos < 0) {
12124                ast_log(LOG_WARNING, "ANM/CON on unconfigured CIC %d\n", cic);
12125                isup_rel(ss7, (e->e == ISUP_EVENT_ANM) ? e->anm.call : e->con.call, -1);
12126                break;
12127             } else {
12128                p = linkset->pvts[chanpos];
12129                ast_mutex_lock(&p->lock);
12130                p->subs[SUB_REAL].needanswer = 1;
12131                if (p->dsp && p->dsp_features) {
12132                   ast_dsp_set_features(p->dsp, p->dsp_features);
12133                   p->dsp_features = 0;
12134                }
12135                dahdi_enable_ec(p);
12136                ast_mutex_unlock(&p->lock);
12137             }
12138             break;
12139          case ISUP_EVENT_RLC:
12140             chanpos = ss7_find_cic(linkset, e->rlc.cic, e->rlc.opc);
12141             if (chanpos < 0) {
12142                ast_log(LOG_WARNING, "RLC on unconfigured CIC %d\n", e->rlc.cic);
12143                break;
12144             } else {
12145                p = linkset->pvts[chanpos];
12146                ast_mutex_lock(&p->lock);
12147                if (p->alreadyhungup)
12148                   p->ss7call = NULL;
12149                else
12150                   ast_log(LOG_NOTICE, "Received RLC out and we haven't sent REL.  Ignoring.\n");
12151                ast_mutex_unlock(&p->lock);
12152                }
12153                break;
12154          case ISUP_EVENT_FAA:
12155             chanpos = ss7_find_cic(linkset, e->faa.cic, e->faa.opc);
12156             if (chanpos < 0) {
12157                ast_log(LOG_WARNING, "FAA on unconfigured CIC %d\n", e->faa.cic);
12158                break;
12159             } else {
12160                p = linkset->pvts[chanpos];
12161                ast_debug(1, "FAA received on CIC %d\n", e->faa.cic);
12162                ast_mutex_lock(&p->lock);
12163                if (p->alreadyhungup){
12164                   p->ss7call = NULL;
12165                   ast_log(LOG_NOTICE, "Received FAA and we haven't sent FAR.  Ignoring.\n");
12166                }
12167                ast_mutex_unlock(&p->lock);
12168             }
12169             break;
12170          default:
12171             ast_debug(1, "Unknown event %s\n", ss7_event2str(e->e));
12172             break;
12173          }
12174       }
12175       ast_mutex_unlock(&linkset->lock);
12176    }
12177 
12178    return 0;
12179 }
12180 #endif   /* defined(HAVE_SS7) */
12181 
12182 #if defined(HAVE_SS7)
12183 static void dahdi_ss7_message(struct ss7 *ss7, char *s)
12184 {
12185 #if 0
12186    int i;
12187 
12188    for (i = 0; i < NUM_SPANS; i++)
12189       if (linksets[i].ss7 == ss7)
12190          break;
12191 
12192    ast_verbose("[%d] %s", i+1, s);
12193 #else
12194    ast_verbose("%s", s);
12195 #endif
12196 }
12197 #endif   /* defined(HAVE_SS7) */
12198 
12199 #if defined(HAVE_SS7)
12200 static void dahdi_ss7_error(struct ss7 *ss7, char *s)
12201 {
12202 #if 0
12203    int i;
12204 
12205    for (i = 0; i < NUM_SPANS; i++)
12206       if (linksets[i].ss7 == ss7)
12207          break;
12208 
12209 #else
12210    ast_log(LOG_ERROR, "%s", s);
12211 #endif
12212 }
12213 #endif   /* defined(HAVE_SS7) */
12214 
12215 #if defined(HAVE_OPENR2)
12216 static void *mfcr2_monitor(void *data)
12217 {
12218    struct dahdi_mfcr2 *mfcr2 = data;
12219    /* we should be using pthread_key_create
12220       and allocate pollers dynamically.
12221       I think do_monitor() could be leaking, since it
12222       could be cancelled at any time and is not
12223       using thread keys, why?, */
12224    struct pollfd pollers[sizeof(mfcr2->pvts)];
12225    int res = 0;
12226    int i = 0;
12227    int oldstate = 0;
12228    int quit_loop = 0;
12229    int maxsleep = 20;
12230    int was_idle = 0;
12231    int pollsize = 0;
12232    /* now that we're ready to get calls, unblock our side and
12233       get current line state */
12234    for (i = 0; i < mfcr2->numchans; i++) {
12235       openr2_chan_set_idle(mfcr2->pvts[i]->r2chan);
12236       openr2_chan_handle_cas(mfcr2->pvts[i]->r2chan);
12237    }
12238    while (1) {
12239       /* we trust here that the mfcr2 channel list will not ever change once
12240          the module is loaded */
12241       pollsize = 0;
12242       for (i = 0; i < mfcr2->numchans; i++) {
12243          pollers[i].revents = 0;
12244          pollers[i].events = 0;
12245          if (mfcr2->pvts[i]->owner) {
12246             continue;
12247          }
12248          if (!mfcr2->pvts[i]->r2chan) {
12249             ast_log(LOG_DEBUG, "Wow, no r2chan on channel %d\n", mfcr2->pvts[i]->channel);
12250             quit_loop = 1;
12251             break;
12252          }
12253          openr2_chan_enable_read(mfcr2->pvts[i]->r2chan);
12254          pollers[i].events = POLLIN | POLLPRI;
12255          pollers[i].fd = mfcr2->pvts[i]->subs[SUB_REAL].dfd;
12256          pollsize++;
12257       }
12258       if (quit_loop) {
12259          break;
12260       }
12261       if (pollsize == 0) {
12262          if (!was_idle) {
12263             ast_log(LOG_DEBUG, "Monitor thread going idle since everybody has an owner\n");
12264             was_idle = 1;
12265          }
12266          poll(NULL, 0, maxsleep);
12267          continue;
12268       }
12269       was_idle = 0;
12270       /* probably poll() is a valid cancel point, lets just be on the safe side
12271          by calling pthread_testcancel */
12272       pthread_testcancel();
12273       res = poll(pollers, mfcr2->numchans, maxsleep);
12274       pthread_testcancel();
12275       if ((res < 0) && (errno != EINTR)) {
12276          ast_log(LOG_ERROR, "going out, poll failed: %s\n", strerror(errno));
12277          break;
12278       }
12279       /* do we want to allow to cancel while processing events? */
12280       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);
12281       for (i = 0; i < mfcr2->numchans; i++) {
12282          if (pollers[i].revents & POLLPRI || pollers[i].revents & POLLIN) {
12283             openr2_chan_process_event(mfcr2->pvts[i]->r2chan);
12284          }
12285       }
12286       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
12287    }
12288    ast_log(LOG_NOTICE, "Quitting MFC/R2 monitor thread\n");
12289    return 0;
12290 }
12291 #endif /* HAVE_OPENR2 */
12292 
12293 #if defined(HAVE_PRI)
12294 static struct dahdi_pvt *pri_find_crv(struct dahdi_pri *pri, int crv)
12295 {
12296    struct dahdi_pvt *p;
12297    p = pri->crvs;
12298    while (p) {
12299       if (p->channel == crv)
12300          return p;
12301       p = p->next;
12302    }
12303    return NULL;
12304 }
12305 #endif   /* defined(HAVE_PRI) */
12306 
12307 #if defined(HAVE_PRI)
12308 static int pri_find_principle(struct dahdi_pri *pri, int channel)
12309 {
12310    int x;
12311    int span = PRI_SPAN(channel);
12312    int spanfd;
12313    struct dahdi_params param;
12314    int principle = -1;
12315    int explicit = PRI_EXPLICIT(channel);
12316    channel = PRI_CHANNEL(channel);
12317 
12318    if (!explicit) {
12319       spanfd = pri_active_dchan_fd(pri);
12320       memset(&param, 0, sizeof(param));
12321       if (ioctl(spanfd, DAHDI_GET_PARAMS, &param))
12322          return -1;
12323       span = pris[param.spanno - 1].prilogicalspan;
12324    }
12325 
12326    for (x = 0; x < pri->numchans; x++) {
12327       if (pri->pvts[x] && (pri->pvts[x]->prioffset == channel) && (pri->pvts[x]->logicalspan == span)) {
12328          principle = x;
12329          break;
12330       }
12331    }
12332 
12333    return principle;
12334 }
12335 #endif   /* defined(HAVE_PRI) */
12336 
12337 #if defined(HAVE_PRI)
12338 static int pri_fixup_principle(struct dahdi_pri *pri, int principle, q931_call *c)
12339 {
12340    int x;
12341    struct dahdi_pvt *crv;
12342    if (!c) {
12343       if (principle < 0)
12344          return -1;
12345       return principle;
12346    }
12347    if ((principle > -1) &&
12348       (principle < pri->numchans) &&
12349       (pri->pvts[principle]) &&
12350       (pri->pvts[principle]->call == c))
12351       return principle;
12352    /* First, check for other bearers */
12353    for (x = 0; x < pri->numchans; x++) {
12354       if (!pri->pvts[x])
12355          continue;
12356       if (pri->pvts[x]->call == c) {
12357          /* Found our call */
12358          if (principle != x) {
12359             struct dahdi_pvt *new = pri->pvts[principle], *old = pri->pvts[x];
12360 
12361             ast_verb(3, "Moving call from channel %d to channel %d\n",
12362                 old->channel, new->channel);
12363             if (new->owner) {
12364                ast_log(LOG_WARNING, "Can't fix up channel from %d to %d because %d is already in use\n",
12365                   old->channel, new->channel, new->channel);
12366                return -1;
12367             }
12368             /* Fix it all up now */
12369             new->owner = old->owner;
12370             old->owner = NULL;
12371             if (new->owner) {
12372                ast_string_field_build(new->owner, name,
12373                   "DAHDI/%d:%d-%d", pri->trunkgroup,
12374                   new->channel, 1);
12375                new->owner->tech_pvt = new;
12376                ast_channel_set_fd(new->owner, 0, new->subs[SUB_REAL].dfd);
12377                new->subs[SUB_REAL].owner = old->subs[SUB_REAL].owner;
12378                old->subs[SUB_REAL].owner = NULL;
12379             } else
12380                ast_log(LOG_WARNING, "Whoa, there's no  owner, and we're having to fix up channel %d to channel %d\n", old->channel, new->channel);
12381             new->call = old->call;
12382             old->call = NULL;
12383 
12384             /* Copy any DSP that may be present */
12385             new->dsp = old->dsp;
12386             new->dsp_features = old->dsp_features;
12387             old->dsp = NULL;
12388             old->dsp_features = 0;
12389          }
12390          return principle;
12391       }
12392    }
12393    /* Now check for a CRV with no bearer */
12394    crv = pri->crvs;
12395    while (crv) {
12396       if (crv->call == c) {
12397          /* This is our match...  Perform some basic checks */
12398          if (crv->bearer)
12399             ast_log(LOG_WARNING, "Trying to fix up call which already has a bearer which isn't the one we think it is\n");
12400          else if (pri->pvts[principle]->owner)
12401             ast_log(LOG_WARNING, "Tring to fix up a call to a bearer which already has an owner!\n");
12402          else {
12403             /* Looks good.  Drop the pseudo channel now, clear up the assignment, and
12404                wakeup the potential sleeper */
12405             dahdi_close_sub(crv, SUB_REAL);
12406             pri->pvts[principle]->call = crv->call;
12407             pri_assign_bearer(crv, pri, pri->pvts[principle]);
12408             ast_debug(1, "Assigning bearer %d/%d to CRV %d:%d\n",
12409                pri->pvts[principle]->logicalspan, pri->pvts[principle]->prioffset,
12410                pri->trunkgroup, crv->channel);
12411             wakeup_sub(crv, SUB_REAL, pri);
12412          }
12413          return principle;
12414       }
12415       crv = crv->next;
12416    }
12417    ast_log(LOG_WARNING, "Call specified, but not found?\n");
12418    return -1;
12419 }
12420 #endif   /* defined(HAVE_PRI) */
12421 
12422 #if defined(HAVE_PRI)
12423 static void *do_idle_thread(void *vchan)
12424 {
12425    struct ast_channel *chan = vchan;
12426    struct dahdi_pvt *pvt = chan->tech_pvt;
12427    struct ast_frame *f;
12428    char ex[80];
12429    /* Wait up to 30 seconds for an answer */
12430    int newms, ms = 30000;
12431    ast_verb(3, "Initiating idle call on channel %s\n", chan->name);
12432    snprintf(ex, sizeof(ex), "%d/%s", pvt->channel, pvt->pri->idledial);
12433    if (ast_call(chan, ex, 0)) {
12434       ast_log(LOG_WARNING, "Idle dial failed on '%s' to '%s'\n", chan->name, ex);
12435       ast_hangup(chan);
12436       return NULL;
12437    }
12438    while ((newms = ast_waitfor(chan, ms)) > 0) {
12439       f = ast_read(chan);
12440       if (!f) {
12441          /* Got hangup */
12442          break;
12443       }
12444       if (f->frametype == AST_FRAME_CONTROL) {
12445          switch (f->subclass) {
12446          case AST_CONTROL_ANSWER:
12447             /* Launch the PBX */
12448             ast_copy_string(chan->exten, pvt->pri->idleext, sizeof(chan->exten));
12449             ast_copy_string(chan->context, pvt->pri->idlecontext, sizeof(chan->context));
12450             chan->priority = 1;
12451             ast_verb(4, "Idle channel '%s' answered, sending to %s@%s\n", chan->name, chan->exten, chan->context);
12452             ast_pbx_run(chan);
12453             /* It's already hungup, return immediately */
12454             return NULL;
12455          case AST_CONTROL_BUSY:
12456             ast_verb(4, "Idle channel '%s' busy, waiting...\n", chan->name);
12457             break;
12458          case AST_CONTROL_CONGESTION:
12459             ast_verb(4, "Idle channel '%s' congested, waiting...\n", chan->name);
12460             break;
12461          };
12462       }
12463       ast_frfree(f);
12464       ms = newms;
12465    }
12466    /* Hangup the channel since nothing happend */
12467    ast_hangup(chan);
12468    return NULL;
12469 }
12470 #endif   /* defined(HAVE_PRI) */
12471 
12472 #if defined(HAVE_PRI)
12473 #ifndef PRI_RESTART
12474 #error "Upgrade your libpri"
12475 #endif
12476 static void dahdi_pri_message(struct pri *pri, char *s)
12477 {
12478    int x, y;
12479    int dchan = -1, span = -1;
12480    int dchancount = 0;
12481 
12482    if (pri) {
12483       for (x = 0; x < NUM_SPANS; x++) {
12484          for (y = 0; y < NUM_DCHANS; y++) {
12485             if (pris[x].dchans[y])
12486                dchancount++;
12487 
12488             if (pris[x].dchans[y] == pri)
12489                dchan = y;
12490          }
12491          if (dchan >= 0) {
12492             span = x;
12493             break;
12494          }
12495          dchancount = 0;
12496       }
12497       if (dchancount > 1 && (span > -1))
12498          ast_verbose("[Span %d D-Channel %d]%s", span, dchan, s);
12499       else
12500          ast_verbose("%s", s);
12501    } else
12502       ast_verbose("%s", s);
12503 
12504    ast_mutex_lock(&pridebugfdlock);
12505 
12506    if (pridebugfd >= 0) {
12507       if (write(pridebugfd, s, strlen(s)) < 0) {
12508          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
12509       }
12510    }
12511 
12512    ast_mutex_unlock(&pridebugfdlock);
12513 }
12514 #endif   /* defined(HAVE_PRI) */
12515 
12516 #if defined(HAVE_PRI)
12517 static void dahdi_pri_error(struct pri *pri, char *s)
12518 {
12519    int x, y;
12520    int dchan = -1, span = -1;
12521    int dchancount = 0;
12522 
12523    if (pri) {
12524       for (x = 0; x < NUM_SPANS; x++) {
12525          for (y = 0; y < NUM_DCHANS; y++) {
12526             if (pris[x].dchans[y])
12527                dchancount++;
12528 
12529             if (pris[x].dchans[y] == pri)
12530                dchan = y;
12531          }
12532          if (dchan >= 0) {
12533             span = x;
12534             break;
12535          }
12536          dchancount = 0;
12537       }
12538       if ((dchancount > 1) && (span > -1))
12539          ast_log(LOG_ERROR, "[Span %d D-Channel %d] PRI: %s", span, dchan, s);
12540       else
12541          ast_log(LOG_ERROR, "%s", s);
12542    } else
12543       ast_log(LOG_ERROR, "%s", s);
12544 
12545    ast_mutex_lock(&pridebugfdlock);
12546 
12547    if (pridebugfd >= 0) {
12548       if (write(pridebugfd, s, strlen(s)) < 0) {
12549          ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
12550       }
12551    }
12552 
12553    ast_mutex_unlock(&pridebugfdlock);
12554 }
12555 #endif   /* defined(HAVE_PRI) */
12556 
12557 #if defined(HAVE_PRI)
12558 static int pri_check_restart(struct dahdi_pri *pri)
12559 {
12560    do {
12561       pri->resetpos++;
12562    } while ((pri->resetpos < pri->numchans) &&
12563       (!pri->pvts[pri->resetpos] ||
12564       pri->pvts[pri->resetpos]->call ||
12565       pri->pvts[pri->resetpos]->resetting));
12566    if (pri->resetpos < pri->numchans) {
12567       /* Mark the channel as resetting and restart it */
12568       pri->pvts[pri->resetpos]->resetting = 1;
12569       pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[pri->resetpos]));
12570    } else {
12571       pri->resetting = 0;
12572       time(&pri->lastreset);
12573    }
12574    return 0;
12575 }
12576 #endif   /* defined(HAVE_PRI) */
12577 
12578 #if defined(HAVE_PRI)
12579 static int pri_hangup_all(struct dahdi_pvt *p, struct dahdi_pri *pri)
12580 {
12581    int x;
12582    int redo;
12583    ast_mutex_unlock(&pri->lock);
12584    ast_mutex_lock(&p->lock);
12585    do {
12586       redo = 0;
12587       for (x = 0; x < 3; x++) {
12588          while (p->subs[x].owner && ast_channel_trylock(p->subs[x].owner)) {
12589             redo++;
12590             DEADLOCK_AVOIDANCE(&p->lock);
12591          }
12592          if (p->subs[x].owner) {
12593             ast_queue_hangup_with_cause(p->subs[x].owner, AST_CAUSE_PRE_EMPTED);
12594             ast_channel_unlock(p->subs[x].owner);
12595          }
12596       }
12597    } while (redo);
12598    ast_mutex_unlock(&p->lock);
12599    ast_mutex_lock(&pri->lock);
12600    return 0;
12601 }
12602 #endif   /* defined(HAVE_PRI) */
12603 
12604 #if defined(HAVE_PRI)
12605 static char * redirectingreason2str(int redirectingreason)
12606 {
12607    switch (redirectingreason) {
12608    case 0:
12609       return "UNKNOWN";
12610    case 1:
12611       return "BUSY";
12612    case 2:
12613       return "NO_REPLY";
12614    case 0xF:
12615       return "UNCONDITIONAL";
12616    default:
12617       return "NOREDIRECT";
12618    }
12619 }
12620 #endif   /* defined(HAVE_PRI) */
12621 
12622 #if defined(HAVE_PRI)
12623 static void apply_plan_to_number(char *buf, size_t size, const struct dahdi_pri *pri, const char *number, const int plan)
12624 {
12625    if (pri->dialplan == -2) { /* autodetect the TON but leave the number untouched */
12626       snprintf(buf, size, "%s", number);
12627       return;
12628    }
12629    if (ast_strlen_zero(number)) { /* make sure a number exists so prefix isn't placed on an empty string */
12630       if (size) {
12631          *buf = '\0';
12632       }
12633       return;
12634    }
12635    switch (plan) {
12636    case PRI_INTERNATIONAL_ISDN:     /* Q.931 dialplan == 0x11 international dialplan => prepend international prefix digits */
12637       snprintf(buf, size, "%s%s", pri->internationalprefix, number);
12638       break;
12639    case PRI_NATIONAL_ISDN:       /* Q.931 dialplan == 0x21 national dialplan => prepend national prefix digits */
12640       snprintf(buf, size, "%s%s", pri->nationalprefix, number);
12641       break;
12642    case PRI_LOCAL_ISDN:       /* Q.931 dialplan == 0x41 local dialplan => prepend local prefix digits */
12643       snprintf(buf, size, "%s%s", pri->localprefix, number);
12644       break;
12645    case PRI_PRIVATE:       /* Q.931 dialplan == 0x49 private dialplan => prepend private prefix digits */
12646       snprintf(buf, size, "%s%s", pri->privateprefix, number);
12647       break;
12648    case PRI_UNKNOWN:       /* Q.931 dialplan == 0x00 unknown dialplan => prepend unknown prefix digits */
12649       snprintf(buf, size, "%s%s", pri->unknownprefix, number);
12650       break;
12651    default:          /* other Q.931 dialplan => don't twiddle with callingnum */
12652       snprintf(buf, size, "%s", number);
12653       break;
12654    }
12655 }
12656 #endif   /* defined(HAVE_PRI) */
12657 
12658 #if defined(HAVE_PRI)
12659 static void *pri_dchannel(void *vpri)
12660 {
12661    struct dahdi_pri *pri = vpri;
12662    pri_event *e;
12663    struct pollfd fds[NUM_DCHANS];
12664    int res;
12665    int chanpos = 0;
12666    int x;
12667    int haveidles;
12668    int activeidles;
12669    int nextidle = -1;
12670    struct ast_channel *c;
12671    struct timeval tv, lowest, *next;
12672    struct timeval lastidle = ast_tvnow();
12673    int doidling=0;
12674    char *cc;
12675    char idlen[80];
12676    struct ast_channel *idle;
12677    pthread_t p;
12678    time_t t;
12679    int i, which=-1;
12680    int numdchans;
12681    int cause=0;
12682    struct dahdi_pvt *crv;
12683    pthread_t threadid;
12684    char ani2str[6];
12685    char plancallingnum[256];
12686    char plancallingani[256];
12687    char calledtonstr[10];
12688 
12689    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
12690 
12691    gettimeofday(&lastidle, NULL);
12692    if (!ast_strlen_zero(pri->idledial) && !ast_strlen_zero(pri->idleext)) {
12693       /* Need to do idle dialing, check to be sure though */
12694       cc = strchr(pri->idleext, '@');
12695       if (cc) {
12696          *cc = '\0';
12697          cc++;
12698          ast_copy_string(pri->idlecontext, cc, sizeof(pri->idlecontext));
12699 #if 0
12700          /* Extensions may not be loaded yet */
12701          if (!ast_exists_extension(NULL, pri->idlecontext, pri->idleext, 1, NULL))
12702             ast_log(LOG_WARNING, "Extension '%s @ %s' does not exist\n", pri->idleext, pri->idlecontext);
12703          else
12704 #endif
12705             doidling = 1;
12706       } else
12707          ast_log(LOG_WARNING, "Idle dial string '%s' lacks '@context'\n", pri->idleext);
12708    }
12709    for (;;) {
12710       for (i = 0; i < NUM_DCHANS; i++) {
12711          if (!pri->dchannels[i])
12712             break;
12713          fds[i].fd = pri->fds[i];
12714          fds[i].events = POLLIN | POLLPRI;
12715          fds[i].revents = 0;
12716       }
12717       numdchans = i;
12718       time(&t);
12719       ast_mutex_lock(&pri->lock);
12720       if ((pri->switchtype != PRI_SWITCH_GR303_TMC) && (pri->sig != SIG_BRI_PTMP) && (pri->resetinterval > 0)) {
12721          if (pri->resetting && pri_is_up(pri)) {
12722             if (pri->resetpos < 0)
12723                pri_check_restart(pri);
12724          } else {
12725             if (!pri->resetting  && (t - pri->lastreset) >= pri->resetinterval) {
12726                pri->resetting = 1;
12727                pri->resetpos = -1;
12728             }
12729          }
12730       }
12731       /* Look for any idle channels if appropriate */
12732       if (doidling && pri_is_up(pri)) {
12733          nextidle = -1;
12734          haveidles = 0;
12735          activeidles = 0;
12736          for (x = pri->numchans; x >= 0; x--) {
12737             if (pri->pvts[x] && !pri->pvts[x]->owner &&
12738                !pri->pvts[x]->call) {
12739                if (haveidles < pri->minunused) {
12740                   haveidles++;
12741                } else if (!pri->pvts[x]->resetting) {
12742                   nextidle = x;
12743                   break;
12744                }
12745             } else if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall)
12746                activeidles++;
12747          }
12748          if (nextidle > -1) {
12749             if (ast_tvdiff_ms(ast_tvnow(), lastidle) > 1000) {
12750                /* Don't create a new idle call more than once per second */
12751                snprintf(idlen, sizeof(idlen), "%d/%s", pri->pvts[nextidle]->channel, pri->idledial);
12752                idle = dahdi_request("DAHDI", AST_FORMAT_ULAW, idlen, &cause);
12753                if (idle) {
12754                   pri->pvts[nextidle]->isidlecall = 1;
12755                   if (ast_pthread_create_background(&p, NULL, do_idle_thread, idle)) {
12756                      ast_log(LOG_WARNING, "Unable to start new thread for idle channel '%s'\n", idle->name);
12757                      dahdi_hangup(idle);
12758                   }
12759                } else
12760                   ast_log(LOG_WARNING, "Unable to request channel 'DAHDI/%s' for idle call\n", idlen);
12761                lastidle = ast_tvnow();
12762             }
12763          } else if ((haveidles < pri->minunused) &&
12764             (activeidles > pri->minidle)) {
12765             /* Mark something for hangup if there is something
12766                that can be hungup */
12767             for (x = pri->numchans; x >= 0; x--) {
12768                /* find a candidate channel */
12769                if (pri->pvts[x] && pri->pvts[x]->owner && pri->pvts[x]->isidlecall) {
12770                   pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
12771                   haveidles++;
12772                   /* Stop if we have enough idle channels or
12773                     can't spare any more active idle ones */
12774                   if ((haveidles >= pri->minunused) ||
12775                      (activeidles <= pri->minidle))
12776                      break;
12777                }
12778             }
12779          }
12780       }
12781       /* Start with reasonable max */
12782       lowest = ast_tv(60, 0);
12783       for (i = 0; i < NUM_DCHANS; i++) {
12784          /* Find lowest available d-channel */
12785          if (!pri->dchannels[i])
12786             break;
12787          if ((next = pri_schedule_next(pri->dchans[i]))) {
12788             /* We need relative time here */
12789             tv = ast_tvsub(*next, ast_tvnow());
12790             if (tv.tv_sec < 0) {
12791                tv = ast_tv(0,0);
12792             }
12793             if (doidling || pri->resetting) {
12794                if (tv.tv_sec > 1) {
12795                   tv = ast_tv(1, 0);
12796                }
12797             } else {
12798                if (tv.tv_sec > 60) {
12799                   tv = ast_tv(60, 0);
12800                }
12801             }
12802          } else if (doidling || pri->resetting) {
12803             /* Make sure we stop at least once per second if we're
12804                monitoring idle channels */
12805             tv = ast_tv(1,0);
12806          } else {
12807             /* Don't poll for more than 60 seconds */
12808             tv = ast_tv(60, 0);
12809          }
12810          if (!i || ast_tvcmp(tv, lowest) < 0) {
12811             lowest = tv;
12812          }
12813       }
12814       ast_mutex_unlock(&pri->lock);
12815 
12816       pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
12817       pthread_testcancel();
12818       e = NULL;
12819       res = poll(fds, numdchans, lowest.tv_sec * 1000 + lowest.tv_usec / 1000);
12820       pthread_testcancel();
12821       pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
12822 
12823       ast_mutex_lock(&pri->lock);
12824       if (!res) {
12825          for (which = 0; which < NUM_DCHANS; which++) {
12826             if (!pri->dchans[which])
12827                break;
12828             /* Just a timeout, run the scheduler */
12829             e = pri_schedule_run(pri->dchans[which]);
12830             if (e)
12831                break;
12832          }
12833       } else if (res > -1) {
12834          for (which = 0; which < NUM_DCHANS; which++) {
12835             if (!pri->dchans[which])
12836                break;
12837             if (fds[which].revents & POLLPRI) {
12838                /* Check for an event */
12839                x = 0;
12840                res = ioctl(pri->fds[which], DAHDI_GETEVENT, &x);
12841                if (x) {
12842                   ast_log(LOG_NOTICE, "PRI got event: %s (%d) on %s D-channel of span %d\n", event2str(x), x, pri_order(which), pri->span);
12843                   manager_event(EVENT_FLAG_SYSTEM, "PRIEvent",
12844                      "PRIEvent: %s\r\n"
12845                      "PRIEventCode: %d\r\n"
12846                      "D-channel: %s\r\n"
12847                      "Span: %d\r\n",
12848                      event2str(x),
12849                      x,
12850                      pri_order(which),
12851                      pri->span
12852                      );
12853                }
12854                /* Keep track of alarm state */
12855                if (x == DAHDI_EVENT_ALARM) {
12856                   pri->dchanavail[which] &= ~(DCHAN_NOTINALARM | DCHAN_UP);
12857                   pri_find_dchan(pri);
12858                } else if (x == DAHDI_EVENT_NOALARM) {
12859                   pri->dchanavail[which] |= DCHAN_NOTINALARM;
12860                   pri_restart(pri->dchans[which]);
12861                }
12862 
12863                ast_debug(1, "Got event %s (%d) on D-channel for span %d\n", event2str(x), x, pri->span);
12864             } else if (fds[which].revents & POLLIN) {
12865                e = pri_check_event(pri->dchans[which]);
12866             }
12867             if (e)
12868                break;
12869          }
12870       } else if (errno != EINTR)
12871          ast_log(LOG_WARNING, "pri_event returned error %d (%s)\n", errno, strerror(errno));
12872 
12873       if (e) {
12874          if (pri->debug)
12875             pri_dump_event(pri->dchans[which], e);
12876 
12877          if (e->e != PRI_EVENT_DCHAN_DOWN) {
12878             if (!(pri->dchanavail[which] & DCHAN_UP)) {
12879                ast_verb(2, "%s D-Channel on span %d up\n", pri_order(which), pri->span);
12880             }
12881             pri->dchanavail[which] |= DCHAN_UP;
12882          } else if (pri->sig != SIG_BRI_PTMP) {
12883             if (pri->dchanavail[which] & DCHAN_UP) {
12884                ast_verb(2, "%s D-Channel on span %d down\n", pri_order(which), pri->span);
12885             }
12886             pri->dchanavail[which] &= ~DCHAN_UP;
12887          }
12888 
12889          if ((e->e != PRI_EVENT_DCHAN_UP) && (e->e != PRI_EVENT_DCHAN_DOWN) && (pri->pri != pri->dchans[which]))
12890             /* Must be an NFAS group that has the secondary dchan active */
12891             pri->pri = pri->dchans[which];
12892 
12893          switch (e->e) {
12894          case PRI_EVENT_DCHAN_UP:
12895             pri->no_d_channels = 0;
12896             if (!pri->pri) pri_find_dchan(pri);
12897 
12898             /* Note presense of D-channel */
12899             time(&pri->lastreset);
12900 
12901             /* Restart in 5 seconds */
12902             if (pri->resetinterval > -1) {
12903                pri->lastreset -= pri->resetinterval;
12904                pri->lastreset += 5;
12905             }
12906             pri->resetting = 0;
12907             /* Take the channels from inalarm condition */
12908             for (i = 0; i < pri->numchans; i++)
12909                if (pri->pvts[i]) {
12910                   pri->pvts[i]->inalarm = 0;
12911                }
12912             break;
12913          case PRI_EVENT_DCHAN_DOWN:
12914             pri_find_dchan(pri);
12915             if (!pri_is_up(pri)) {
12916                pri->resetting = 0;
12917                /* Hangup active channels and put them in alarm mode */
12918                for (i = 0; i < pri->numchans; i++) {
12919                   struct dahdi_pvt *p = pri->pvts[i];
12920                   if (p) {
12921                      if (!p->pri || !p->pri->pri || pri_get_timer(p->pri->pri, PRI_TIMER_T309) < 0) {
12922                         /* T309 is not enabled : hangup calls when alarm occurs */
12923                         if (p->call) {
12924                            if (p->pri && p->pri->pri) {
12925                               pri_hangup(p->pri->pri, p->call, -1);
12926                               pri_destroycall(p->pri->pri, p->call);
12927                               p->call = NULL;
12928                            } else
12929                               ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
12930                         }
12931                         if (p->realcall) {
12932                            pri_hangup_all(p->realcall, pri);
12933                         } else if (p->owner)
12934                            p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
12935                      }
12936                      /* For PTMP connections with non persistent layer 2 we want
12937                       * to *not* declare inalarm unless there actually is an alarm */
12938                      if (p->sig != SIG_BRI_PTMP) {
12939                         p->inalarm = 1;
12940                      }
12941                   }
12942                }
12943             }
12944             break;
12945          case PRI_EVENT_RESTART:
12946             if (e->restart.channel > -1) {
12947                chanpos = pri_find_principle(pri, e->restart.channel);
12948                if (chanpos < 0)
12949                   ast_log(LOG_WARNING, "Restart requested on odd/unavailable channel number %d/%d on span %d\n",
12950                      PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
12951                else {
12952                   ast_verb(3, "B-channel %d/%d restarted on span %d\n",
12953                         PRI_SPAN(e->restart.channel), PRI_CHANNEL(e->restart.channel), pri->span);
12954                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
12955                   if (pri->pvts[chanpos]->call) {
12956                      pri_destroycall(pri->pri, pri->pvts[chanpos]->call);
12957                      pri->pvts[chanpos]->call = NULL;
12958                   }
12959                   /* Force soft hangup if appropriate */
12960                   if (pri->pvts[chanpos]->realcall)
12961                      pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
12962                   else if (pri->pvts[chanpos]->owner)
12963                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
12964                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
12965                }
12966             } else {
12967                ast_verb(3, "Restart on requested on entire span %d\n", pri->span);
12968                for (x = 0; x < pri->numchans; x++)
12969                   if (pri->pvts[x]) {
12970                      ast_mutex_lock(&pri->pvts[x]->lock);
12971                      if (pri->pvts[x]->call) {
12972                         pri_destroycall(pri->pri, pri->pvts[x]->call);
12973                         pri->pvts[x]->call = NULL;
12974                      }
12975                      if (pri->pvts[x]->realcall)
12976                         pri_hangup_all(pri->pvts[x]->realcall, pri);
12977                      else if (pri->pvts[x]->owner)
12978                         pri->pvts[x]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
12979                      ast_mutex_unlock(&pri->pvts[x]->lock);
12980                   }
12981             }
12982             break;
12983          case PRI_EVENT_KEYPAD_DIGIT:
12984             chanpos = pri_find_principle(pri, e->digit.channel);
12985             if (chanpos < 0) {
12986                ast_log(LOG_WARNING, "KEYPAD_DIGITs received on unconfigured channel %d/%d span %d\n",
12987                   PRI_SPAN(e->digit.channel), PRI_CHANNEL(e->digit.channel), pri->span);
12988             } else {
12989                chanpos = pri_fixup_principle(pri, chanpos, e->digit.call);
12990                if (chanpos > -1) {
12991                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
12992                   /* queue DTMF frame if the PBX for this call was already started (we're forwarding KEYPAD_DIGITs further on */
12993                   if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && pri->pvts[chanpos]->call==e->digit.call && pri->pvts[chanpos]->owner) {
12994                      /* how to do that */
12995                      int digitlen = strlen(e->digit.digits);
12996                      char digit;
12997                      int i;
12998                      for (i = 0; i < digitlen; i++) {
12999                         digit = e->digit.digits[i];
13000                         {
13001                            struct ast_frame f = { AST_FRAME_DTMF, digit, };
13002                            dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13003                         }
13004                      }
13005                   }
13006                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13007                }
13008             }
13009             break;
13010 
13011          case PRI_EVENT_INFO_RECEIVED:
13012             chanpos = pri_find_principle(pri, e->ring.channel);
13013             if (chanpos < 0) {
13014                ast_log(LOG_WARNING, "INFO received on unconfigured channel %d/%d span %d\n",
13015                   PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
13016             } else {
13017                chanpos = pri_fixup_principle(pri, chanpos, e->ring.call);
13018                if (chanpos > -1) {
13019                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13020                   /* queue DTMF frame if the PBX for this call was already started (we're forwarding INFORMATION further on */
13021                   if ((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && pri->pvts[chanpos]->call==e->ring.call && pri->pvts[chanpos]->owner) {
13022                      /* how to do that */
13023                      int digitlen = strlen(e->ring.callednum);
13024                      char digit;
13025                      int i;
13026                      for (i = 0; i < digitlen; i++) {
13027                         digit = e->ring.callednum[i];
13028                         {
13029                            struct ast_frame f = { AST_FRAME_DTMF, digit, };
13030                            dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13031                         }
13032                      }
13033                   }
13034                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13035                }
13036             }
13037             break;
13038          case PRI_EVENT_RING:
13039             crv = NULL;
13040             if (e->ring.channel == -1)
13041                chanpos = pri_find_empty_chan(pri, 1);
13042             else
13043                chanpos = pri_find_principle(pri, e->ring.channel);
13044             /* if no channel specified find one empty */
13045             if (chanpos < 0) {
13046                ast_log(LOG_WARNING, "Ring requested on unconfigured channel %d/%d span %d\n",
13047                   PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
13048             } else {
13049                ast_mutex_lock(&pri->pvts[chanpos]->lock);
13050                if (pri->pvts[chanpos]->owner) {
13051                   if (pri->pvts[chanpos]->call == e->ring.call) {
13052                      ast_log(LOG_WARNING, "Duplicate setup requested on channel %d/%d already in use on span %d\n",
13053                         PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
13054                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13055                      break;
13056                   } else {
13057                      /* This is where we handle initial glare */
13058                      ast_debug(1, "Ring requested on channel %d/%d already in use or previously requested on span %d.  Attempting to renegotiate channel.\n",
13059                      PRI_SPAN(e->ring.channel), PRI_CHANNEL(e->ring.channel), pri->span);
13060                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13061                      chanpos = -1;
13062                   }
13063                }
13064                if (chanpos > -1)
13065                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13066             }
13067             if ((chanpos < 0) && (e->ring.flexible))
13068                chanpos = pri_find_empty_chan(pri, 1);
13069             if (chanpos > -1) {
13070                ast_mutex_lock(&pri->pvts[chanpos]->lock);
13071                if (pri->switchtype == PRI_SWITCH_GR303_TMC) {
13072                   /* Should be safe to lock CRV AFAIK while bearer is still locked */
13073                   crv = pri_find_crv(pri, pri_get_crv(pri->pri, e->ring.call, NULL));
13074                   if (crv)
13075                      ast_mutex_lock(&crv->lock);
13076                   if (!crv || crv->owner) {
13077                      pri->pvts[chanpos]->call = NULL;
13078                      if (crv) {
13079                         if (crv->owner)
13080                            crv->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13081                         ast_log(LOG_WARNING, "Call received for busy CRV %d on span %d\n", pri_get_crv(pri->pri, e->ring.call, NULL), pri->span);
13082                      } else
13083                         ast_log(LOG_NOTICE, "Call received for unconfigured CRV %d on span %d\n", pri_get_crv(pri->pri, e->ring.call, NULL), pri->span);
13084                      pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_INVALID_CALL_REFERENCE);
13085                      if (crv)
13086                         ast_mutex_unlock(&crv->lock);
13087                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13088                      break;
13089                   }
13090                }
13091                pri->pvts[chanpos]->call = e->ring.call;
13092                apply_plan_to_number(plancallingnum, sizeof(plancallingnum), pri, e->ring.callingnum, e->ring.callingplan);
13093                if (pri->pvts[chanpos]->use_callerid) {
13094                   ast_shrink_phone_number(plancallingnum);
13095                   ast_copy_string(pri->pvts[chanpos]->cid_num, plancallingnum, sizeof(pri->pvts[chanpos]->cid_num));
13096 #ifdef PRI_ANI
13097                   if (!ast_strlen_zero(e->ring.callingani)) {
13098                      apply_plan_to_number(plancallingani, sizeof(plancallingani), pri, e->ring.callingani, e->ring.callingplanani);
13099                      ast_shrink_phone_number(plancallingani);
13100                      ast_copy_string(pri->pvts[chanpos]->cid_ani, plancallingani, sizeof(pri->pvts[chanpos]->cid_ani));
13101                   } else {
13102                      pri->pvts[chanpos]->cid_ani[0] = '\0';
13103                   }
13104 #endif
13105                   ast_copy_string(pri->pvts[chanpos]->cid_name, e->ring.callingname, sizeof(pri->pvts[chanpos]->cid_name));
13106                   pri->pvts[chanpos]->cid_ton = e->ring.callingplan; /* this is the callingplan (TON/NPI), e->ring.callingplan>>4 would be the TON */
13107                } else {
13108                   pri->pvts[chanpos]->cid_num[0] = '\0';
13109                   pri->pvts[chanpos]->cid_ani[0] = '\0';
13110                   pri->pvts[chanpos]->cid_name[0] = '\0';
13111                   pri->pvts[chanpos]->cid_ton = 0;
13112                }
13113                apply_plan_to_number(pri->pvts[chanpos]->rdnis, sizeof(pri->pvts[chanpos]->rdnis), pri,
13114                   e->ring.redirectingnum, e->ring.callingplanrdnis);
13115 
13116                /* Set DNID on all incoming calls -- even immediate */
13117                ast_copy_string(pri->pvts[chanpos]->dnid, e->ring.callednum, sizeof(pri->pvts[chanpos]->dnid));
13118 
13119                /* If immediate=yes go to s|1 */
13120                if (pri->pvts[chanpos]->immediate) {
13121                   ast_verb(3, "Going to extension s|1 because of immediate=yes\n");
13122                   pri->pvts[chanpos]->exten[0] = 's';
13123                   pri->pvts[chanpos]->exten[1] = '\0';
13124                }
13125                /* Get called number */
13126                else if (!ast_strlen_zero(e->ring.callednum)) {
13127                   ast_copy_string(pri->pvts[chanpos]->exten, e->ring.callednum, sizeof(pri->pvts[chanpos]->exten));
13128                } else if (pri->overlapdial)
13129                   pri->pvts[chanpos]->exten[0] = '\0';
13130                else {
13131                   /* Some PRI circuits are set up to send _no_ digits.  Handle them as 's'. */
13132                   pri->pvts[chanpos]->exten[0] = 's';
13133                   pri->pvts[chanpos]->exten[1] = '\0';
13134                }
13135                /* No number yet, but received "sending complete"? */
13136                if (e->ring.complete && (ast_strlen_zero(e->ring.callednum))) {
13137                   ast_verb(3, "Going to extension s|1 because of Complete received\n");
13138                   pri->pvts[chanpos]->exten[0] = 's';
13139                   pri->pvts[chanpos]->exten[1] = '\0';
13140                }
13141 
13142                /* Make sure extension exists (or in overlap dial mode, can exist) */
13143                if (((pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING) && ast_canmatch_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) ||
13144                   ast_exists_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
13145                   /* Setup law */
13146                   int law;
13147                   if (pri->switchtype != PRI_SWITCH_GR303_TMC) {
13148                      /* Set to audio mode at this point */
13149                      law = 1;
13150                      if (ioctl(pri->pvts[chanpos]->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &law) == -1)
13151                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n", pri->pvts[chanpos]->channel, law, strerror(errno));
13152                   }
13153                   if (e->ring.layer1 == PRI_LAYER_1_ALAW)
13154                      law = DAHDI_LAW_ALAW;
13155                   else
13156                      law = DAHDI_LAW_MULAW;
13157                   res = dahdi_setlaw(pri->pvts[chanpos]->subs[SUB_REAL].dfd, law);
13158                   if (res < 0)
13159                      ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pri->pvts[chanpos]->channel);
13160                   res = set_actual_gain(pri->pvts[chanpos]->subs[SUB_REAL].dfd, 0, pri->pvts[chanpos]->rxgain, pri->pvts[chanpos]->txgain, law);
13161                   if (res < 0)
13162                      ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pri->pvts[chanpos]->channel);
13163                   if (e->ring.complete || !(pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)) {
13164                      /* Just announce proceeding */
13165                      pri->pvts[chanpos]->proceeding = 1;
13166                      pri_proceeding(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 0);
13167                   } else {
13168                      if (pri->switchtype != PRI_SWITCH_GR303_TMC)
13169                         pri_need_more_info(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
13170                      else
13171                         pri_answer(pri->pri, e->ring.call, PVT_TO_CHANNEL(pri->pvts[chanpos]), 1);
13172                   }
13173                   /* Get the use_callingpres state */
13174                   pri->pvts[chanpos]->callingpres = e->ring.callingpres;
13175 
13176                   /* Start PBX */
13177                   if (!e->ring.complete
13178                      && (pri->overlapdial & DAHDI_OVERLAPDIAL_INCOMING)
13179                      && ast_matchmore_extension(NULL, pri->pvts[chanpos]->context, pri->pvts[chanpos]->exten, 1, pri->pvts[chanpos]->cid_num)) {
13180                      /*
13181                       * Release the PRI lock while we create the channel
13182                       * so other threads can send D channel messages.
13183                       */
13184                      ast_mutex_unlock(&pri->lock);
13185                      if (crv) {
13186                         /* Set bearer and such */
13187                         pri_assign_bearer(crv, pri, pri->pvts[chanpos]);
13188                         c = dahdi_new(crv, AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
13189                         pri->pvts[chanpos]->owner = &inuse;
13190                         ast_debug(1, "Started up crv %d:%d on bearer channel %d\n", pri->trunkgroup, crv->channel, crv->bearer->channel);
13191                      } else {
13192                         c = dahdi_new(pri->pvts[chanpos], AST_STATE_RESERVED, 0, SUB_REAL, law, e->ring.ctype);
13193                      }
13194                      ast_mutex_lock(&pri->lock);
13195                      if (c) {
13196                         if (!ast_strlen_zero(e->ring.callingsubaddr)) {
13197                            pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
13198                         }
13199                         if (e->ring.ani2 >= 0) {
13200                            snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
13201                            pbx_builtin_setvar_helper(c, "ANI2", ani2str);
13202                            pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
13203                         }
13204 
13205 #ifdef SUPPORT_USERUSER
13206                         if (!ast_strlen_zero(e->ring.useruserinfo)) {
13207                            pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
13208                         }
13209 #endif
13210 
13211                         snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
13212                         pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
13213                         if (e->ring.redirectingreason >= 0)
13214                            pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
13215                      }
13216                      if (c && !ast_pthread_create_detached(&threadid, NULL, ss_thread, c)) {
13217                         ast_verb(3, "Accepting overlap call from '%s' to '%s' on channel %d/%d, span %d\n",
13218                            plancallingnum, S_OR(pri->pvts[chanpos]->exten, "<unspecified>"),
13219                            pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
13220                      } else {
13221                         ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
13222                            pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
13223                         if (c)
13224                            ast_hangup(c);
13225                         else {
13226                            pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
13227                            pri->pvts[chanpos]->call = NULL;
13228                         }
13229                      }
13230                   } else {
13231                      /*
13232                       * Release the PRI lock while we create the channel
13233                       * so other threads can send D channel messages.
13234                       */
13235                      ast_mutex_unlock(&pri->lock);
13236                      c = dahdi_new(pri->pvts[chanpos], AST_STATE_RING, 0, SUB_REAL, law, e->ring.ctype);
13237                      ast_mutex_lock(&pri->lock);
13238                      if (c) {
13239                         /*
13240                          * It is reasonably safe to set the following
13241                          * channel variables while the PRI and DAHDI private
13242                          * structures are locked.  The PBX has not been
13243                          * started yet and it is unlikely that any other task
13244                          * will do anything with the channel we have just
13245                          * created.
13246                          */
13247                         if (!ast_strlen_zero(e->ring.callingsubaddr)) {
13248                            pbx_builtin_setvar_helper(c, "CALLINGSUBADDR", e->ring.callingsubaddr);
13249                         }
13250                         if (e->ring.ani2 >= 0) {
13251                            snprintf(ani2str, sizeof(ani2str), "%d", e->ring.ani2);
13252                            pbx_builtin_setvar_helper(c, "ANI2", ani2str);
13253                            pri->pvts[chanpos]->cid_ani2 = e->ring.ani2;
13254                         }
13255 
13256 #ifdef SUPPORT_USERUSER
13257                         if (!ast_strlen_zero(e->ring.useruserinfo)) {
13258                            pbx_builtin_setvar_helper(c, "USERUSERINFO", e->ring.useruserinfo);
13259                         }
13260 #endif
13261 
13262                         if (e->ring.redirectingreason >= 0)
13263                            pbx_builtin_setvar_helper(c, "PRIREDIRECTREASON", redirectingreason2str(e->ring.redirectingreason));
13264 
13265                         snprintf(calledtonstr, sizeof(calledtonstr), "%d", e->ring.calledplan);
13266                         pbx_builtin_setvar_helper(c, "CALLEDTON", calledtonstr);
13267                      }
13268                      if (c && !ast_pbx_start(c)) {
13269                         ast_verb(3, "Accepting call from '%s' to '%s' on channel %d/%d, span %d\n",
13270                            plancallingnum, pri->pvts[chanpos]->exten,
13271                            pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
13272 
13273                         dahdi_enable_ec(pri->pvts[chanpos]);
13274                      } else {
13275                         ast_log(LOG_WARNING, "Unable to start PBX on channel %d/%d, span %d\n",
13276                            pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span);
13277                         if (c) {
13278                            ast_hangup(c);
13279                         } else {
13280                            pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_SWITCH_CONGESTION);
13281                            pri->pvts[chanpos]->call = NULL;
13282                         }
13283                      }
13284                   }
13285                } else {
13286                   ast_verb(3, "Extension '%s' in context '%s' from '%s' does not exist.  Rejecting call on channel %d/%d, span %d\n",
13287                      pri->pvts[chanpos]->exten, pri->pvts[chanpos]->context, pri->pvts[chanpos]->cid_num, pri->pvts[chanpos]->logicalspan,
13288                      pri->pvts[chanpos]->prioffset, pri->span);
13289                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_UNALLOCATED);
13290                   pri->pvts[chanpos]->call = NULL;
13291                   pri->pvts[chanpos]->exten[0] = '\0';
13292                }
13293                if (crv)
13294                   ast_mutex_unlock(&crv->lock);
13295                ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13296             } else {
13297                if (e->ring.flexible)
13298                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION);
13299                else
13300                   pri_hangup(pri->pri, e->ring.call, PRI_CAUSE_REQUESTED_CHAN_UNAVAIL);
13301             }
13302             break;
13303          case PRI_EVENT_RINGING:
13304             chanpos = pri_find_principle(pri, e->ringing.channel);
13305             if (chanpos < 0) {
13306                ast_log(LOG_WARNING, "Ringing requested on unconfigured channel %d/%d span %d\n",
13307                   PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
13308             } else {
13309                chanpos = pri_fixup_principle(pri, chanpos, e->ringing.call);
13310                if (chanpos < 0) {
13311                   ast_log(LOG_WARNING, "Ringing requested on channel %d/%d not in use on span %d\n",
13312                      PRI_SPAN(e->ringing.channel), PRI_CHANNEL(e->ringing.channel), pri->span);
13313                } else {
13314                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13315                   if (ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
13316                      dahdi_enable_ec(pri->pvts[chanpos]);
13317                      pri->pvts[chanpos]->subs[SUB_REAL].needringing = 1;
13318                      pri->pvts[chanpos]->alerting = 1;
13319                   } else
13320                      ast_debug(1, "Deferring ringing notification because of extra digits to dial...\n");
13321 
13322                   if (
13323 #ifdef PRI_PROGRESS_MASK
13324                      e->ringing.progressmask & PRI_PROG_INBAND_AVAILABLE
13325 #else
13326                      e->ringing.progress == 8
13327 #endif
13328                      ) {
13329                      /* Now we can do call progress detection */
13330                      if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
13331                         /* RINGING detection isn't required because we got ALERTING signal */
13332                         ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features & ~DSP_PROGRESS_RINGING);
13333                         pri->pvts[chanpos]->dsp_features = 0;
13334                      }
13335                   }
13336 
13337 #ifdef SUPPORT_USERUSER
13338                   if (!ast_strlen_zero(e->ringing.useruserinfo)) {
13339                      struct ast_channel *owner = pri->pvts[chanpos]->owner;
13340                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13341                      pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->ringing.useruserinfo);
13342                      ast_mutex_lock(&pri->pvts[chanpos]->lock);
13343                   }
13344 #endif
13345 
13346                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13347                }
13348             }
13349             break;
13350          case PRI_EVENT_PROGRESS:
13351             /* Get chan value if e->e is not PRI_EVNT_RINGING */
13352             chanpos = pri_find_principle(pri, e->proceeding.channel);
13353             if (chanpos > -1) {
13354                if ((!pri->pvts[chanpos]->progress)
13355 #ifdef PRI_PROGRESS_MASK
13356                   || (e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE)
13357 #else
13358                   || (e->proceeding.progress == 8)
13359 #endif
13360                   ) {
13361                   struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, };
13362 
13363                   if (e->proceeding.cause > -1) {
13364                      ast_verb(3, "PROGRESS with cause code %d received\n", e->proceeding.cause);
13365 
13366                      /* Work around broken, out of spec USER_BUSY cause in a progress message */
13367                      if (e->proceeding.cause == AST_CAUSE_USER_BUSY) {
13368                         if (pri->pvts[chanpos]->owner) {
13369                            ast_verb(3, "PROGRESS with 'user busy' received, signalling AST_CONTROL_BUSY instead of AST_CONTROL_PROGRESS\n");
13370 
13371                            pri->pvts[chanpos]->owner->hangupcause = e->proceeding.cause;
13372                            f.subclass = AST_CONTROL_BUSY;
13373                         }
13374                      }
13375                   }
13376 
13377                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13378                   ast_debug(1, "Queuing frame from PRI_EVENT_PROGRESS on channel %d/%d span %d\n",
13379                      pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
13380                   dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13381                   if (
13382 #ifdef PRI_PROGRESS_MASK
13383                      e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
13384 #else
13385                      e->proceeding.progress == 8
13386 #endif
13387                      ) {
13388                      /* Now we can do call progress detection */
13389                      if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
13390                         ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
13391                         pri->pvts[chanpos]->dsp_features = 0;
13392                      }
13393                      /* Bring voice path up */
13394                      f.subclass = AST_CONTROL_PROGRESS;
13395                      dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13396                   }
13397                   pri->pvts[chanpos]->progress = 1;
13398                   pri->pvts[chanpos]->dialing = 0;
13399                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13400                }
13401             }
13402             break;
13403          case PRI_EVENT_PROCEEDING:
13404             chanpos = pri_find_principle(pri, e->proceeding.channel);
13405             if (chanpos > -1) {
13406                if (!pri->pvts[chanpos]->proceeding) {
13407                   struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_PROCEEDING, };
13408 
13409                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13410                   ast_debug(1, "Queuing frame from PRI_EVENT_PROCEEDING on channel %d/%d span %d\n",
13411                      pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset,pri->span);
13412                   dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13413                   if (
13414 #ifdef PRI_PROGRESS_MASK
13415                      e->proceeding.progressmask & PRI_PROG_INBAND_AVAILABLE
13416 #else
13417                      e->proceeding.progress == 8
13418 #endif
13419                      ) {
13420                      /* Now we can do call progress detection */
13421                      if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
13422                         ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
13423                         pri->pvts[chanpos]->dsp_features = 0;
13424                      }
13425                      /* Bring voice path up */
13426                      f.subclass = AST_CONTROL_PROGRESS;
13427                      dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13428                   }
13429                   pri->pvts[chanpos]->proceeding = 1;
13430                   pri->pvts[chanpos]->dialing = 0;
13431                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13432                }
13433             }
13434             break;
13435          case PRI_EVENT_FACNAME:
13436             chanpos = pri_find_principle(pri, e->facname.channel);
13437             if (chanpos < 0) {
13438                ast_log(LOG_WARNING, "Facility Name requested on unconfigured channel %d/%d span %d\n",
13439                   PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
13440             } else {
13441                chanpos = pri_fixup_principle(pri, chanpos, e->facname.call);
13442                if (chanpos < 0) {
13443                   ast_log(LOG_WARNING, "Facility Name requested on channel %d/%d not in use on span %d\n",
13444                      PRI_SPAN(e->facname.channel), PRI_CHANNEL(e->facname.channel), pri->span);
13445                } else if (pri->pvts[chanpos]->use_callerid) {
13446                   /* Re-use *69 field for PRI */
13447                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13448                   ast_copy_string(pri->pvts[chanpos]->lastcid_num, e->facname.callingnum, sizeof(pri->pvts[chanpos]->lastcid_num));
13449                   ast_copy_string(pri->pvts[chanpos]->lastcid_name, e->facname.callingname, sizeof(pri->pvts[chanpos]->lastcid_name));
13450                   pri->pvts[chanpos]->subs[SUB_REAL].needcallerid = 1;
13451                   dahdi_enable_ec(pri->pvts[chanpos]);
13452                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13453                }
13454             }
13455             break;
13456          case PRI_EVENT_ANSWER:
13457             chanpos = pri_find_principle(pri, e->answer.channel);
13458             if (chanpos < 0) {
13459                ast_log(LOG_WARNING, "Answer on unconfigured channel %d/%d span %d\n",
13460                   PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
13461             } else {
13462                chanpos = pri_fixup_principle(pri, chanpos, e->answer.call);
13463                if (chanpos < 0) {
13464                   ast_log(LOG_WARNING, "Answer requested on channel %d/%d not in use on span %d\n",
13465                      PRI_SPAN(e->answer.channel), PRI_CHANNEL(e->answer.channel), pri->span);
13466                } else {
13467                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13468                   /* Now we can do call progress detection */
13469 
13470                   /* We changed this so it turns on the DSP no matter what... progress or no progress.
13471                    * By this time, we need DTMF detection and other features that were previously disabled
13472                    * -- Matt F */
13473                   if (pri->pvts[chanpos]->dsp && pri->pvts[chanpos]->dsp_features) {
13474                      ast_dsp_set_features(pri->pvts[chanpos]->dsp, pri->pvts[chanpos]->dsp_features);
13475                      pri->pvts[chanpos]->dsp_features = 0;
13476                   }
13477                   if (pri->pvts[chanpos]->realcall && (pri->pvts[chanpos]->realcall->sig == SIG_FXSKS)) {
13478                      ast_debug(1, "Starting up GR-303 trunk now that we got CONNECT...\n");
13479                      x = DAHDI_START;
13480                      res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
13481                      if (res < 0) {
13482                         if (errno != EINPROGRESS) {
13483                            ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
13484                         }
13485                      }
13486                   } else if (!ast_strlen_zero(pri->pvts[chanpos]->dop.dialstr)) {
13487                      pri->pvts[chanpos]->dialing = 1;
13488                      /* Send any "w" waited stuff */
13489                      res = ioctl(pri->pvts[chanpos]->subs[SUB_REAL].dfd, DAHDI_DIAL, &pri->pvts[chanpos]->dop);
13490                      if (res < 0) {
13491                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d: %s\n", pri->pvts[chanpos]->channel, strerror(errno));
13492                         pri->pvts[chanpos]->dop.dialstr[0] = '\0';
13493                      } else
13494                         ast_debug(1, "Sent deferred digit string: %s\n", pri->pvts[chanpos]->dop.dialstr);
13495 
13496                      pri->pvts[chanpos]->dop.dialstr[0] = '\0';
13497                   } else if (pri->pvts[chanpos]->confirmanswer) {
13498                      ast_debug(1, "Waiting on answer confirmation on channel %d!\n", pri->pvts[chanpos]->channel);
13499                   } else {
13500                      pri->pvts[chanpos]->dialing = 0;
13501                      pri->pvts[chanpos]->subs[SUB_REAL].needanswer =1;
13502                      /* Enable echo cancellation if it's not on already */
13503                      dahdi_enable_ec(pri->pvts[chanpos]);
13504                   }
13505 
13506 #ifdef SUPPORT_USERUSER
13507                   if (!ast_strlen_zero(e->answer.useruserinfo)) {
13508                      struct ast_channel *owner = pri->pvts[chanpos]->owner;
13509                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13510                      pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->answer.useruserinfo);
13511                      ast_mutex_lock(&pri->pvts[chanpos]->lock);
13512                   }
13513 #endif
13514 
13515                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13516                }
13517             }
13518             break;
13519          case PRI_EVENT_HANGUP:
13520             chanpos = pri_find_principle(pri, e->hangup.channel);
13521             if (chanpos < 0) {
13522                ast_log(LOG_WARNING, "Hangup requested on unconfigured channel %d/%d span %d\n",
13523                   PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13524             } else {
13525                chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
13526                if (chanpos > -1) {
13527                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13528                   if (!pri->pvts[chanpos]->alreadyhungup) {
13529                      /* we're calling here dahdi_hangup so once we get there we need to clear p->call after calling pri_hangup */
13530                      pri->pvts[chanpos]->alreadyhungup = 1;
13531                      if (pri->pvts[chanpos]->realcall)
13532                         pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
13533                      else if (pri->pvts[chanpos]->owner) {
13534                         /* Queue a BUSY instead of a hangup if our cause is appropriate */
13535                         pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
13536                         switch (pri->pvts[chanpos]->owner->_state) {
13537                         case AST_STATE_BUSY:
13538                         case AST_STATE_UP:
13539                            pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13540                            break;
13541                         default:
13542                            if (!pri->pvts[chanpos]->outgoing) {
13543                               /*
13544                                * The incoming call leg hung up before getting
13545                                * connected so just hangup the call.
13546                                */
13547                               pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13548                               break;
13549                            }
13550                            switch (e->hangup.cause) {
13551                            case PRI_CAUSE_USER_BUSY:
13552                               pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
13553                               break;
13554                            case PRI_CAUSE_CALL_REJECTED:
13555                            case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
13556                            case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
13557                            case PRI_CAUSE_SWITCH_CONGESTION:
13558                            case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
13559                            case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
13560                               pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
13561                               break;
13562                            default:
13563                               pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13564                            }
13565                            break;
13566                         }
13567                      }
13568                      ast_verb(3, "Channel %d/%d, span %d got hangup, cause %d\n",
13569                            pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, e->hangup.cause);
13570                   } else {
13571                      pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
13572                      pri->pvts[chanpos]->call = NULL;
13573                   }
13574                   if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
13575                      ast_verb(3, "Forcing restart of channel %d/%d on span %d since channel reported in use\n",
13576                            PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13577                      pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
13578                      pri->pvts[chanpos]->resetting = 1;
13579                   }
13580                   if (e->hangup.aoc_units > -1)
13581                      ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
13582                            pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
13583 
13584 #ifdef SUPPORT_USERUSER
13585                   if (pri->pvts[chanpos]->owner && !ast_strlen_zero(e->hangup.useruserinfo)) {
13586                      struct ast_channel *owner = pri->pvts[chanpos]->owner;
13587                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13588                      pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->hangup.useruserinfo);
13589                      ast_mutex_lock(&pri->pvts[chanpos]->lock);
13590                   }
13591 #endif
13592 
13593                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13594                } else {
13595                   ast_log(LOG_WARNING, "Hangup on bad channel %d/%d on span %d\n",
13596                      PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13597                }
13598             }
13599             break;
13600 #ifndef PRI_EVENT_HANGUP_REQ
13601 #error please update libpri
13602 #endif
13603          case PRI_EVENT_HANGUP_REQ:
13604             chanpos = pri_find_principle(pri, e->hangup.channel);
13605             if (chanpos < 0) {
13606                ast_log(LOG_WARNING, "Hangup REQ requested on unconfigured channel %d/%d span %d\n",
13607                   PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13608             } else {
13609                chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
13610                if (chanpos > -1) {
13611                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13612                   if (pri->pvts[chanpos]->realcall)
13613                      pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
13614                   else if (pri->pvts[chanpos]->owner) {
13615                      pri->pvts[chanpos]->owner->hangupcause = e->hangup.cause;
13616                      switch (pri->pvts[chanpos]->owner->_state) {
13617                      case AST_STATE_BUSY:
13618                      case AST_STATE_UP:
13619                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13620                         break;
13621                      default:
13622                         if (!pri->pvts[chanpos]->outgoing) {
13623                            /*
13624                             * The incoming call leg hung up before getting
13625                             * connected so just hangup the call.
13626                             */
13627                            pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13628                            break;
13629                         }
13630                         switch (e->hangup.cause) {
13631                         case PRI_CAUSE_USER_BUSY:
13632                            pri->pvts[chanpos]->subs[SUB_REAL].needbusy =1;
13633                            break;
13634                         case PRI_CAUSE_CALL_REJECTED:
13635                         case PRI_CAUSE_NETWORK_OUT_OF_ORDER:
13636                         case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
13637                         case PRI_CAUSE_SWITCH_CONGESTION:
13638                         case PRI_CAUSE_DESTINATION_OUT_OF_ORDER:
13639                         case PRI_CAUSE_NORMAL_TEMPORARY_FAILURE:
13640                            pri->pvts[chanpos]->subs[SUB_REAL].needcongestion =1;
13641                            break;
13642                         default:
13643                            pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13644                            break;
13645                         }
13646                         break;
13647                      }
13648                      ast_verb(3, "Channel %d/%d, span %d got hangup request, cause %d\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span, e->hangup.cause);
13649                      if (e->hangup.aoc_units > -1)
13650                         ast_verb(3, "Channel %d/%d, span %d received AOC-E charging %d unit%s\n",
13651                               pri->pvts[chanpos]->logicalspan, pri->pvts[chanpos]->prioffset, pri->span, (int)e->hangup.aoc_units, (e->hangup.aoc_units == 1) ? "" : "s");
13652                   } else {
13653                      pri_hangup(pri->pri, pri->pvts[chanpos]->call, e->hangup.cause);
13654                      pri->pvts[chanpos]->call = NULL;
13655                   }
13656                   if (e->hangup.cause == PRI_CAUSE_REQUESTED_CHAN_UNAVAIL) {
13657                      ast_verb(3, "Forcing restart of channel %d/%d span %d since channel reported in use\n",
13658                            PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13659                      pri_reset(pri->pri, PVT_TO_CHANNEL(pri->pvts[chanpos]));
13660                      pri->pvts[chanpos]->resetting = 1;
13661                   }
13662 
13663 #ifdef SUPPORT_USERUSER
13664                   if (!ast_strlen_zero(e->hangup.useruserinfo)) {
13665                      struct ast_channel *owner = pri->pvts[chanpos]->owner;
13666                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13667                      pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->hangup.useruserinfo);
13668                      ast_mutex_lock(&pri->pvts[chanpos]->lock);
13669                   }
13670 #endif
13671 
13672                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13673                } else {
13674                   ast_log(LOG_WARNING, "Hangup REQ on bad channel %d/%d on span %d\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13675                }
13676             }
13677             break;
13678          case PRI_EVENT_HANGUP_ACK:
13679             chanpos = pri_find_principle(pri, e->hangup.channel);
13680             if (chanpos < 0) {
13681                ast_log(LOG_WARNING, "Hangup ACK requested on unconfigured channel number %d/%d span %d\n",
13682                   PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13683             } else {
13684                chanpos = pri_fixup_principle(pri, chanpos, e->hangup.call);
13685                if (chanpos > -1) {
13686                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13687                   pri->pvts[chanpos]->call = NULL;
13688                   pri->pvts[chanpos]->resetting = 0;
13689                   if (pri->pvts[chanpos]->owner) {
13690                      ast_verb(3, "Channel %d/%d, span %d got hangup ACK\n", PRI_SPAN(e->hangup.channel), PRI_CHANNEL(e->hangup.channel), pri->span);
13691                   }
13692 
13693 #ifdef SUPPORT_USERUSER
13694                   if (!ast_strlen_zero(e->hangup.useruserinfo)) {
13695                      struct ast_channel *owner = pri->pvts[chanpos]->owner;
13696                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13697                      pbx_builtin_setvar_helper(owner, "USERUSERINFO", e->hangup.useruserinfo);
13698                      ast_mutex_lock(&pri->pvts[chanpos]->lock);
13699                   }
13700 #endif
13701 
13702                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13703                }
13704             }
13705             break;
13706          case PRI_EVENT_CONFIG_ERR:
13707             ast_log(LOG_WARNING, "PRI Error on span %d: %s\n", pri->span, e->err.err);
13708             break;
13709          case PRI_EVENT_RESTART_ACK:
13710             chanpos = pri_find_principle(pri, e->restartack.channel);
13711             if (chanpos < 0) {
13712                /* Sometime switches (e.g. I421 / British Telecom) don't give us the
13713                   channel number, so we have to figure it out...  This must be why
13714                   everybody resets exactly a channel at a time. */
13715                for (x = 0; x < pri->numchans; x++) {
13716                   if (pri->pvts[x] && pri->pvts[x]->resetting) {
13717                      chanpos = x;
13718                      ast_mutex_lock(&pri->pvts[chanpos]->lock);
13719                      ast_debug(1, "Assuming restart ack is really for channel %d/%d span %d\n", pri->pvts[chanpos]->logicalspan,
13720                         pri->pvts[chanpos]->prioffset, pri->span);
13721                      if (pri->pvts[chanpos]->realcall)
13722                         pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
13723                      else if (pri->pvts[chanpos]->owner) {
13724                         ast_log(LOG_WARNING, "Got restart ack on channel %d/%d with owner on span %d\n", pri->pvts[chanpos]->logicalspan,
13725                            pri->pvts[chanpos]->prioffset, pri->span);
13726                         pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13727                      }
13728                      pri->pvts[chanpos]->resetting = 0;
13729                      ast_verb(3, "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
13730                            pri->pvts[chanpos]->prioffset, pri->span);
13731                      ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13732                      if (pri->resetting)
13733                         pri_check_restart(pri);
13734                      break;
13735                   }
13736                }
13737                if (chanpos < 0) {
13738                   ast_log(LOG_WARNING, "Restart ACK requested on strange channel %d/%d span %d\n",
13739                      PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
13740                }
13741             } else {
13742                if (pri->pvts[chanpos]) {
13743                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13744                   if (pri->pvts[chanpos]->realcall)
13745                      pri_hangup_all(pri->pvts[chanpos]->realcall, pri);
13746                   else if (pri->pvts[chanpos]->owner) {
13747                      ast_log(LOG_WARNING, "Got restart ack on channel %d/%d span %d with owner\n",
13748                         PRI_SPAN(e->restartack.channel), PRI_CHANNEL(e->restartack.channel), pri->span);
13749                      pri->pvts[chanpos]->owner->_softhangup |= AST_SOFTHANGUP_DEV;
13750                   }
13751                   pri->pvts[chanpos]->resetting = 0;
13752                   pri->pvts[chanpos]->inservice = 1;
13753                   ast_verb(3, "B-channel %d/%d successfully restarted on span %d\n", pri->pvts[chanpos]->logicalspan,
13754                            pri->pvts[chanpos]->prioffset, pri->span);
13755                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13756                   if (pri->resetting)
13757                      pri_check_restart(pri);
13758                }
13759             }
13760             break;
13761          case PRI_EVENT_SETUP_ACK:
13762             chanpos = pri_find_principle(pri, e->setup_ack.channel);
13763             if (chanpos < 0) {
13764                ast_log(LOG_WARNING, "Received SETUP_ACKNOWLEDGE on unconfigured channel %d/%d span %d\n",
13765                   PRI_SPAN(e->setup_ack.channel), PRI_CHANNEL(e->setup_ack.channel), pri->span);
13766             } else {
13767                chanpos = pri_fixup_principle(pri, chanpos, e->setup_ack.call);
13768                if (chanpos > -1) {
13769                   ast_mutex_lock(&pri->pvts[chanpos]->lock);
13770                   pri->pvts[chanpos]->setup_ack = 1;
13771                   /* Send any queued digits */
13772                   for (x = 0;x < strlen(pri->pvts[chanpos]->dialdest); x++) {
13773                      ast_debug(1, "Sending pending digit '%c'\n", pri->pvts[chanpos]->dialdest[x]);
13774                      pri_information(pri->pri, pri->pvts[chanpos]->call,
13775                         pri->pvts[chanpos]->dialdest[x]);
13776                   }
13777                   ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13778                } else
13779                   ast_log(LOG_WARNING, "Unable to move channel %d!\n", e->setup_ack.channel);
13780             }
13781             break;
13782          case PRI_EVENT_NOTIFY:
13783             chanpos = pri_find_principle(pri, e->notify.channel);
13784             if (chanpos < 0) {
13785                ast_log(LOG_WARNING, "Received NOTIFY on unconfigured channel %d/%d span %d\n",
13786                   PRI_SPAN(e->notify.channel), PRI_CHANNEL(e->notify.channel), pri->span);
13787             } else if (!pri->discardremoteholdretrieval) {
13788                struct ast_frame f = { AST_FRAME_CONTROL, };
13789                ast_mutex_lock(&pri->pvts[chanpos]->lock);
13790                switch (e->notify.info) {
13791                case PRI_NOTIFY_REMOTE_HOLD:
13792                   f.subclass = AST_CONTROL_HOLD;
13793                   dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13794                   break;
13795                case PRI_NOTIFY_REMOTE_RETRIEVAL:
13796                   f.subclass = AST_CONTROL_UNHOLD;
13797                   dahdi_queue_frame(pri->pvts[chanpos], &f, pri);
13798                   break;
13799                }
13800                ast_mutex_unlock(&pri->pvts[chanpos]->lock);
13801             }
13802             break;
13803          default:
13804             ast_debug(1, "Event: %d\n", e->e);
13805          }
13806       }
13807       ast_mutex_unlock(&pri->lock);
13808    }
13809    /* Never reached */
13810    return NULL;
13811 }
13812 #endif   /* defined(HAVE_PRI) */
13813 
13814 #if defined(HAVE_PRI)
13815 static int start_pri(struct dahdi_pri *pri)
13816 {
13817    int res, x;
13818    struct dahdi_params p;
13819    struct dahdi_bufferinfo bi;
13820    struct dahdi_spaninfo si;
13821    int i;
13822 
13823    for (i = 0; i < NUM_DCHANS; i++) {
13824       if (!pri->dchannels[i])
13825          break;
13826       pri->fds[i] = open("/dev/dahdi/channel", O_RDWR);
13827       x = pri->dchannels[i];
13828       if ((pri->fds[i] < 0) || (ioctl(pri->fds[i],DAHDI_SPECIFY,&x) == -1)) {
13829          ast_log(LOG_ERROR, "Unable to open D-channel %d (%s)\n", x, strerror(errno));
13830          return -1;
13831       }
13832       memset(&p, 0, sizeof(p));
13833       res = ioctl(pri->fds[i], DAHDI_GET_PARAMS, &p);
13834       if (res) {
13835          dahdi_close_pri_fd(pri, i);
13836          ast_log(LOG_ERROR, "Unable to get parameters for D-channel %d (%s)\n", x, strerror(errno));
13837          return -1;
13838       }
13839       if ((p.sigtype != DAHDI_SIG_HDLCFCS) && (p.sigtype != DAHDI_SIG_HARDHDLC)) {
13840          dahdi_close_pri_fd(pri, i);
13841          ast_log(LOG_ERROR, "D-channel %d is not in HDLC/FCS mode.\n", x);
13842          return -1;
13843       }
13844       memset(&si, 0, sizeof(si));
13845       res = ioctl(pri->fds[i], DAHDI_SPANSTAT, &si);
13846       if (res) {
13847          dahdi_close_pri_fd(pri, i);
13848          ast_log(LOG_ERROR, "Unable to get span state for D-channel %d (%s)\n", x, strerror(errno));
13849       }
13850       if (!si.alarms)
13851          pri->dchanavail[i] |= DCHAN_NOTINALARM;
13852       else
13853          pri->dchanavail[i] &= ~DCHAN_NOTINALARM;
13854       memset(&bi, 0, sizeof(bi));
13855       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
13856       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
13857       bi.numbufs = 32;
13858       bi.bufsize = 1024;
13859       if (ioctl(pri->fds[i], DAHDI_SET_BUFINFO, &bi)) {
13860          ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n", x, strerror(errno));
13861          dahdi_close_pri_fd(pri, i);
13862          return -1;
13863       }
13864       switch (pri->sig) {
13865       case SIG_BRI:
13866          pri->dchans[i] = pri_new_bri(pri->fds[i], 1, pri->nodetype, pri->switchtype);
13867          break;
13868       case SIG_BRI_PTMP:
13869          pri->dchans[i] = pri_new_bri(pri->fds[i], 0, pri->nodetype, pri->switchtype);
13870          break;
13871       default:
13872          pri->dchans[i] = pri_new(pri->fds[i], pri->nodetype, pri->switchtype);
13873          break;
13874       }
13875       /* Force overlap dial if we're doing GR-303! */
13876       if (pri->switchtype == PRI_SWITCH_GR303_TMC)
13877          pri->overlapdial |= DAHDI_OVERLAPDIAL_BOTH;
13878       pri_set_overlapdial(pri->dchans[i],(pri->overlapdial & DAHDI_OVERLAPDIAL_OUTGOING)?1:0);
13879 #ifdef HAVE_PRI_PROG_W_CAUSE
13880       pri_set_chan_mapping_logical(pri->dchans[i], pri->qsigchannelmapping == DAHDI_CHAN_MAPPING_LOGICAL);
13881 #endif
13882 #ifdef HAVE_PRI_INBANDDISCONNECT
13883       pri_set_inbanddisconnect(pri->dchans[i], pri->inbanddisconnect);
13884 #endif
13885       /* Enslave to master if appropriate */
13886       if (i)
13887          pri_enslave(pri->dchans[0], pri->dchans[i]);
13888       if (!pri->dchans[i]) {
13889          dahdi_close_pri_fd(pri, i);
13890          ast_log(LOG_ERROR, "Unable to create PRI structure\n");
13891          return -1;
13892       }
13893       pri_set_debug(pri->dchans[i], DEFAULT_PRI_DEBUG);
13894       pri_set_nsf(pri->dchans[i], pri->nsf);
13895 #ifdef PRI_GETSET_TIMERS
13896       for (x = 0; x < PRI_MAX_TIMERS; x++) {
13897          if (pritimers[x] != 0)
13898             pri_set_timer(pri->dchans[i], x, pritimers[x]);
13899       }
13900 #endif
13901    }
13902    /* Assume primary is the one we use */
13903    pri->pri = pri->dchans[0];
13904    pri->resetpos = -1;
13905    if (ast_pthread_create_background(&pri->master, NULL, pri_dchannel, pri)) {
13906       for (i = 0; i < NUM_DCHANS; i++) {
13907          if (!pri->dchannels[i])
13908             break;
13909          dahdi_close_pri_fd(pri, i);
13910       }
13911       ast_log(LOG_ERROR, "Unable to spawn D-channel: %s\n", strerror(errno));
13912       return -1;
13913    }
13914    return 0;
13915 }
13916 #endif   /* defined(HAVE_PRI) */
13917 
13918 #if defined(HAVE_PRI)
13919 static char *complete_span_helper(const char *line, const char *word, int pos, int state, int rpos)
13920 {
13921    int which, span;
13922    char *ret = NULL;
13923 
13924    if (pos != rpos)
13925       return ret;
13926 
13927    for (which = span = 0; span < NUM_SPANS; span++) {
13928       if (pris[span].pri && ++which > state) {
13929          if (asprintf(&ret, "%d", span + 1) < 0) { /* user indexes start from 1 */
13930             ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
13931          }
13932          break;
13933       }
13934    }
13935    return ret;
13936 }
13937 #endif   /* defined(HAVE_PRI) */
13938 
13939 #if defined(HAVE_PRI)
13940 static char *complete_span_4(const char *line, const char *word, int pos, int state)
13941 {
13942    return complete_span_helper(line,word,pos,state,3);
13943 }
13944 #endif   /* defined(HAVE_PRI) */
13945 
13946 #if defined(HAVE_PRI)
13947 static char *handle_pri_set_debug_file(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13948 {
13949    int myfd;
13950    switch (cmd) {
13951    case CLI_INIT:
13952       e->command = "pri set debug file";
13953       e->usage = "Usage: pri set debug file [output-file]\n"
13954          "       Sends PRI debug output to the specified output file\n";
13955       return NULL;
13956    case CLI_GENERATE:
13957       return NULL;
13958    }
13959    if (a->argc < 5)
13960       return CLI_SHOWUSAGE;
13961 
13962    if (ast_strlen_zero(a->argv[4]))
13963       return CLI_SHOWUSAGE;
13964 
13965    myfd = open(a->argv[4], O_CREAT|O_WRONLY, AST_FILE_MODE);
13966    if (myfd < 0) {
13967       ast_cli(a->fd, "Unable to open '%s' for writing\n", a->argv[4]);
13968       return CLI_SUCCESS;
13969    }
13970 
13971    ast_mutex_lock(&pridebugfdlock);
13972 
13973    if (pridebugfd >= 0)
13974       close(pridebugfd);
13975 
13976    pridebugfd = myfd;
13977    ast_copy_string(pridebugfilename,a->argv[4],sizeof(pridebugfilename));
13978    ast_mutex_unlock(&pridebugfdlock);
13979    ast_cli(a->fd, "PRI debug output will be sent to '%s'\n", a->argv[4]);
13980    return CLI_SUCCESS;
13981 }
13982 #endif   /* defined(HAVE_PRI) */
13983 
13984 #if defined(HAVE_PRI)
13985 static char *handle_pri_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13986 {
13987    int span;
13988    int x;
13989    int level = 0;
13990    switch (cmd) {
13991    case CLI_INIT:
13992       e->command = "pri set debug {on|off|0|1|2} span";
13993       e->usage =
13994          "Usage: pri set debug {<level>|on|off} span <span>\n"
13995          "       Enables debugging on a given PRI span\n";
13996       return NULL;
13997    case CLI_GENERATE:
13998       return complete_span_4(a->line, a->word, a->pos, a->n);
13999    }
14000    if (a->argc < 6) {
14001       return CLI_SHOWUSAGE;
14002    }
14003 
14004    if (!strcasecmp(a->argv[3], "on")) {
14005       level = 1;
14006    } else if (!strcasecmp(a->argv[3], "off")) {
14007       level = 0;
14008    } else {
14009       level = atoi(a->argv[3]);
14010    }
14011    span = atoi(a->argv[5]);
14012    if ((span < 1) || (span > NUM_SPANS)) {
14013       ast_cli(a->fd, "Invalid span %s.  Should be a number %d to %d\n", a->argv[5], 1, NUM_SPANS);
14014       return CLI_SUCCESS;
14015    }
14016    if (!pris[span-1].pri) {
14017       ast_cli(a->fd, "No PRI running on span %d\n", span);
14018       return CLI_SUCCESS;
14019    }
14020    for (x = 0; x < NUM_DCHANS; x++) {
14021       if (pris[span-1].dchans[x]) {
14022          if (level == 1) {
14023             pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
14024                PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
14025                PRI_DEBUG_Q921_STATE);
14026             ast_cli(a->fd, "Enabled debugging on span %d\n", span);
14027          } else if (level == 0) {
14028             pri_set_debug(pris[span-1].dchans[x], 0);
14029             //close the file if it's set
14030             ast_mutex_lock(&pridebugfdlock);
14031             close(pridebugfd);
14032             pridebugfd = -1;
14033             ast_cli(a->fd, "PRI debug output to file disabled\n");
14034             ast_mutex_unlock(&pridebugfdlock);
14035          } else {
14036             pri_set_debug(pris[span-1].dchans[x], PRI_DEBUG_APDU |
14037                PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q931_STATE |
14038                PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_STATE);
14039             ast_cli(a->fd, "Enabled debugging on span %d\n", span);
14040          }
14041       }
14042    }
14043    return CLI_SUCCESS;
14044 }
14045 #endif   /* defined(HAVE_PRI) */
14046 
14047 #if defined(HAVE_PRI)
14048 static void build_status(char *s, size_t len, int status, int active)
14049 {
14050    if (!s || len < 1) {
14051       return;
14052    }
14053    s[0] = '\0';
14054    if (status & DCHAN_PROVISIONED)
14055       strncat(s, "Provisioned, ", len - strlen(s) - 1);
14056    if (!(status & DCHAN_NOTINALARM))
14057       strncat(s, "In Alarm, ", len - strlen(s) - 1);
14058    if (status & DCHAN_UP)
14059       strncat(s, "Up", len - strlen(s) - 1);
14060    else
14061       strncat(s, "Down", len - strlen(s) - 1);
14062    if (active)
14063       strncat(s, ", Active", len - strlen(s) - 1);
14064    else
14065       strncat(s, ", Standby", len - strlen(s) - 1);
14066    s[len - 1] = '\0';
14067 }
14068 #endif   /* defined(HAVE_PRI) */
14069 
14070 #if defined(HAVE_PRI)
14071 static char *handle_pri_show_spans(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14072 {
14073    int span;
14074    int x;
14075    char status[256];
14076 
14077    switch (cmd) {
14078    case CLI_INIT:
14079       e->command = "pri show spans";
14080       e->usage =
14081          "Usage: pri show spans\n"
14082          "       Displays PRI Information\n";
14083       return NULL;
14084    case CLI_GENERATE:
14085       return NULL;
14086    }
14087 
14088    if (a->argc != 3)
14089       return CLI_SHOWUSAGE;
14090 
14091    for (span = 0; span < NUM_SPANS; span++) {
14092       if (pris[span].pri) {
14093          for (x = 0; x < NUM_DCHANS; x++) {
14094             if (pris[span].dchannels[x]) {
14095                build_status(status, sizeof(status), pris[span].dchanavail[x], pris[span].dchans[x] == pris[span].pri);
14096                ast_cli(a->fd, "PRI span %d/%d: %s\n", span + 1, x, status);
14097             }
14098          }
14099       }
14100    }
14101    return CLI_SUCCESS;
14102 }
14103 #endif   /* defined(HAVE_PRI) */
14104 
14105 #if defined(HAVE_PRI)
14106 static char *handle_pri_show_span(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14107 {
14108    int span;
14109    int x;
14110    char status[256];
14111    switch (cmd) {
14112    case CLI_INIT:
14113       e->command = "pri show span";
14114       e->usage =
14115          "Usage: pri show span <span>\n"
14116          "       Displays PRI Information on a given PRI span\n";
14117       return NULL;
14118    case CLI_GENERATE:
14119       return complete_span_4(a->line, a->word, a->pos, a->n);
14120    }
14121 
14122    if (a->argc < 4)
14123       return CLI_SHOWUSAGE;
14124    span = atoi(a->argv[3]);
14125    if ((span < 1) || (span > NUM_SPANS)) {
14126       ast_cli(a->fd, "Invalid span '%s'.  Should be a number from %d to %d\n", a->argv[3], 1, NUM_SPANS);
14127       return CLI_SUCCESS;
14128    }
14129    if (!pris[span-1].pri) {
14130       ast_cli(a->fd, "No PRI running on span %d\n", span);
14131       return CLI_SUCCESS;
14132    }
14133    for (x = 0; x < NUM_DCHANS; x++) {
14134       if (pris[span-1].dchannels[x]) {
14135 #ifdef PRI_DUMP_INFO_STR
14136          char *info_str = NULL;
14137 #endif
14138          ast_cli(a->fd, "%s D-channel: %d\n", pri_order(x), pris[span-1].dchannels[x]);
14139          build_status(status, sizeof(status), pris[span-1].dchanavail[x], pris[span-1].dchans[x] == pris[span-1].pri);
14140          ast_cli(a->fd, "Status: %s\n", status);
14141 #ifdef PRI_DUMP_INFO_STR
14142          info_str = pri_dump_info_str(pris[span-1].pri);
14143          if (info_str) {
14144             ast_cli(a->fd, "%s", info_str);
14145             ast_free(info_str);
14146          }
14147 #else
14148          pri_dump_info(pris[span-1].pri);
14149 #endif
14150          ast_cli(a->fd, "Overlap Recv: %s\n\n", (pris[span-1].overlapdial & DAHDI_OVERLAPDIAL_INCOMING)?"Yes":"No");
14151       }
14152    }
14153    return CLI_SUCCESS;
14154 }
14155 #endif   /* defined(HAVE_PRI) */
14156 
14157 #if defined(HAVE_PRI)
14158 static char *handle_pri_show_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14159 {
14160    int x;
14161    int span;
14162    int count=0;
14163    int debug=0;
14164 
14165    switch (cmd) {
14166    case CLI_INIT:
14167       e->command = "pri show debug";
14168       e->usage =
14169          "Usage: pri show debug\n"
14170          "  Show the debug state of pri spans\n";
14171       return NULL;
14172    case CLI_GENERATE:
14173       return NULL;
14174    }
14175 
14176    for (span = 0; span < NUM_SPANS; span++) {
14177       if (pris[span].pri) {
14178          for (x = 0; x < NUM_DCHANS; x++) {
14179             debug = 0;
14180             if (pris[span].dchans[x]) {
14181                debug = pri_get_debug(pris[span].dchans[x]);
14182                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" );
14183                count++;
14184             }
14185          }
14186       }
14187 
14188    }
14189    ast_mutex_lock(&pridebugfdlock);
14190    if (pridebugfd >= 0)
14191       ast_cli(a->fd, "Logging PRI debug to file %s\n", pridebugfilename);
14192    ast_mutex_unlock(&pridebugfdlock);
14193 
14194    if (!count)
14195       ast_cli(a->fd, "No debug set or no PRI running\n");
14196    return CLI_SUCCESS;
14197 }
14198 #endif   /* defined(HAVE_PRI) */
14199 
14200 #if defined(HAVE_PRI)
14201 static char *handle_pri_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14202 {
14203    switch (cmd) {
14204    case CLI_INIT:
14205       e->command = "pri show version";
14206       e->usage =
14207          "Usage: pri show version\n"
14208          "Show libpri version information\n";
14209       return NULL;
14210    case CLI_GENERATE:
14211       return NULL;
14212    }
14213 
14214    ast_cli(a->fd, "libpri version: %s\n", pri_get_version());
14215 
14216    return CLI_SUCCESS;
14217 }
14218 #endif   /* defined(HAVE_PRI) */
14219 
14220 #if defined(HAVE_PRI)
14221 static struct ast_cli_entry dahdi_pri_cli[] = {
14222    AST_CLI_DEFINE(handle_pri_debug, "Enables PRI debugging on a span"),
14223    AST_CLI_DEFINE(handle_pri_show_spans, "Displays PRI Information"),
14224    AST_CLI_DEFINE(handle_pri_show_span, "Displays PRI Information"),
14225    AST_CLI_DEFINE(handle_pri_show_debug, "Displays current PRI debug settings"),
14226    AST_CLI_DEFINE(handle_pri_set_debug_file, "Sends PRI debug output to the specified file"),
14227    AST_CLI_DEFINE(handle_pri_version, "Displays libpri version"),
14228 };
14229 #endif   /* defined(HAVE_PRI) */
14230 
14231 #ifdef HAVE_OPENR2
14232 
14233 static char *handle_mfcr2_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14234 {
14235    switch (cmd) {
14236    case CLI_INIT:
14237       e->command = "mfcr2 show version";
14238       e->usage =
14239          "Usage: mfcr2 show version\n"
14240          "       Shows the version of the OpenR2 library being used.\n";
14241       return NULL;
14242    case CLI_GENERATE:
14243       return NULL;
14244    }
14245    ast_cli(a->fd, "OpenR2 version: %s, revision: %s\n", openr2_get_version(), openr2_get_revision());
14246    return CLI_SUCCESS;
14247 }
14248 
14249 static char *handle_mfcr2_show_variants(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14250 {
14251 #define FORMAT "%4s %40s\n"
14252    int i = 0;
14253    int numvariants = 0;
14254    const openr2_variant_entry_t *variants;
14255    switch (cmd) {
14256    case CLI_INIT:
14257       e->command = "mfcr2 show variants";
14258       e->usage =
14259          "Usage: mfcr2 show variants\n"
14260          "       Shows the list of MFC/R2 variants supported.\n";
14261       return NULL;
14262    case CLI_GENERATE:
14263       return NULL;
14264    }
14265    if (!(variants = openr2_proto_get_variant_list(&numvariants))) {
14266       ast_cli(a->fd, "Failed to get list of variants.\n");
14267       return CLI_FAILURE;
14268    }
14269    ast_cli(a->fd, FORMAT, "Variant Code", "Country");
14270    for (i = 0; i < numvariants; i++) {
14271       ast_cli(a->fd, FORMAT, variants[i].name, variants[i].country);
14272    }
14273    return CLI_SUCCESS;
14274 #undef FORMAT
14275 }
14276 
14277 static char *handle_mfcr2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14278 {
14279 #define FORMAT "%4s %-7.7s %-7.7s %-8.8s %-9.9s %-16.16s %-8.8s %-8.8s\n"
14280    int filtertype = 0;
14281    int targetnum = 0;
14282    char channo[5];
14283    char anino[5];
14284    char dnisno[5];
14285    struct dahdi_pvt *p;
14286    openr2_context_t *r2context;
14287    openr2_variant_t r2variant;
14288    switch (cmd) {
14289    case CLI_INIT:
14290       e->command = "mfcr2 show channels [group|context]";
14291       e->usage =
14292          "Usage: mfcr2 show channels [group <group> | context <context>]\n"
14293          "       Shows the DAHDI channels configured with MFC/R2 signaling.\n";
14294       return NULL;
14295    case CLI_GENERATE:
14296       return NULL;
14297    }
14298    if (!((a->argc == 3) || (a->argc == 5))) {
14299       return CLI_SHOWUSAGE;
14300    }
14301    if (a->argc == 5) {
14302       if (!strcasecmp(a->argv[3], "group")) {
14303          targetnum = atoi(a->argv[4]);
14304          if ((targetnum < 0) || (targetnum > 63))
14305             return CLI_SHOWUSAGE;
14306          targetnum = 1 << targetnum;
14307          filtertype = 1;
14308       } else if (!strcasecmp(a->argv[3], "context")) {
14309          filtertype = 2;
14310       } else {
14311          return CLI_SHOWUSAGE;
14312       }
14313    }
14314    ast_cli(a->fd, FORMAT, "Chan", "Variant", "Max ANI", "Max DNIS", "ANI First", "Immediate Accept", "Tx CAS", "Rx CAS");
14315    ast_mutex_lock(&iflock);
14316    p = iflist;
14317    for (p = iflist; p; p = p->next) {
14318       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14319          continue;
14320       }
14321       if (filtertype) {
14322          switch(filtertype) {
14323          case 1: /* mfcr2 show channels group <group> */
14324             if (p->group != targetnum) {
14325                continue;
14326             }
14327             break;
14328          case 2: /* mfcr2 show channels context <context> */
14329             if (strcasecmp(p->context, a->argv[4])) {
14330                continue;
14331             }
14332             break;
14333          default:
14334             ;
14335          }
14336       }
14337       r2context = openr2_chan_get_context(p->r2chan);
14338       r2variant = openr2_context_get_variant(r2context);
14339       snprintf(channo, sizeof(channo), "%d", p->channel);
14340       snprintf(anino, sizeof(anino), "%d", openr2_context_get_max_ani(r2context));
14341       snprintf(dnisno, sizeof(dnisno), "%d", openr2_context_get_max_dnis(r2context));
14342       ast_cli(a->fd, FORMAT, channo, openr2_proto_get_variant_string(r2variant),
14343             anino, dnisno, openr2_context_get_ani_first(r2context) ? "Yes" : "No",
14344             openr2_context_get_immediate_accept(r2context) ? "Yes" : "No",
14345             openr2_chan_get_tx_cas_string(p->r2chan), openr2_chan_get_rx_cas_string(p->r2chan));
14346    }
14347    ast_mutex_unlock(&iflock);
14348    return CLI_SUCCESS;
14349 #undef FORMAT
14350 }
14351 
14352 static char *handle_mfcr2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14353 {
14354    struct dahdi_pvt *p = NULL;
14355    int channo = 0;
14356    char *toklevel = NULL;
14357    char *saveptr = NULL;
14358    char *logval = NULL;
14359    openr2_log_level_t loglevel = OR2_LOG_NOTHING;
14360    openr2_log_level_t tmplevel = OR2_LOG_NOTHING;
14361    switch (cmd) {
14362    case CLI_INIT:
14363       e->command = "mfcr2 set debug";
14364       e->usage =
14365          "Usage: mfcr2 set debug <loglevel> <channel>\n"
14366          "       Set a new logging level for the specified channel.\n"
14367          "       If no channel is specified the logging level will be applied to all channels.\n";
14368       return NULL;
14369    case CLI_GENERATE:
14370       return NULL;
14371    }
14372    if (a->argc < 4) {
14373       return CLI_SHOWUSAGE;
14374    }
14375    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14376    logval = ast_strdupa(a->argv[3]);
14377    toklevel = strtok_r(logval, ",", &saveptr);
14378    if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14379       ast_cli(a->fd, "Invalid MFC/R2 logging level '%s'.\n", a->argv[3]);
14380       return CLI_FAILURE;
14381    } else if (OR2_LOG_NOTHING == tmplevel) {
14382       loglevel = tmplevel;
14383    } else {
14384       loglevel |= tmplevel;
14385       while ((toklevel = strtok_r(NULL, ",", &saveptr))) {
14386          if (-1 == (tmplevel = openr2_log_get_level(toklevel))) {
14387             ast_cli(a->fd, "Ignoring invalid logging level: '%s'.\n", toklevel);
14388             continue;
14389          }
14390          loglevel |= tmplevel;
14391       }
14392    }
14393    ast_mutex_lock(&iflock);
14394    for (p = iflist; p; p = p->next) {
14395       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14396          continue;
14397       }
14398       if ((channo != -1) && (p->channel != channo )) {
14399          continue;
14400       }
14401       openr2_chan_set_log_level(p->r2chan, loglevel);
14402       if (channo != -1) {
14403          ast_cli(a->fd, "MFC/R2 debugging set to '%s' for channel %d.\n", a->argv[3], p->channel);
14404          break;
14405       }
14406    }
14407    if ((channo != -1) && !p) {
14408       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14409    }
14410    if (channo == -1) {
14411       ast_cli(a->fd, "MFC/R2 debugging set to '%s' for all channels.\n", a->argv[3]);
14412    }
14413    ast_mutex_unlock(&iflock);
14414    return CLI_SUCCESS;
14415 }
14416 
14417 static char *handle_mfcr2_call_files(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14418 {
14419    struct dahdi_pvt *p = NULL;
14420    int channo = 0;
14421    switch (cmd) {
14422    case CLI_INIT:
14423       e->command = "mfcr2 call files [on|off]";
14424       e->usage =
14425          "Usage: mfcr2 call files [on|off] <channel>\n"
14426          "       Enable call files creation on the specified channel.\n"
14427          "       If no channel is specified call files creation policy will be applied to all channels.\n";
14428       return NULL;
14429    case CLI_GENERATE:
14430       return NULL;
14431    }
14432    if (a->argc < 4) {
14433       return CLI_SHOWUSAGE;
14434    }
14435    channo = (a->argc == 5) ? atoi(a->argv[4]) : -1;
14436    ast_mutex_lock(&iflock);
14437    for (p = iflist; p; p = p->next) {
14438       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14439          continue;
14440       }
14441       if ((channo != -1) && (p->channel != channo )) {
14442          continue;
14443       }
14444       if (ast_true(a->argv[3])) {
14445          openr2_chan_enable_call_files(p->r2chan);
14446       } else {
14447          openr2_chan_disable_call_files(p->r2chan);
14448       }
14449       if (channo != -1) {
14450          if (ast_true(a->argv[3])) {
14451             ast_cli(a->fd, "MFC/R2 call files enabled for channel %d.\n", p->channel);
14452          } else {
14453             ast_cli(a->fd, "MFC/R2 call files disabled for channel %d.\n", p->channel);
14454          }
14455          break;
14456       }
14457    }
14458    if ((channo != -1) && !p) {
14459       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14460    }
14461    if (channo == -1) {
14462       if (ast_true(a->argv[3])) {
14463          ast_cli(a->fd, "MFC/R2 Call files enabled for all channels.\n");
14464       } else {
14465          ast_cli(a->fd, "MFC/R2 Call files disabled for all channels.\n");
14466       }
14467    }
14468    ast_mutex_unlock(&iflock);
14469    return CLI_SUCCESS;
14470 }
14471 
14472 static char *handle_mfcr2_set_idle(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14473 {
14474    struct dahdi_pvt *p = NULL;
14475    int channo = 0;
14476    switch (cmd) {
14477    case CLI_INIT:
14478       e->command = "mfcr2 set idle";
14479       e->usage =
14480          "Usage: mfcr2 set idle <channel>\n"
14481          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14482          "       Force the given channel into IDLE state.\n"
14483          "       If no channel is specified, all channels will be set to IDLE.\n";
14484       return NULL;
14485    case CLI_GENERATE:
14486       return NULL;
14487    }
14488    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14489    ast_mutex_lock(&iflock);
14490    for (p = iflist; p; p = p->next) {
14491       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14492          continue;
14493       }
14494       if ((channo != -1) && (p->channel != channo )) {
14495          continue;
14496       }
14497       openr2_chan_set_idle(p->r2chan);
14498       ast_mutex_lock(&p->lock);
14499       p->locallyblocked = 0;
14500       p->mfcr2call = 0;
14501       ast_mutex_unlock(&p->lock);
14502       if (channo != -1) {
14503          break;
14504       }
14505    }
14506    if ((channo != -1) && !p) {
14507       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14508    }
14509    ast_mutex_unlock(&iflock);
14510    return CLI_SUCCESS;
14511 }
14512 
14513 static char *handle_mfcr2_set_blocked(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14514 {
14515    struct dahdi_pvt *p = NULL;
14516    int channo = 0;
14517    switch (cmd) {
14518    case CLI_INIT:
14519       e->command = "mfcr2 set blocked";
14520       e->usage =
14521          "Usage: mfcr2 set blocked <channel>\n"
14522          "       DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.\n"
14523          "       Force the given channel into BLOCKED state.\n"
14524          "       If no channel is specified, all channels will be set to BLOCKED.\n";
14525       return NULL;
14526    case CLI_GENERATE:
14527       return NULL;
14528    }
14529    channo = (a->argc == 4) ? atoi(a->argv[3]) : -1;
14530    ast_mutex_lock(&iflock);
14531    for (p = iflist; p; p = p->next) {
14532       if (!(p->sig & SIG_MFCR2) || !p->r2chan) {
14533          continue;
14534       }
14535       if ((channo != -1) && (p->channel != channo )) {
14536          continue;
14537       }
14538       openr2_chan_set_blocked(p->r2chan);
14539       ast_mutex_lock(&p->lock);
14540       p->locallyblocked = 1;
14541       ast_mutex_unlock(&p->lock);
14542       if (channo != -1) {
14543          break;
14544       }
14545    }
14546    if ((channo != -1) && !p) {
14547       ast_cli(a->fd, "MFC/R2 channel %d not found.\n", channo);
14548    }
14549    ast_mutex_unlock(&iflock);
14550    return CLI_SUCCESS;
14551 }
14552 
14553 static struct ast_cli_entry dahdi_mfcr2_cli[] = {
14554    AST_CLI_DEFINE(handle_mfcr2_version, "Show OpenR2 library version"),
14555    AST_CLI_DEFINE(handle_mfcr2_show_variants, "Show supported MFC/R2 variants"),
14556    AST_CLI_DEFINE(handle_mfcr2_show_channels, "Show MFC/R2 channels"),
14557    AST_CLI_DEFINE(handle_mfcr2_set_debug, "Set MFC/R2 channel logging level"),
14558    AST_CLI_DEFINE(handle_mfcr2_call_files, "Enable/Disable MFC/R2 call files"),
14559    AST_CLI_DEFINE(handle_mfcr2_set_idle, "Reset MFC/R2 channel forcing it to IDLE"),
14560    AST_CLI_DEFINE(handle_mfcr2_set_blocked, "Reset MFC/R2 channel forcing it to BLOCKED"),
14561 };
14562 
14563 #endif /* HAVE_OPENR2 */
14564 
14565 static char *dahdi_destroy_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14566 {
14567    int channel;
14568    int ret;
14569    switch (cmd) {
14570    case CLI_INIT:
14571       e->command = "dahdi destroy channel";
14572       e->usage =
14573          "Usage: dahdi destroy channel <chan num>\n"
14574          "  DON'T USE THIS UNLESS YOU KNOW WHAT YOU ARE DOING.  Immediately removes a given channel, whether it is in use or not\n";
14575       return NULL;
14576    case CLI_GENERATE:
14577       return NULL;
14578    }
14579    if (a->argc != 4)
14580       return CLI_SHOWUSAGE;
14581 
14582    channel = atoi(a->argv[3]);
14583    ret = dahdi_destroy_channel_bynum(channel);
14584    return ( RESULT_SUCCESS == ret ) ? CLI_SUCCESS : CLI_FAILURE;
14585 }
14586 
14587 static void dahdi_softhangup_all(void)
14588 {
14589    struct dahdi_pvt *p;
14590 retry:
14591    ast_mutex_lock(&iflock);
14592    for (p = iflist; p; p = p->next) {
14593       ast_mutex_lock(&p->lock);
14594       if (p->owner && !p->restartpending) {
14595          if (ast_channel_trylock(p->owner)) {
14596             if (option_debug > 2)
14597                ast_verbose("Avoiding deadlock\n");
14598             /* Avoid deadlock since you're not supposed to lock iflock or pvt before a channel */
14599             ast_mutex_unlock(&p->lock);
14600             ast_mutex_unlock(&iflock);
14601             goto retry;
14602          }
14603          if (option_debug > 2)
14604             ast_verbose("Softhanging up on %s\n", p->owner->name);
14605          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_EXPLICIT);
14606          p->restartpending = 1;
14607          num_restart_pending++;
14608          ast_channel_unlock(p->owner);
14609       }
14610       ast_mutex_unlock(&p->lock);
14611    }
14612    ast_mutex_unlock(&iflock);
14613 }
14614 
14615 static int setup_dahdi(int reload);
14616 static int dahdi_restart(void)
14617 {
14618 #if defined(HAVE_PRI) || defined(HAVE_SS7)
14619    int i, j;
14620 #endif
14621    int cancel_code;
14622    struct dahdi_pvt *p;
14623 
14624    ast_mutex_lock(&restart_lock);
14625    ast_verb(1, "Destroying channels and reloading DAHDI configuration.\n");
14626    dahdi_softhangup_all();
14627    ast_verb(4, "Initial softhangup of all DAHDI channels complete.\n");
14628 #ifdef HAVE_OPENR2
14629    dahdi_r2_destroy_links();
14630 #endif
14631 
14632 #if defined(HAVE_PRI)
14633    for (i = 0; i < NUM_SPANS; i++) {
14634       if (pris[i].master && (pris[i].master != AST_PTHREADT_NULL)) {
14635          cancel_code = pthread_cancel(pris[i].master);
14636          pthread_kill(pris[i].master, SIGURG);
14637          ast_debug(4, "Waiting to join thread of span %d with pid=%p, cancel_code=%d\n", i, (void *) pris[i].master, cancel_code);
14638          pthread_join(pris[i].master, NULL);
14639          ast_debug(4, "Joined thread of span %d\n", i);
14640       }
14641    }
14642 #endif
14643 
14644 #if defined(HAVE_SS7)
14645    for (i = 0; i < NUM_SPANS; i++) {
14646       if (linksets[i].master && (linksets[i].master != AST_PTHREADT_NULL)) {
14647          cancel_code = pthread_cancel(linksets[i].master);
14648          pthread_kill(linksets[i].master, SIGURG);
14649          ast_debug(4, "Waiting to join thread of span %d with pid=%p, cancel_code=%d\n", i, (void *) linksets[i].master, cancel_code);
14650          pthread_join(linksets[i].master, NULL);
14651          ast_debug(4, "Joined thread of span %d\n", i);
14652       }
14653    }
14654 #endif
14655 
14656    ast_mutex_lock(&monlock);
14657    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
14658       cancel_code = pthread_cancel(monitor_thread);
14659       pthread_kill(monitor_thread, SIGURG);
14660       ast_debug(4, "Waiting to join monitor thread with pid=%p, cancel_code=%d\n", (void *) monitor_thread, cancel_code);
14661       pthread_join(monitor_thread, NULL);
14662       ast_debug(4, "Joined monitor thread\n");
14663    }
14664    monitor_thread = AST_PTHREADT_NULL; /* prepare to restart thread in setup_dahdi once channels are reconfigured */
14665 
14666    ast_mutex_lock(&ss_thread_lock);
14667    while (ss_thread_count > 0) { /* let ss_threads finish and run dahdi_hangup before dahvi_pvts are destroyed */
14668       int x = DAHDI_FLASH;
14669       ast_debug(3, "Waiting on %d ss_thread(s) to finish\n", ss_thread_count);
14670 
14671       for (p = iflist; p; p = p->next) {
14672          if (p->owner)
14673             ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x); /* important to create an event for dahdi_wait_event to register so that all ss_threads terminate */
14674          }
14675          ast_cond_wait(&ss_thread_complete, &ss_thread_lock);
14676       }
14677 
14678    /* ensure any created channels before monitor threads were stopped are hungup */
14679    dahdi_softhangup_all();
14680    ast_verb(4, "Final softhangup of all DAHDI channels complete.\n");
14681    destroy_all_channels();
14682    ast_debug(1, "Channels destroyed. Now re-reading config. %d active channels remaining.\n", ast_active_channels());
14683 
14684    ast_mutex_unlock(&monlock);
14685 
14686 #ifdef HAVE_PRI
14687    for (i = 0; i < NUM_SPANS; i++) {
14688       for (j = 0; j < NUM_DCHANS; j++)
14689          dahdi_close_pri_fd(&(pris[i]), j);
14690    }
14691 
14692    memset(pris, 0, sizeof(pris));
14693    for (i = 0; i < NUM_SPANS; i++) {
14694       ast_mutex_init(&pris[i].lock);
14695       pris[i].offset = -1;
14696       pris[i].master = AST_PTHREADT_NULL;
14697       for (j = 0; j < NUM_DCHANS; j++)
14698          pris[i].fds[j] = -1;
14699       }
14700    pri_set_error(dahdi_pri_error);
14701    pri_set_message(dahdi_pri_message);
14702 #endif
14703 #ifdef HAVE_SS7
14704    for (i = 0; i < NUM_SPANS; i++) {
14705       for (j = 0; j < NUM_DCHANS; j++)
14706          dahdi_close_ss7_fd(&(linksets[i]), j);
14707    }
14708 
14709    memset(linksets, 0, sizeof(linksets));
14710    for (i = 0; i < NUM_SPANS; i++) {
14711       ast_mutex_init(&linksets[i].lock);
14712       linksets[i].master = AST_PTHREADT_NULL;
14713       for (j = 0; j < NUM_DCHANS; j++)
14714          linksets[i].fds[j] = -1;
14715    }
14716    ss7_set_error(dahdi_ss7_error);
14717    ss7_set_message(dahdi_ss7_message);
14718 #endif
14719 
14720    if (setup_dahdi(2) != 0) {
14721       ast_log(LOG_WARNING, "Reload channels from dahdi config failed!\n");
14722       ast_mutex_unlock(&ss_thread_lock);
14723       return 1;
14724    }
14725    ast_mutex_unlock(&ss_thread_lock);
14726    ast_mutex_unlock(&restart_lock);
14727    return 0;
14728 }
14729 
14730 static char *dahdi_restart_cmd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14731 {
14732    switch (cmd) {
14733    case CLI_INIT:
14734       e->command = "dahdi restart";
14735       e->usage =
14736          "Usage: dahdi restart\n"
14737          "  Restarts the DAHDI channels: destroys them all and then\n"
14738          "  re-reads them from chan_dahdi.conf.\n"
14739          "  Note that this will STOP any running CALL on DAHDI channels.\n"
14740          "";
14741       return NULL;
14742    case CLI_GENERATE:
14743       return NULL;
14744    }
14745    if (a->argc != 2)
14746       return CLI_SHOWUSAGE;
14747 
14748    if (dahdi_restart() != 0)
14749       return CLI_FAILURE;
14750    return CLI_SUCCESS;
14751 }
14752 
14753 static int action_dahdirestart(struct mansession *s, const struct message *m)
14754 {
14755    if (dahdi_restart() != 0) {
14756       astman_send_error(s, m, "Failed rereading DAHDI configuration");
14757       return 1;
14758    }
14759    astman_send_ack(s, m, "DAHDIRestart: Success");
14760    return 0;
14761 }
14762 
14763 static char *dahdi_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14764 {
14765 #define FORMAT "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
14766 #define FORMAT2 "%7s %-10.10s %-15.15s %-10.10s %-20.20s %-10.10s %-10.10s\n"
14767    unsigned int targetnum = 0;
14768    int filtertype = 0;
14769    struct dahdi_pvt *tmp = NULL;
14770    char tmps[20] = "";
14771    char statestr[20] = "";
14772    char blockstr[20] = "";
14773    ast_mutex_t *lock;
14774    struct dahdi_pvt *start;
14775 #ifdef HAVE_PRI
14776    int trunkgroup;
14777    struct dahdi_pri *pri = NULL;
14778    int x;
14779 #endif
14780    switch (cmd) {
14781    case CLI_INIT:
14782       e->command = "dahdi show channels [trunkgroup|group|context]";
14783       e->usage =
14784          "Usage: dahdi show channels [ trunkgroup <trunkgroup> | group <group> | context <context> ]\n"
14785          "  Shows a list of available channels with optional filtering\n"
14786          "  <group> must be a number between 0 and 63\n";
14787       return NULL;
14788    case CLI_GENERATE:
14789       return NULL;
14790    }
14791 
14792    lock = &iflock;
14793    start = iflist;
14794 
14795    /* syntax: dahdi show channels [ group <group> | context <context> | trunkgroup <trunkgroup> ] */
14796 
14797    if (!((a->argc == 3) || (a->argc == 5)))
14798       return CLI_SHOWUSAGE;
14799 
14800    if (a->argc == 5) {
14801 #ifdef HAVE_PRI
14802       if (!strcasecmp(a->argv[3], "trunkgroup")) {
14803          /* this option requires no special handling, so leave filtertype to zero */
14804          if ((trunkgroup = atoi(a->argv[4])) < 1)
14805             return CLI_SHOWUSAGE;
14806          for (x = 0; x < NUM_SPANS; x++) {
14807             if (pris[x].trunkgroup == trunkgroup) {
14808                pri = pris + x;
14809                break;
14810             }
14811          }
14812          if (pri) {
14813             start = pri->crvs;
14814             lock = &pri->lock;
14815          } else {
14816             ast_cli(a->fd, "No such trunk group %d\n", trunkgroup);
14817             return CLI_FAILURE;
14818          }
14819       } else
14820 #endif
14821       if (!strcasecmp(a->argv[3], "group")) {
14822          targetnum = atoi(a->argv[4]);
14823          if ((targetnum < 0) || (targetnum > 63))
14824             return CLI_SHOWUSAGE;
14825          targetnum = 1 << targetnum;
14826          filtertype = 1;
14827       } else if (!strcasecmp(a->argv[3], "context")) {
14828          filtertype = 2;
14829       }
14830    }
14831 
14832    ast_mutex_lock(lock);
14833 #ifdef HAVE_PRI
14834    ast_cli(a->fd, FORMAT2, pri ? "CRV" : "Chan", "Extension", "Context", "Language", "MOH Interpret", "Blocked", "State");
14835 #else
14836    ast_cli(a->fd, FORMAT2, "Chan", "Extension", "Context", "Language", "MOH Interpret", "Blocked", "State");
14837 #endif
14838 
14839    tmp = start;
14840    while (tmp) {
14841       if (filtertype) {
14842          switch(filtertype) {
14843          case 1: /* dahdi show channels group <group> */
14844             if (!(tmp->group & targetnum)) {
14845                tmp = tmp->next;
14846                continue;
14847             }
14848             break;
14849          case 2: /* dahdi show channels context <context> */
14850             if (strcasecmp(tmp->context, a->argv[4])) {
14851                tmp = tmp->next;
14852                continue;
14853             }
14854             break;
14855          default:
14856             ;
14857          }
14858       }
14859       if (tmp->channel > 0) {
14860          snprintf(tmps, sizeof(tmps), "%d", tmp->channel);
14861       } else
14862          ast_copy_string(tmps, "pseudo", sizeof(tmps));
14863 
14864       if (tmp->locallyblocked)
14865          blockstr[0] = 'L';
14866       else
14867          blockstr[0] = ' ';
14868 
14869       if (tmp->remotelyblocked)
14870          blockstr[1] = 'R';
14871       else
14872          blockstr[1] = ' ';
14873 
14874       blockstr[2] = '\0';
14875 
14876       snprintf(statestr, sizeof(statestr), "%s", "In Service");
14877 
14878       ast_cli(a->fd, FORMAT, tmps, tmp->exten, tmp->context, tmp->language, tmp->mohinterpret, blockstr, statestr);
14879       tmp = tmp->next;
14880    }
14881    ast_mutex_unlock(lock);
14882    return CLI_SUCCESS;
14883 #undef FORMAT
14884 #undef FORMAT2
14885 }
14886 
14887 static char *dahdi_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14888 {
14889    int channel;
14890    struct dahdi_pvt *tmp = NULL;
14891    struct dahdi_confinfo ci;
14892    struct dahdi_params ps;
14893    int x;
14894    ast_mutex_t *lock;
14895    struct dahdi_pvt *start;
14896 #ifdef HAVE_PRI
14897    char *c;
14898    int trunkgroup;
14899    struct dahdi_pri *pri=NULL;
14900 #endif
14901    switch (cmd) {
14902    case CLI_INIT:
14903       e->command = "dahdi show channel";
14904       e->usage =
14905          "Usage: dahdi show channel <chan num>\n"
14906          "  Detailed information about a given channel\n";
14907       return NULL;
14908    case CLI_GENERATE:
14909       return NULL;
14910    }
14911 
14912    lock = &iflock;
14913    start = iflist;
14914 
14915    if (a->argc != 4)
14916       return CLI_SHOWUSAGE;
14917 #ifdef HAVE_PRI
14918    if ((c = strchr(a->argv[3], ':'))) {
14919       if (sscanf(a->argv[3], "%30d:%30d", &trunkgroup, &channel) != 2)
14920          return CLI_SHOWUSAGE;
14921       if ((trunkgroup < 1) || (channel < 1))
14922          return CLI_SHOWUSAGE;
14923       for (x = 0; x < NUM_SPANS; x++) {
14924          if (pris[x].trunkgroup == trunkgroup) {
14925             pri = pris + x;
14926             break;
14927          }
14928       }
14929       if (pri) {
14930          start = pri->crvs;
14931          lock = &pri->lock;
14932       } else {
14933          ast_cli(a->fd, "No such trunk group %d\n", trunkgroup);
14934          return CLI_FAILURE;
14935       }
14936    } else
14937 #endif
14938       channel = atoi(a->argv[3]);
14939 
14940    ast_mutex_lock(lock);
14941    tmp = start;
14942    while (tmp) {
14943       if (tmp->channel == channel) {
14944 #ifdef HAVE_PRI
14945          if (pri)
14946             ast_cli(a->fd, "Trunk/CRV: %d/%d\n", trunkgroup, tmp->channel);
14947          else
14948 #endif
14949          ast_cli(a->fd, "Channel: %d\n", tmp->channel);
14950          ast_cli(a->fd, "File Descriptor: %d\n", tmp->subs[SUB_REAL].dfd);
14951          ast_cli(a->fd, "Span: %d\n", tmp->span);
14952          ast_cli(a->fd, "Extension: %s\n", tmp->exten);
14953          ast_cli(a->fd, "Dialing: %s\n", tmp->dialing ? "yes" : "no");
14954          ast_cli(a->fd, "Context: %s\n", tmp->context);
14955          ast_cli(a->fd, "Caller ID: %s\n", tmp->cid_num);
14956          ast_cli(a->fd, "Calling TON: %d\n", tmp->cid_ton);
14957          ast_cli(a->fd, "Caller ID name: %s\n", tmp->cid_name);
14958          ast_cli(a->fd, "Mailbox: %s\n", S_OR(tmp->mailbox, "none"));
14959          if (tmp->vars) {
14960             struct ast_variable *v;
14961             ast_cli(a->fd, "Variables:\n");
14962             for (v = tmp->vars ; v ; v = v->next)
14963                ast_cli(a->fd, "       %s = %s\n", v->name, v->value);
14964          }
14965          ast_cli(a->fd, "Destroy: %d\n", tmp->destroy);
14966          ast_cli(a->fd, "InAlarm: %d\n", tmp->inalarm);
14967          ast_cli(a->fd, "Signalling Type: %s\n", sig2str(tmp->sig));
14968          ast_cli(a->fd, "Radio: %d\n", tmp->radio);
14969          ast_cli(a->fd, "Owner: %s\n", tmp->owner ? tmp->owner->name : "<None>");
14970          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)" : "");
14971          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)" : "");
14972          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)" : "");
14973          ast_cli(a->fd, "Confno: %d\n", tmp->confno);
14974          ast_cli(a->fd, "Propagated Conference: %d\n", tmp->propconfno);
14975          ast_cli(a->fd, "Real in conference: %d\n", tmp->inconference);
14976          ast_cli(a->fd, "DSP: %s\n", tmp->dsp ? "yes" : "no");
14977          ast_cli(a->fd, "Busy Detection: %s\n", tmp->busydetect ? "yes" : "no");
14978          if (tmp->busydetect) {
14979 #if defined(BUSYDETECT_TONEONLY)
14980             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_TONEONLY\n");
14981 #elif defined(BUSYDETECT_COMPARE_TONE_AND_SILENCE)
14982             ast_cli(a->fd, "    Busy Detector Helper: BUSYDETECT_COMPARE_TONE_AND_SILENCE\n");
14983 #endif
14984 #ifdef BUSYDETECT_DEBUG
14985             ast_cli(a->fd, "    Busy Detector Debug: Enabled\n");
14986 #endif
14987             ast_cli(a->fd, "    Busy Count: %d\n", tmp->busycount);
14988             ast_cli(a->fd, "    Busy Pattern: %d,%d\n", tmp->busy_tonelength, tmp->busy_quietlength);
14989          }
14990          ast_cli(a->fd, "TDD: %s\n", tmp->tdd ? "yes" : "no");
14991          ast_cli(a->fd, "Relax DTMF: %s\n", tmp->dtmfrelax ? "yes" : "no");
14992          ast_cli(a->fd, "Dialing/CallwaitCAS: %d/%d\n", tmp->dialing, tmp->callwaitcas);
14993          ast_cli(a->fd, "Default law: %s\n", tmp->law == DAHDI_LAW_MULAW ? "ulaw" : tmp->law == DAHDI_LAW_ALAW ? "alaw" : "unknown");
14994          ast_cli(a->fd, "Fax Handled: %s\n", tmp->faxhandled ? "yes" : "no");
14995          ast_cli(a->fd, "Pulse phone: %s\n", tmp->pulsedial ? "yes" : "no");
14996          ast_cli(a->fd, "DND: %s\n", tmp->dnd ? "yes" : "no");
14997          ast_cli(a->fd, "Echo Cancellation:\n");
14998 
14999          if (tmp->echocancel.head.tap_length) {
15000             ast_cli(a->fd, "\t%d taps\n", tmp->echocancel.head.tap_length);
15001             for (x = 0; x < tmp->echocancel.head.param_count; x++) {
15002                ast_cli(a->fd, "\t\t%s: %ud\n", tmp->echocancel.params[x].name, tmp->echocancel.params[x].value);
15003             }
15004             ast_cli(a->fd, "\t%scurrently %s\n", tmp->echocanbridged ? "" : "(unless TDM bridged) ", tmp->echocanon ? "ON" : "OFF");
15005          } else {
15006             ast_cli(a->fd, "\tnone\n");
15007          }
15008          ast_cli(a->fd, "Wait for dialtone: %dms\n", tmp->waitfordialtone);
15009          if (tmp->master)
15010             ast_cli(a->fd, "Master Channel: %d\n", tmp->master->channel);
15011          for (x = 0; x < MAX_SLAVES; x++) {
15012             if (tmp->slaves[x])
15013                ast_cli(a->fd, "Slave Channel: %d\n", tmp->slaves[x]->channel);
15014          }
15015 #ifdef HAVE_OPENR2
15016          if (tmp->mfcr2) {
15017             char calldir[OR2_MAX_PATH];
15018             openr2_context_t *r2context = openr2_chan_get_context(tmp->r2chan);
15019             openr2_variant_t r2variant = openr2_context_get_variant(r2context);
15020             ast_cli(a->fd, "MFC/R2 MF State: %s\n", openr2_chan_get_mf_state_string(tmp->r2chan));
15021             ast_cli(a->fd, "MFC/R2 MF Group: %s\n", openr2_chan_get_mf_group_string(tmp->r2chan));
15022             ast_cli(a->fd, "MFC/R2 State: %s\n", openr2_chan_get_r2_state_string(tmp->r2chan));
15023             ast_cli(a->fd, "MFC/R2 Call State: %s\n", openr2_chan_get_call_state_string(tmp->r2chan));
15024             ast_cli(a->fd, "MFC/R2 Call Files Enabled: %s\n", openr2_chan_get_call_files_enabled(tmp->r2chan) ? "Yes" : "No");
15025             ast_cli(a->fd, "MFC/R2 Variant: %s\n", openr2_proto_get_variant_string(r2variant));
15026             ast_cli(a->fd, "MFC/R2 Max ANI: %d\n", openr2_context_get_max_ani(r2context));
15027             ast_cli(a->fd, "MFC/R2 Max DNIS: %d\n", openr2_context_get_max_dnis(r2context));
15028             ast_cli(a->fd, "MFC/R2 Get ANI First: %s\n", openr2_context_get_ani_first(r2context) ? "Yes" : "No");
15029 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
15030             ast_cli(a->fd, "MFC/R2 Skip Category Request: %s\n", openr2_context_get_skip_category_request(r2context) ? "Yes" : "No");
15031 #endif
15032             ast_cli(a->fd, "MFC/R2 Immediate Accept: %s\n", openr2_context_get_immediate_accept(r2context) ? "Yes" : "No");
15033             ast_cli(a->fd, "MFC/R2 Accept on Offer: %s\n", tmp->mfcr2_accept_on_offer ? "Yes" : "No");
15034             ast_cli(a->fd, "MFC/R2 Charge Calls: %s\n", tmp->mfcr2_charge_calls ? "Yes" : "No");
15035             ast_cli(a->fd, "MFC/R2 Allow Collect Calls: %s\n", tmp->mfcr2_allow_collect_calls ? "Yes" : "No");
15036             ast_cli(a->fd, "MFC/R2 Forced Release: %s\n", tmp->mfcr2_forced_release ? "Yes" : "No");
15037             ast_cli(a->fd, "MFC/R2 MF Back Timeout: %dms\n", openr2_context_get_mf_back_timeout(r2context));
15038             ast_cli(a->fd, "MFC/R2 R2 Metering Pulse Timeout: %dms\n", openr2_context_get_metering_pulse_timeout(r2context));
15039             ast_cli(a->fd, "MFC/R2 Rx CAS: %s\n", openr2_chan_get_rx_cas_string(tmp->r2chan));
15040             ast_cli(a->fd, "MFC/R2 Tx CAS: %s\n", openr2_chan_get_tx_cas_string(tmp->r2chan));
15041             ast_cli(a->fd, "MFC/R2 MF Tx Signal: %d\n", openr2_chan_get_tx_mf_signal(tmp->r2chan));
15042             ast_cli(a->fd, "MFC/R2 MF Rx Signal: %d\n", openr2_chan_get_rx_mf_signal(tmp->r2chan));
15043             ast_cli(a->fd, "MFC/R2 Call Files Directory: %s\n", openr2_context_get_log_directory(r2context, calldir, sizeof(calldir)));
15044          }
15045 #endif
15046 #ifdef HAVE_SS7
15047          if (tmp->ss7) {
15048             ast_cli(a->fd, "CIC: %d\n", tmp->cic);
15049          }
15050 #endif
15051 #ifdef HAVE_PRI
15052          if (tmp->pri) {
15053             ast_cli(a->fd, "PRI Flags: ");
15054             if (tmp->resetting)
15055                ast_cli(a->fd, "Resetting ");
15056             if (tmp->call)
15057                ast_cli(a->fd, "Call ");
15058             if (tmp->bearer)
15059                ast_cli(a->fd, "Bearer ");
15060             ast_cli(a->fd, "\n");
15061             if (tmp->logicalspan)
15062                ast_cli(a->fd, "PRI Logical Span: %d\n", tmp->logicalspan);
15063             else
15064                ast_cli(a->fd, "PRI Logical Span: Implicit\n");
15065          }
15066 #endif
15067          memset(&ci, 0, sizeof(ci));
15068          ps.channo = tmp->channel;
15069          if (tmp->subs[SUB_REAL].dfd > -1) {
15070             memset(&ci, 0, sizeof(ci));
15071             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONF, &ci)) {
15072                ast_cli(a->fd, "Actual Confinfo: Num/%d, Mode/0x%04x\n", ci.confno, ci.confmode);
15073             }
15074             if (!ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GETCONFMUTE, &x)) {
15075                ast_cli(a->fd, "Actual Confmute: %s\n", x ? "Yes" : "No");
15076             }
15077             memset(&ps, 0, sizeof(ps));
15078             if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &ps) < 0) {
15079                ast_log(LOG_WARNING, "Failed to get parameters on channel %d: %s\n", tmp->channel, strerror(errno));
15080             } else {
15081                ast_cli(a->fd, "Hookstate (FXS only): %s\n", ps.rxisoffhook ? "Offhook" : "Onhook");
15082             }
15083          }
15084          ast_mutex_unlock(lock);
15085          return CLI_SUCCESS;
15086       }
15087       tmp = tmp->next;
15088    }
15089 
15090    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15091    ast_mutex_unlock(lock);
15092    return CLI_FAILURE;
15093 }
15094 
15095 static char *handle_dahdi_show_cadences(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15096 {
15097    int i, j;
15098    switch (cmd) {
15099    case CLI_INIT:
15100       e->command = "dahdi show cadences";
15101       e->usage =
15102          "Usage: dahdi show cadences\n"
15103          "       Shows all cadences currently defined\n";
15104       return NULL;
15105    case CLI_GENERATE:
15106       return NULL;
15107    }
15108    for (i = 0; i < num_cadence; i++) {
15109       char output[1024];
15110       char tmp[16], tmp2[64];
15111       snprintf(tmp, sizeof(tmp), "r%d: ", i + 1);
15112       term_color(output, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(output));
15113 
15114       for (j = 0; j < 16; j++) {
15115          if (cadences[i].ringcadence[j] == 0)
15116             break;
15117          snprintf(tmp, sizeof(tmp), "%d", cadences[i].ringcadence[j]);
15118          if (cidrings[i] * 2 - 1 == j)
15119             term_color(tmp2, tmp, COLOR_MAGENTA, COLOR_BLACK, sizeof(tmp2) - 1);
15120          else
15121             term_color(tmp2, tmp, COLOR_GREEN, COLOR_BLACK, sizeof(tmp2) - 1);
15122          if (j != 0)
15123             strncat(output, ",", sizeof(output) - strlen(output) - 1);
15124          strncat(output, tmp2, sizeof(output) - strlen(output) - 1);
15125       }
15126       ast_cli(a->fd,"%s\n",output);
15127    }
15128    return CLI_SUCCESS;
15129 }
15130 
15131 /* Based on irqmiss.c */
15132 static char *dahdi_show_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15133 {
15134    #define FORMAT "%-40.40s %-7.7s %-6d %-6d %-6d %-3.3s %-4.4s %-8.8s %s\n"
15135    #define FORMAT2 "%-40.40s %-7.7s %-6.6s %-6.6s %-6.6s %-3.3s %-4.4s %-8.8s %s\n"
15136    int span;
15137    int res;
15138    char alarmstr[50];
15139 
15140    int ctl;
15141    struct dahdi_spaninfo s;
15142 
15143    switch (cmd) {
15144    case CLI_INIT:
15145       e->command = "dahdi show status";
15146       e->usage =
15147          "Usage: dahdi show status\n"
15148          "       Shows a list of DAHDI cards with status\n";
15149       return NULL;
15150    case CLI_GENERATE:
15151       return NULL;
15152    }
15153    ctl = open("/dev/dahdi/ctl", O_RDWR);
15154    if (ctl < 0) {
15155       ast_cli(a->fd, "No DAHDI found. Unable to open /dev/dahdi/ctl: %s\n", strerror(errno));
15156       return CLI_FAILURE;
15157    }
15158    ast_cli(a->fd, FORMAT2, "Description", "Alarms", "IRQ", "bpviol", "CRC4", "Framing", "Coding", "Options", "LBO");
15159 
15160    for (span = 1; span < DAHDI_MAX_SPANS; ++span) {
15161       s.spanno = span;
15162       res = ioctl(ctl, DAHDI_SPANSTAT, &s);
15163       if (res) {
15164          continue;
15165       }
15166       alarmstr[0] = '\0';
15167       if (s.alarms > 0) {
15168          if (s.alarms & DAHDI_ALARM_BLUE)
15169             strcat(alarmstr, "BLU/");
15170          if (s.alarms & DAHDI_ALARM_YELLOW)
15171             strcat(alarmstr, "YEL/");
15172          if (s.alarms & DAHDI_ALARM_RED)
15173             strcat(alarmstr, "RED/");
15174          if (s.alarms & DAHDI_ALARM_LOOPBACK)
15175             strcat(alarmstr, "LB/");
15176          if (s.alarms & DAHDI_ALARM_RECOVER)
15177             strcat(alarmstr, "REC/");
15178          if (s.alarms & DAHDI_ALARM_NOTOPEN)
15179             strcat(alarmstr, "NOP/");
15180          if (!strlen(alarmstr))
15181             strcat(alarmstr, "UUU/");
15182          if (strlen(alarmstr)) {
15183             /* Strip trailing / */
15184             alarmstr[strlen(alarmstr) - 1] = '\0';
15185          }
15186       } else {
15187          if (s.numchans)
15188             strcpy(alarmstr, "OK");
15189          else
15190             strcpy(alarmstr, "UNCONFIGURED");
15191       }
15192 
15193       ast_cli(a->fd, FORMAT, s.desc, alarmstr, s.irqmisses, s.bpvcount, s.crc4count,
15194          s.lineconfig & DAHDI_CONFIG_D4 ? "D4" :
15195          s.lineconfig & DAHDI_CONFIG_ESF ? "ESF" :
15196          s.lineconfig & DAHDI_CONFIG_CCS ? "CCS" :
15197          "CAS",
15198          s.lineconfig & DAHDI_CONFIG_B8ZS ? "B8ZS" :
15199          s.lineconfig & DAHDI_CONFIG_HDB3 ? "HDB3" :
15200          s.lineconfig & DAHDI_CONFIG_AMI ? "AMI" :
15201          "Unk",
15202          s.lineconfig & DAHDI_CONFIG_CRC4 ?
15203             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "CRC4/YEL" : "CRC4" :
15204             s.lineconfig & DAHDI_CONFIG_NOTOPEN ? "YEL" : "",
15205          lbostr[s.lbo]
15206          );
15207    }
15208    close(ctl);
15209 
15210    return CLI_SUCCESS;
15211 #undef FORMAT
15212 #undef FORMAT2
15213 }
15214 
15215 static char *dahdi_show_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15216 {
15217    int pseudo_fd = -1;
15218    struct dahdi_versioninfo vi;
15219 
15220    switch (cmd) {
15221    case CLI_INIT:
15222       e->command = "dahdi show version";
15223       e->usage =
15224          "Usage: dahdi show version\n"
15225          "       Shows the DAHDI version in use\n";
15226       return NULL;
15227    case CLI_GENERATE:
15228       return NULL;
15229    }
15230    if ((pseudo_fd = open("/dev/dahdi/ctl", O_RDONLY)) < 0) {
15231       ast_cli(a->fd, "Failed to open control file to get version.\n");
15232       return CLI_SUCCESS;
15233    }
15234 
15235    strcpy(vi.version, "Unknown");
15236    strcpy(vi.echo_canceller, "Unknown");
15237 
15238    if (ioctl(pseudo_fd, DAHDI_GETVERSION, &vi))
15239       ast_cli(a->fd, "Failed to get DAHDI version: %s\n", strerror(errno));
15240    else
15241       ast_cli(a->fd, "DAHDI Version: %s Echo Canceller: %s\n", vi.version, vi.echo_canceller);
15242 
15243    close(pseudo_fd);
15244 
15245    return CLI_SUCCESS;
15246 }
15247 
15248 static char *dahdi_set_hwgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15249 {
15250    int channel;
15251    int gain;
15252    int tx;
15253    struct dahdi_hwgain hwgain;
15254    struct dahdi_pvt *tmp = NULL;
15255 
15256    switch (cmd) {
15257    case CLI_INIT:
15258       e->command = "dahdi set hwgain";
15259       e->usage =
15260          "Usage: dahdi set hwgain <rx|tx> <chan#> <gain>\n"
15261          "  Sets the hardware gain on a a given channel, overriding the\n"
15262          "   value provided at module loadtime, whether the channel is in\n"
15263          "   use or not.  Changes take effect immediately.\n"
15264          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15265          "   <chan num> is the channel number relative to the device\n"
15266          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15267       return NULL;
15268    case CLI_GENERATE:
15269       return NULL;
15270    }
15271 
15272    if (a->argc != 6)
15273       return CLI_SHOWUSAGE;
15274 
15275    if (!strcasecmp("rx", a->argv[3]))
15276       tx = 0; /* rx */
15277    else if (!strcasecmp("tx", a->argv[3]))
15278       tx = 1; /* tx */
15279    else
15280       return CLI_SHOWUSAGE;
15281 
15282    channel = atoi(a->argv[4]);
15283    gain = atof(a->argv[5])*10.0;
15284 
15285    ast_mutex_lock(&iflock);
15286 
15287    for (tmp = iflist; tmp; tmp = tmp->next) {
15288 
15289       if (tmp->channel != channel)
15290          continue;
15291 
15292       if (tmp->subs[SUB_REAL].dfd == -1)
15293          break;
15294 
15295       hwgain.newgain = gain;
15296       hwgain.tx = tx;
15297       if (ioctl(tmp->subs[SUB_REAL].dfd, DAHDI_SET_HWGAIN, &hwgain) < 0) {
15298          ast_cli(a->fd, "Unable to set the hardware gain for channel %d: %s\n", channel, strerror(errno));
15299          ast_mutex_unlock(&iflock);
15300          return CLI_FAILURE;
15301       }
15302       ast_cli(a->fd, "hardware %s gain set to %d (%.1f dB) on channel %d\n",
15303          tx ? "tx" : "rx", gain, (float)gain/10.0, channel);
15304       break;
15305    }
15306 
15307    ast_mutex_unlock(&iflock);
15308 
15309    if (tmp)
15310       return CLI_SUCCESS;
15311 
15312    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15313    return CLI_FAILURE;
15314 
15315 }
15316 
15317 static char *dahdi_set_swgain(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15318 {
15319    int channel;
15320    float gain;
15321    int tx;
15322    int res;
15323    ast_mutex_t *lock;
15324    struct dahdi_pvt *tmp = NULL;
15325 
15326    switch (cmd) {
15327    case CLI_INIT:
15328       e->command = "dahdi set swgain";
15329       e->usage =
15330          "Usage: dahdi set swgain <rx|tx> <chan#> <gain>\n"
15331          "  Sets the software gain on a a given channel, overriding the\n"
15332          "   value provided at module loadtime, whether the channel is in\n"
15333          "   use or not.  Changes take effect immediately.\n"
15334          "   <rx|tx> which direction do you want to change (relative to our module)\n"
15335          "   <chan num> is the channel number relative to the device\n"
15336          "   <gain> is the gain in dB (e.g. -3.5 for -3.5dB)\n";
15337       return NULL;
15338    case CLI_GENERATE:
15339       return NULL;
15340    }
15341 
15342    lock = &iflock;
15343 
15344    if (a->argc != 6)
15345       return CLI_SHOWUSAGE;
15346 
15347    if (!strcasecmp("rx", a->argv[3]))
15348       tx = 0; /* rx */
15349    else if (!strcasecmp("tx", a->argv[3]))
15350       tx = 1; /* tx */
15351    else
15352       return CLI_SHOWUSAGE;
15353 
15354    channel = atoi(a->argv[4]);
15355    gain = atof(a->argv[5]);
15356 
15357    ast_mutex_lock(lock);
15358    for (tmp = iflist; tmp; tmp = tmp->next) {
15359 
15360       if (tmp->channel != channel)
15361          continue;
15362 
15363       if (tmp->subs[SUB_REAL].dfd == -1)
15364          break;
15365 
15366       if (tx)
15367          res = set_actual_txgain(tmp->subs[SUB_REAL].dfd, channel, gain, tmp->law);
15368       else
15369          res = set_actual_rxgain(tmp->subs[SUB_REAL].dfd, channel, gain, tmp->law);
15370 
15371       if (res) {
15372          ast_cli(a->fd, "Unable to set the software gain for channel %d\n", channel);
15373          ast_mutex_unlock(lock);
15374          return CLI_FAILURE;
15375       }
15376 
15377       ast_cli(a->fd, "software %s gain set to %.1f on channel %d\n",
15378          tx ? "tx" : "rx", gain, channel);
15379       break;
15380    }
15381    ast_mutex_unlock(lock);
15382 
15383    if (tmp)
15384       return CLI_SUCCESS;
15385 
15386    ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15387    return CLI_FAILURE;
15388 
15389 }
15390 
15391 static char *dahdi_set_dnd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15392 {
15393    int channel;
15394    int on;
15395    struct dahdi_pvt *dahdi_chan = NULL;
15396 
15397    switch (cmd) {
15398    case CLI_INIT:
15399       e->command = "dahdi set dnd";
15400       e->usage =
15401          "Usage: dahdi set dnd <chan#> <on|off>\n"
15402          "  Sets/resets DND (Do Not Disturb) mode on a channel.\n"
15403          "  Changes take effect immediately.\n"
15404          "  <chan num> is the channel number\n"
15405          "  <on|off> Enable or disable DND mode?\n"
15406          ;
15407       return NULL;
15408    case CLI_GENERATE:
15409       return NULL;
15410    }
15411 
15412    if (a->argc != 5)
15413       return CLI_SHOWUSAGE;
15414 
15415    if ((channel = atoi(a->argv[3])) <= 0) {
15416       ast_cli(a->fd, "Expected channel number, got '%s'\n", a->argv[3]);
15417       return CLI_SHOWUSAGE;
15418    }
15419 
15420    if (ast_true(a->argv[4]))
15421       on = 1;
15422    else if (ast_false(a->argv[4]))
15423       on = 0;
15424    else {
15425       ast_cli(a->fd, "Expected 'on' or 'off', got '%s'\n", a->argv[4]);
15426       return CLI_SHOWUSAGE;
15427    }
15428 
15429    ast_mutex_lock(&iflock);
15430    for (dahdi_chan = iflist; dahdi_chan; dahdi_chan = dahdi_chan->next) {
15431       if (dahdi_chan->channel != channel)
15432          continue;
15433 
15434       /* Found the channel. Actually set it */
15435       dahdi_dnd(dahdi_chan, on);
15436       break;
15437    }
15438    ast_mutex_unlock(&iflock);
15439 
15440    if (!dahdi_chan) {
15441       ast_cli(a->fd, "Unable to find given channel %d\n", channel);
15442       return CLI_FAILURE;
15443    }
15444 
15445    return CLI_SUCCESS;
15446 }
15447 
15448 static struct ast_cli_entry dahdi_cli[] = {
15449    AST_CLI_DEFINE(handle_dahdi_show_cadences, "List cadences"),
15450    AST_CLI_DEFINE(dahdi_show_channels, "Show active DAHDI channels"),
15451    AST_CLI_DEFINE(dahdi_show_channel, "Show information on a channel"),
15452    AST_CLI_DEFINE(dahdi_destroy_channel, "Destroy a channel"),
15453    AST_CLI_DEFINE(dahdi_restart_cmd, "Fully restart DAHDI channels"),
15454    AST_CLI_DEFINE(dahdi_show_status, "Show all DAHDI cards status"),
15455    AST_CLI_DEFINE(dahdi_show_version, "Show the DAHDI version in use"),
15456    AST_CLI_DEFINE(dahdi_set_hwgain, "Set hardware gain on a channel"),
15457    AST_CLI_DEFINE(dahdi_set_swgain, "Set software gain on a channel"),
15458    AST_CLI_DEFINE(dahdi_set_dnd, "Sets/resets DND (Do Not Disturb) mode on a channel"),
15459 };
15460 
15461 #define TRANSFER  0
15462 #define HANGUP    1
15463 
15464 static int dahdi_fake_event(struct dahdi_pvt *p, int mode)
15465 {
15466    if (p) {
15467       switch (mode) {
15468          case TRANSFER:
15469             p->fake_event = DAHDI_EVENT_WINKFLASH;
15470             break;
15471          case HANGUP:
15472             p->fake_event = DAHDI_EVENT_ONHOOK;
15473             break;
15474          default:
15475             ast_log(LOG_WARNING, "I don't know how to handle transfer event with this: %d on channel %s\n",mode, p->owner->name);
15476       }
15477    }
15478    return 0;
15479 }
15480 static struct dahdi_pvt *find_channel(int channel)
15481 {
15482    struct dahdi_pvt *p = iflist;
15483    while (p) {
15484       if (p->channel == channel) {
15485          break;
15486       }
15487       p = p->next;
15488    }
15489    return p;
15490 }
15491 
15492 static int action_dahdidndon(struct mansession *s, const struct message *m)
15493 {
15494    struct dahdi_pvt *p = NULL;
15495    const char *channel = astman_get_header(m, "DAHDIChannel");
15496 
15497    if (ast_strlen_zero(channel)) {
15498       astman_send_error(s, m, "No channel specified");
15499       return 0;
15500    }
15501    p = find_channel(atoi(channel));
15502    if (!p) {
15503       astman_send_error(s, m, "No such channel");
15504       return 0;
15505    }
15506    p->dnd = 1;
15507    astman_send_ack(s, m, "DND Enabled");
15508    return 0;
15509 }
15510 
15511 static int action_dahdidndoff(struct mansession *s, const struct message *m)
15512 {
15513    struct dahdi_pvt *p = NULL;
15514    const char *channel = astman_get_header(m, "DAHDIChannel");
15515 
15516    if (ast_strlen_zero(channel)) {
15517       astman_send_error(s, m, "No channel specified");
15518       return 0;
15519    }
15520    p = find_channel(atoi(channel));
15521    if (!p) {
15522       astman_send_error(s, m, "No such channel");
15523       return 0;
15524    }
15525    p->dnd = 0;
15526    astman_send_ack(s, m, "DND Disabled");
15527    return 0;
15528 }
15529 
15530 static int action_transfer(struct mansession *s, const struct message *m)
15531 {
15532    struct dahdi_pvt *p = NULL;
15533    const char *channel = astman_get_header(m, "DAHDIChannel");
15534 
15535    if (ast_strlen_zero(channel)) {
15536       astman_send_error(s, m, "No channel specified");
15537       return 0;
15538    }
15539    p = find_channel(atoi(channel));
15540    if (!p) {
15541       astman_send_error(s, m, "No such channel");
15542       return 0;
15543    }
15544    dahdi_fake_event(p,TRANSFER);
15545    astman_send_ack(s, m, "DAHDITransfer");
15546    return 0;
15547 }
15548 
15549 static int action_transferhangup(struct mansession *s, const struct message *m)
15550 {
15551    struct dahdi_pvt *p = NULL;
15552    const char *channel = astman_get_header(m, "DAHDIChannel");
15553 
15554    if (ast_strlen_zero(channel)) {
15555       astman_send_error(s, m, "No channel specified");
15556       return 0;
15557    }
15558    p = find_channel(atoi(channel));
15559    if (!p) {
15560       astman_send_error(s, m, "No such channel");
15561       return 0;
15562    }
15563    dahdi_fake_event(p,HANGUP);
15564    astman_send_ack(s, m, "DAHDIHangup");
15565    return 0;
15566 }
15567 
15568 static int action_dahdidialoffhook(struct mansession *s, const struct message *m)
15569 {
15570    struct dahdi_pvt *p = NULL;
15571    const char *channel = astman_get_header(m, "DAHDIChannel");
15572    const char *number = astman_get_header(m, "Number");
15573    int i;
15574 
15575    if (ast_strlen_zero(channel)) {
15576       astman_send_error(s, m, "No channel specified");
15577       return 0;
15578    }
15579    if (ast_strlen_zero(number)) {
15580       astman_send_error(s, m, "No number specified");
15581       return 0;
15582    }
15583    p = find_channel(atoi(channel));
15584    if (!p) {
15585       astman_send_error(s, m, "No such channel");
15586       return 0;
15587    }
15588    if (!p->owner) {
15589       astman_send_error(s, m, "Channel does not have it's owner");
15590       return 0;
15591    }
15592    for (i = 0; i < strlen(number); i++) {
15593       struct ast_frame f = { AST_FRAME_DTMF, number[i] };
15594       dahdi_queue_frame(p, &f, NULL);
15595    }
15596    astman_send_ack(s, m, "DAHDIDialOffhook");
15597    return 0;
15598 }
15599 
15600 static int action_dahdishowchannels(struct mansession *s, const struct message *m)
15601 {
15602    struct dahdi_pvt *tmp = NULL;
15603    const char *id = astman_get_header(m, "ActionID");
15604    const char *dahdichannel = astman_get_header(m, "DAHDIChannel");
15605    char idText[256] = "";
15606    int channels = 0;
15607    int dahdichanquery = -1;
15608    if (!ast_strlen_zero(dahdichannel)) {
15609       dahdichanquery = atoi(dahdichannel);
15610    }
15611 
15612    astman_send_ack(s, m, "DAHDI channel status will follow");
15613    if (!ast_strlen_zero(id))
15614       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
15615 
15616    ast_mutex_lock(&iflock);
15617 
15618    tmp = iflist;
15619    while (tmp) {
15620       if (tmp->channel > 0) {
15621          int alm = get_alarms(tmp);
15622 
15623          /* If a specific channel is queried for, only deliver status for that channel */
15624          if (dahdichanquery > 0 && tmp->channel != dahdichanquery)
15625             continue;
15626 
15627          channels++;
15628          if (tmp->owner) {
15629             /* Add data if we have a current call */
15630             astman_append(s,
15631                "Event: DAHDIShowChannels\r\n"
15632                "DAHDIChannel: %d\r\n"
15633                "Channel: %s\r\n"
15634                "Uniqueid: %s\r\n"
15635                "AccountCode: %s\r\n"
15636                "Signalling: %s\r\n"
15637                "SignallingCode: %d\r\n"
15638                "Context: %s\r\n"
15639                "DND: %s\r\n"
15640                "Alarm: %s\r\n"
15641                "%s"
15642                "\r\n",
15643                tmp->channel,
15644                tmp->owner->name,
15645                tmp->owner->uniqueid,
15646                tmp->owner->accountcode,
15647                sig2str(tmp->sig),
15648                tmp->sig,
15649                tmp->context,
15650                tmp->dnd ? "Enabled" : "Disabled",
15651                alarm2str(alm), idText);
15652          } else {
15653             astman_append(s,
15654                "Event: DAHDIShowChannels\r\n"
15655                "DAHDIChannel: %d\r\n"
15656                "Signalling: %s\r\n"
15657                "SignallingCode: %d\r\n"
15658                "Context: %s\r\n"
15659                "DND: %s\r\n"
15660                "Alarm: %s\r\n"
15661                "%s"
15662                "\r\n",
15663                tmp->channel, sig2str(tmp->sig), tmp->sig,
15664                tmp->context,
15665                tmp->dnd ? "Enabled" : "Disabled",
15666                alarm2str(alm), idText);
15667          }
15668       }
15669 
15670       tmp = tmp->next;
15671    }
15672 
15673    ast_mutex_unlock(&iflock);
15674 
15675    astman_append(s,
15676       "Event: DAHDIShowChannelsComplete\r\n"
15677       "%s"
15678       "Items: %d\r\n"
15679       "\r\n",
15680       idText,
15681       channels);
15682    return 0;
15683 }
15684 
15685 #if defined(HAVE_SS7)
15686 static int linkset_addsigchan(int sigchan)
15687 {
15688    struct dahdi_ss7 *link;
15689    int res;
15690    int curfd;
15691    struct dahdi_params p;
15692    struct dahdi_bufferinfo bi;
15693    struct dahdi_spaninfo si;
15694 
15695 
15696    link = ss7_resolve_linkset(cur_linkset);
15697    if (!link) {
15698       ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
15699       return -1;
15700    }
15701 
15702    if (cur_ss7type < 0) {
15703       ast_log(LOG_ERROR, "Unspecified or invalid ss7type\n");
15704       return -1;
15705    }
15706 
15707    if (!link->ss7)
15708       link->ss7 = ss7_new(cur_ss7type);
15709 
15710    if (!link->ss7) {
15711       ast_log(LOG_ERROR, "Can't create new SS7!\n");
15712       return -1;
15713    }
15714 
15715    link->type = cur_ss7type;
15716 
15717    if (cur_pointcode < 0) {
15718       ast_log(LOG_ERROR, "Unspecified pointcode!\n");
15719       return -1;
15720    } else
15721       ss7_set_pc(link->ss7, cur_pointcode);
15722 
15723    if (sigchan < 0) {
15724       ast_log(LOG_ERROR, "Invalid sigchan!\n");
15725       return -1;
15726    } else {
15727       if (link->numsigchans >= NUM_DCHANS) {
15728          ast_log(LOG_ERROR, "Too many sigchans on linkset %d\n", cur_linkset);
15729          return -1;
15730       }
15731       curfd = link->numsigchans;
15732 
15733       link->fds[curfd] = open("/dev/dahdi/channel", O_RDWR, 0600);
15734       if ((link->fds[curfd] < 0) || (ioctl(link->fds[curfd],DAHDI_SPECIFY,&sigchan) == -1)) {
15735          ast_log(LOG_ERROR, "Unable to open SS7 sigchan %d (%s)\n", sigchan, strerror(errno));
15736          return -1;
15737       }
15738       memset(&p, 0, sizeof(p));
15739       res = ioctl(link->fds[curfd], DAHDI_GET_PARAMS, &p);
15740       if (res) {
15741          dahdi_close_ss7_fd(link, curfd);
15742          ast_log(LOG_ERROR, "Unable to get parameters for sigchan %d (%s)\n", sigchan, strerror(errno));
15743          return -1;
15744       }
15745       if ((p.sigtype != DAHDI_SIG_HDLCFCS) && (p.sigtype != DAHDI_SIG_HARDHDLC) && (p.sigtype != DAHDI_SIG_MTP2)) {
15746          dahdi_close_ss7_fd(link, curfd);
15747          ast_log(LOG_ERROR, "sigchan %d is not in HDLC/FCS mode.\n", sigchan);
15748          return -1;
15749       }
15750 
15751       memset(&bi, 0, sizeof(bi));
15752       bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
15753       bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
15754       bi.numbufs = 32;
15755       bi.bufsize = 512;
15756 
15757       if (ioctl(link->fds[curfd], DAHDI_SET_BUFINFO, &bi)) {
15758          ast_log(LOG_ERROR, "Unable to set appropriate buffering on channel %d: %s\n", sigchan, strerror(errno));
15759          dahdi_close_ss7_fd(link, curfd);
15760          return -1;
15761       }
15762 
15763       if (p.sigtype == DAHDI_SIG_MTP2)
15764          ss7_add_link(link->ss7, SS7_TRANSPORT_DAHDIMTP2, link->fds[curfd]);
15765       else
15766          ss7_add_link(link->ss7, SS7_TRANSPORT_DAHDIDCHAN, link->fds[curfd]);
15767 
15768       link->numsigchans++;
15769 
15770       memset(&si, 0, sizeof(si));
15771       res = ioctl(link->fds[curfd], DAHDI_SPANSTAT, &si);
15772       if (res) {
15773          dahdi_close_ss7_fd(link, curfd);
15774          ast_log(LOG_ERROR, "Unable to get span state for sigchan %d (%s)\n", sigchan, strerror(errno));
15775       }
15776 
15777       if (!si.alarms) {
15778          link->linkstate[curfd] = LINKSTATE_DOWN;
15779          ss7_link_noalarm(link->ss7, link->fds[curfd]);
15780       } else {
15781          link->linkstate[curfd] = LINKSTATE_DOWN | LINKSTATE_INALARM;
15782          ss7_link_alarm(link->ss7, link->fds[curfd]);
15783       }
15784    }
15785 
15786    if (cur_adjpointcode < 0) {
15787       ast_log(LOG_ERROR, "Unspecified adjpointcode!\n");
15788       return -1;
15789    } else {
15790       ss7_set_adjpc(link->ss7, link->fds[curfd], cur_adjpointcode);
15791    }
15792 
15793    if (cur_defaultdpc < 0) {
15794       ast_log(LOG_ERROR, "Unspecified defaultdpc!\n");
15795       return -1;
15796    }
15797 
15798    if (cur_networkindicator < 0) {
15799       ast_log(LOG_ERROR, "Invalid networkindicator!\n");
15800       return -1;
15801    } else
15802       ss7_set_network_ind(link->ss7, cur_networkindicator);
15803 
15804    return 0;
15805 }
15806 #endif   /* defined(HAVE_SS7) */
15807 
15808 #if defined(HAVE_SS7)
15809 static char *handle_ss7_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15810 {
15811    int span;
15812    switch (cmd) {
15813    case CLI_INIT:
15814       e->command = "ss7 set debug {on|off} linkset";
15815       e->usage =
15816          "Usage: ss7 set debug {on|off} linkset <linkset>\n"
15817          "       Enables debugging on a given SS7 linkset\n";
15818       return NULL;
15819    case CLI_GENERATE:
15820       return NULL;
15821    }
15822    if (a->argc < 6)
15823       return CLI_SHOWUSAGE;
15824    span = atoi(a->argv[5]);
15825    if ((span < 1) || (span > NUM_SPANS)) {
15826       ast_cli(a->fd, "Invalid linkset %s.  Should be a number from %d to %d\n", a->argv[5], 1, NUM_SPANS);
15827       return CLI_SUCCESS;
15828    }
15829    if (!linksets[span-1].ss7) {
15830       ast_cli(a->fd, "No SS7 running on linkset %d\n", span);
15831       return CLI_SUCCESS;
15832    }
15833    if (linksets[span-1].ss7) {
15834       if (!strcasecmp(a->argv[3], "on")) {
15835          ss7_set_debug(linksets[span-1].ss7, SS7_DEBUG_MTP2 | SS7_DEBUG_MTP3 | SS7_DEBUG_ISUP);
15836          ast_cli(a->fd, "Enabled debugging on linkset %d\n", span);
15837       } else {
15838          ss7_set_debug(linksets[span-1].ss7, 0);
15839          ast_cli(a->fd, "Disabled debugging on linkset %d\n", span);
15840       }
15841    }
15842 
15843    return CLI_SUCCESS;
15844 }
15845 #endif   /* defined(HAVE_SS7) */
15846 
15847 #if defined(HAVE_SS7)
15848 static char *handle_ss7_block_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15849 {
15850    int linkset, cic;
15851    int blocked = -1, i;
15852    switch (cmd) {
15853    case CLI_INIT:
15854       e->command = "ss7 block cic";
15855       e->usage =
15856          "Usage: ss7 block cic <linkset> <CIC>\n"
15857          "       Sends a remote blocking request for the given CIC on the specified linkset\n";
15858       return NULL;
15859    case CLI_GENERATE:
15860       return NULL;
15861    }
15862    if (a->argc == 5)
15863       linkset = atoi(a->argv[3]);
15864    else
15865       return CLI_SHOWUSAGE;
15866 
15867    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15868       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15869       return CLI_SUCCESS;
15870    }
15871 
15872    if (!linksets[linkset-1].ss7) {
15873       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15874       return CLI_SUCCESS;
15875    }
15876 
15877    cic = atoi(a->argv[4]);
15878 
15879    if (cic < 1) {
15880       ast_cli(a->fd, "Invalid CIC specified!\n");
15881       return CLI_SUCCESS;
15882    }
15883 
15884    for (i = 0; i < linksets[linkset-1].numchans; i++) {
15885       if (linksets[linkset-1].pvts[i]->cic == cic) {
15886          blocked = linksets[linkset-1].pvts[i]->locallyblocked;
15887          if (!blocked) {
15888             ast_mutex_lock(&linksets[linkset-1].lock);
15889             isup_blo(linksets[linkset-1].ss7, cic, linksets[linkset-1].pvts[i]->dpc);
15890             ast_mutex_unlock(&linksets[linkset-1].lock);
15891          }
15892       }
15893    }
15894 
15895    if (blocked < 0) {
15896       ast_cli(a->fd, "Invalid CIC specified!\n");
15897       return CLI_SUCCESS;
15898    }
15899 
15900    if (!blocked)
15901       ast_cli(a->fd, "Sent blocking request for linkset %d on CIC %d\n", linkset, cic);
15902    else
15903       ast_cli(a->fd, "CIC %d already locally blocked\n", cic);
15904 
15905    /* Break poll on the linkset so it sends our messages */
15906    pthread_kill(linksets[linkset-1].master, SIGURG);
15907 
15908    return CLI_SUCCESS;
15909 }
15910 #endif   /* defined(HAVE_SS7) */
15911 
15912 #if defined(HAVE_SS7)
15913 static char *handle_ss7_block_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15914 {
15915    int linkset;
15916    int i;
15917    switch (cmd) {
15918    case CLI_INIT:
15919       e->command = "ss7 block linkset";
15920       e->usage =
15921          "Usage: ss7 block linkset <linkset number>\n"
15922          "       Sends a remote blocking request for all CICs on the given linkset\n";
15923       return NULL;
15924    case CLI_GENERATE:
15925       return NULL;
15926    }
15927    if (a->argc == 4)
15928       linkset = atoi(a->argv[3]);
15929    else
15930       return CLI_SHOWUSAGE;
15931 
15932    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15933       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15934       return CLI_SUCCESS;
15935    }
15936 
15937    if (!linksets[linkset-1].ss7) {
15938       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15939       return CLI_SUCCESS;
15940    }
15941 
15942    for (i = 0; i < linksets[linkset-1].numchans; i++) {
15943       ast_cli(a->fd, "Sending remote blocking request on CIC %d\n", linksets[linkset-1].pvts[i]->cic);
15944       ast_mutex_lock(&linksets[linkset-1].lock);
15945       isup_blo(linksets[linkset-1].ss7, linksets[linkset-1].pvts[i]->cic, linksets[linkset-1].pvts[i]->dpc);
15946       ast_mutex_unlock(&linksets[linkset-1].lock);
15947    }
15948 
15949    /* Break poll on the linkset so it sends our messages */
15950    pthread_kill(linksets[linkset-1].master, SIGURG);
15951 
15952    return CLI_SUCCESS;
15953 }
15954 #endif   /* defined(HAVE_SS7) */
15955 
15956 #if defined(HAVE_SS7)
15957 static char *handle_ss7_unblock_cic(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15958 {
15959    int linkset, cic;
15960    int i, blocked = -1;
15961    switch (cmd) {
15962    case CLI_INIT:
15963       e->command = "ss7 unblock cic";
15964       e->usage =
15965          "Usage: ss7 unblock cic <linkset> <CIC>\n"
15966          "       Sends a remote unblocking request for the given CIC on the specified linkset\n";
15967       return NULL;
15968    case CLI_GENERATE:
15969       return NULL;
15970    }
15971 
15972    if (a->argc == 5)
15973       linkset = atoi(a->argv[3]);
15974    else
15975       return CLI_SHOWUSAGE;
15976 
15977    if ((linkset < 1) || (linkset > NUM_SPANS)) {
15978       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
15979       return CLI_SUCCESS;
15980    }
15981 
15982    if (!linksets[linkset-1].ss7) {
15983       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
15984       return CLI_SUCCESS;
15985    }
15986 
15987    cic = atoi(a->argv[4]);
15988 
15989    if (cic < 1) {
15990       ast_cli(a->fd, "Invalid CIC specified!\n");
15991       return CLI_SUCCESS;
15992    }
15993 
15994    for (i = 0; i < linksets[linkset-1].numchans; i++) {
15995       if (linksets[linkset-1].pvts[i]->cic == cic) {
15996          blocked = linksets[linkset-1].pvts[i]->locallyblocked;
15997          if (blocked) {
15998             ast_mutex_lock(&linksets[linkset-1].lock);
15999             isup_ubl(linksets[linkset-1].ss7, cic, linksets[linkset-1].pvts[i]->dpc);
16000             ast_mutex_unlock(&linksets[linkset-1].lock);
16001          }
16002       }
16003    }
16004 
16005    if (blocked > 0)
16006       ast_cli(a->fd, "Sent unblocking request for linkset %d on CIC %d\n", linkset, cic);
16007 
16008    /* Break poll on the linkset so it sends our messages */
16009    pthread_kill(linksets[linkset-1].master, SIGURG);
16010 
16011    return CLI_SUCCESS;
16012 }
16013 #endif   /* defined(HAVE_SS7) */
16014 
16015 #if defined(HAVE_SS7)
16016 static char *handle_ss7_unblock_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16017 {
16018    int linkset;
16019    int i;
16020    switch (cmd) {
16021    case CLI_INIT:
16022       e->command = "ss7 unblock linkset";
16023       e->usage =
16024          "Usage: ss7 unblock linkset <linkset number>\n"
16025          "       Sends a remote unblocking request for all CICs on the specified linkset\n";
16026       return NULL;
16027    case CLI_GENERATE:
16028       return NULL;
16029    }
16030 
16031    if (a->argc == 4)
16032       linkset = atoi(a->argv[3]);
16033    else
16034       return CLI_SHOWUSAGE;
16035 
16036    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16037       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16038       return CLI_SUCCESS;
16039    }
16040 
16041    if (!linksets[linkset-1].ss7) {
16042       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16043       return CLI_SUCCESS;
16044    }
16045 
16046    for (i = 0; i < linksets[linkset-1].numchans; i++) {
16047       ast_cli(a->fd, "Sending remote unblock request on CIC %d\n", linksets[linkset-1].pvts[i]->cic);
16048       ast_mutex_lock(&linksets[linkset-1].lock);
16049       isup_ubl(linksets[linkset-1].ss7, linksets[linkset-1].pvts[i]->cic, linksets[linkset-1].pvts[i]->dpc);
16050       ast_mutex_unlock(&linksets[linkset-1].lock);
16051    }
16052 
16053    /* Break poll on the linkset so it sends our messages */
16054    pthread_kill(linksets[linkset-1].master, SIGURG);
16055 
16056    return CLI_SUCCESS;
16057 }
16058 #endif   /* defined(HAVE_SS7) */
16059 
16060 #if defined(HAVE_SS7)
16061 static char *handle_ss7_show_linkset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16062 {
16063    int linkset;
16064    struct dahdi_ss7 *ss7;
16065    switch (cmd) {
16066    case CLI_INIT:
16067       e->command = "ss7 show linkset";
16068       e->usage =
16069          "Usage: ss7 show linkset <span>\n"
16070          "       Shows the status of an SS7 linkset.\n";
16071       return NULL;
16072    case CLI_GENERATE:
16073       return NULL;
16074    }
16075 
16076    if (a->argc < 4)
16077       return CLI_SHOWUSAGE;
16078    linkset = atoi(a->argv[3]);
16079    if ((linkset < 1) || (linkset > NUM_SPANS)) {
16080       ast_cli(a->fd, "Invalid linkset %s.  Should be a number %d to %d\n", a->argv[3], 1, NUM_SPANS);
16081       return CLI_SUCCESS;
16082    }
16083    if (!linksets[linkset-1].ss7) {
16084       ast_cli(a->fd, "No SS7 running on linkset %d\n", linkset);
16085       return CLI_SUCCESS;
16086    }
16087    if (linksets[linkset-1].ss7)
16088       ss7 = &linksets[linkset-1];
16089 
16090    ast_cli(a->fd, "SS7 linkset %d status: %s\n", linkset, (ss7->state == LINKSET_STATE_UP) ? "Up" : "Down");
16091 
16092    return CLI_SUCCESS;
16093 }
16094 #endif   /* defined(HAVE_SS7) */
16095 
16096 #if defined(HAVE_SS7)
16097 static char *handle_ss7_version(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16098 {
16099    switch (cmd) {
16100    case CLI_INIT:
16101       e->command = "ss7 show version";
16102       e->usage =
16103          "Usage: ss7 show version\n"
16104          "  Show the libss7 version\n";
16105       return NULL;
16106    case CLI_GENERATE:
16107       return NULL;
16108    }
16109 
16110    ast_cli(a->fd, "libss7 version: %s\n", ss7_get_version());
16111 
16112    return CLI_SUCCESS;
16113 }
16114 #endif   /* defined(HAVE_SS7) */
16115 
16116 #if defined(HAVE_SS7)
16117 static struct ast_cli_entry dahdi_ss7_cli[] = {
16118    AST_CLI_DEFINE(handle_ss7_debug, "Enables SS7 debugging on a linkset"),
16119    AST_CLI_DEFINE(handle_ss7_block_cic, "Blocks the given CIC"),
16120    AST_CLI_DEFINE(handle_ss7_unblock_cic, "Unblocks the given CIC"),
16121    AST_CLI_DEFINE(handle_ss7_block_linkset, "Blocks all CICs on a linkset"),
16122    AST_CLI_DEFINE(handle_ss7_unblock_linkset, "Unblocks all CICs on a linkset"),
16123    AST_CLI_DEFINE(handle_ss7_show_linkset, "Shows the status of a linkset"),
16124    AST_CLI_DEFINE(handle_ss7_version, "Displays libss7 version"),
16125 };
16126 #endif   /* defined(HAVE_SS7) */
16127 
16128 static int __unload_module(void)
16129 {
16130    struct dahdi_pvt *p;
16131 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16132    int i, j;
16133 #endif
16134 
16135 #ifdef HAVE_PRI
16136    for (i = 0; i < NUM_SPANS; i++) {
16137       if (pris[i].master != AST_PTHREADT_NULL)
16138          pthread_cancel(pris[i].master);
16139    }
16140    ast_cli_unregister_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
16141    ast_unregister_application(dahdi_send_keypad_facility_app);
16142 #ifdef HAVE_PRI_PROG_W_CAUSE
16143    ast_unregister_application(dahdi_send_callrerouting_facility_app);
16144 #endif
16145 #endif
16146 #if defined(HAVE_SS7)
16147    for (i = 0; i < NUM_SPANS; i++) {
16148       if (linksets[i].master != AST_PTHREADT_NULL)
16149          pthread_cancel(linksets[i].master);
16150       }
16151    ast_cli_unregister_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
16152 #endif
16153 #if defined(HAVE_OPENR2)
16154    dahdi_r2_destroy_links();
16155    ast_cli_unregister_multiple(dahdi_mfcr2_cli, ARRAY_LEN(dahdi_mfcr2_cli));
16156    ast_unregister_application(dahdi_accept_r2_call_app);
16157 #endif
16158 
16159    ast_cli_unregister_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
16160    ast_manager_unregister( "DAHDIDialOffhook" );
16161    ast_manager_unregister( "DAHDIHangup" );
16162    ast_manager_unregister( "DAHDITransfer" );
16163    ast_manager_unregister( "DAHDIDNDoff" );
16164    ast_manager_unregister( "DAHDIDNDon" );
16165    ast_manager_unregister("DAHDIShowChannels");
16166    ast_manager_unregister("DAHDIRestart");
16167    ast_channel_unregister(&dahdi_tech);
16168    ast_mutex_lock(&iflock);
16169    /* Hangup all interfaces if they have an owner */
16170    p = iflist;
16171    while (p) {
16172       if (p->owner)
16173          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
16174       p = p->next;
16175    }
16176    ast_mutex_unlock(&iflock);
16177    ast_mutex_lock(&monlock);
16178    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
16179       pthread_cancel(monitor_thread);
16180       pthread_kill(monitor_thread, SIGURG);
16181       pthread_join(monitor_thread, NULL);
16182    }
16183    monitor_thread = AST_PTHREADT_STOP;
16184    ast_mutex_unlock(&monlock);
16185 
16186    destroy_all_channels();
16187 
16188 #if defined(HAVE_PRI)
16189    for (i = 0; i < NUM_SPANS; i++) {
16190       if (pris[i].master && (pris[i].master != AST_PTHREADT_NULL))
16191          pthread_join(pris[i].master, NULL);
16192       for (j = 0; j < NUM_DCHANS; j++) {
16193          dahdi_close_pri_fd(&(pris[i]), j);
16194       }
16195    }
16196 #endif
16197 
16198 #if defined(HAVE_SS7)
16199    for (i = 0; i < NUM_SPANS; i++) {
16200       if (linksets[i].master && (linksets[i].master != AST_PTHREADT_NULL))
16201          pthread_join(linksets[i].master, NULL);
16202       for (j = 0; j < NUM_DCHANS; j++) {
16203          dahdi_close_ss7_fd(&(linksets[i]), j);
16204       }
16205    }
16206 #endif
16207    ast_cond_destroy(&ss_thread_complete);
16208    return 0;
16209 }
16210 
16211 static int unload_module(void)
16212 {
16213 #if defined(HAVE_PRI) || defined(HAVE_SS7)
16214    int y;
16215 #endif
16216 #ifdef HAVE_PRI
16217    for (y = 0; y < NUM_SPANS; y++)
16218       ast_mutex_destroy(&pris[y].lock);
16219 #endif
16220 #ifdef HAVE_SS7
16221    for (y = 0; y < NUM_SPANS; y++)
16222       ast_mutex_destroy(&linksets[y].lock);
16223 #endif /* HAVE_SS7 */
16224    return __unload_module();
16225 }
16226 
16227 static int build_channels(struct dahdi_chan_conf *conf, int iscrv, const char *value, int reload, int lineno, int *found_pseudo)
16228 {
16229    char *c, *chan;
16230    int x, start, finish;
16231    struct dahdi_pvt *tmp;
16232 #ifdef HAVE_PRI
16233    struct dahdi_pri *pri;
16234    int trunkgroup, y;
16235 #endif
16236 
16237    if ((reload == 0) && (conf->chan.sig < 0) && !conf->is_sig_auto) {
16238       ast_log(LOG_ERROR, "Signalling must be specified before any channels are.\n");
16239       return -1;
16240    }
16241 
16242    c = ast_strdupa(value);
16243 
16244 #ifdef HAVE_PRI
16245    pri = NULL;
16246    if (iscrv) {
16247       if (sscanf(c, "%30d:%n", &trunkgroup, &y) != 1) {
16248          ast_log(LOG_WARNING, "CRV must begin with trunkgroup followed by a colon at line %d.\n", lineno);
16249          return -1;
16250       }
16251       if (trunkgroup < 1) {
16252          ast_log(LOG_WARNING, "CRV trunk group must be a positive number at line %d.\n", lineno);
16253          return -1;
16254       }
16255       c += y;
16256       for (y = 0; y < NUM_SPANS; y++) {
16257          if (pris[y].trunkgroup == trunkgroup) {
16258             pri = pris + y;
16259             break;
16260          }
16261       }
16262       if (!pri) {
16263          ast_log(LOG_WARNING, "No such trunk group %d at CRV declaration at line %d.\n", trunkgroup, lineno);
16264          return -1;
16265       }
16266    }
16267 #endif
16268 
16269    while ((chan = strsep(&c, ","))) {
16270       if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
16271          /* Range */
16272       } else if (sscanf(chan, "%30d", &start)) {
16273          /* Just one */
16274          finish = start;
16275       } else if (!strcasecmp(chan, "pseudo")) {
16276          finish = start = CHAN_PSEUDO;
16277          if (found_pseudo)
16278             *found_pseudo = 1;
16279       } else {
16280          ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'\n", value, chan);
16281          return -1;
16282       }
16283       if (finish < start) {
16284          ast_log(LOG_WARNING, "Sillyness: %d < %d\n", start, finish);
16285          x = finish;
16286          finish = start;
16287          start = x;
16288       }
16289 
16290       for (x = start; x <= finish; x++) {
16291 #ifdef HAVE_PRI
16292          tmp = mkintf(x, conf, pri, reload);
16293 #else
16294          tmp = mkintf(x, conf, NULL, reload);
16295 #endif
16296 
16297          if (tmp) {
16298 #ifdef HAVE_PRI
16299             if (pri)
16300                ast_verb(3, "%s CRV %d:%d, %s signalling\n", reload ? "Reconfigured" : "Registered", trunkgroup, x, sig2str(tmp->sig));
16301             else
16302 #endif
16303                ast_verb(3, "%s channel %d, %s signalling\n", reload ? "Reconfigured" : "Registered", x, sig2str(tmp->sig));
16304          } else {
16305             ast_log(LOG_ERROR, "Unable to %s channel '%s'\n",
16306                (reload == 1) ? "reconfigure" : "register", value);
16307             return -1;
16308          }
16309       }
16310    }
16311 
16312    return 0;
16313 }
16314 
16315 /** The length of the parameters list of 'dahdichan'.
16316  * \todo Move definition of MAX_CHANLIST_LEN to a proper place. */
16317 #define MAX_CHANLIST_LEN 80
16318 
16319 static void process_echocancel(struct dahdi_chan_conf *confp, const char *data, unsigned int line)
16320 {
16321    char *parse = ast_strdupa(data);
16322    char *params[DAHDI_MAX_ECHOCANPARAMS + 1];
16323    unsigned int param_count;
16324    unsigned int x;
16325 
16326    if (!(param_count = ast_app_separate_args(parse, ',', params, ARRAY_LEN(params))))
16327       return;
16328 
16329    memset(&confp->chan.echocancel, 0, sizeof(confp->chan.echocancel));
16330 
16331    /* first parameter is tap length, process it here */
16332 
16333    x = ast_strlen_zero(params[0]) ? 0 : atoi(params[0]);
16334 
16335    if ((x == 32) || (x == 64) || (x == 128) || (x == 256) || (x == 512) || (x == 1024))
16336       confp->chan.echocancel.head.tap_length = x;
16337    else if ((confp->chan.echocancel.head.tap_length = ast_true(params[0])))
16338       confp->chan.echocancel.head.tap_length = 128;
16339 
16340    /* now process any remaining parameters */
16341 
16342    for (x = 1; x < param_count; x++) {
16343       struct {
16344          char *name;
16345          char *value;
16346       } param;
16347 
16348       if (ast_app_separate_args(params[x], '=', (char **) &param, 2) < 1) {
16349          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, params[x]);
16350          continue;
16351       }
16352 
16353       if (ast_strlen_zero(param.name) || (strlen(param.name) > sizeof(confp->chan.echocancel.params[0].name)-1)) {
16354          ast_log(LOG_WARNING, "Invalid echocancel parameter supplied at line %d: '%s'\n", line, param.name);
16355          continue;
16356       }
16357 
16358       strcpy(confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].name, param.name);
16359 
16360       if (param.value) {
16361          if (sscanf(param.value, "%30d", &confp->chan.echocancel.params[confp->chan.echocancel.head.param_count].value) != 1) {
16362             ast_log(LOG_WARNING, "Invalid echocancel parameter value supplied at line %d: '%s'\n", line, param.value);
16363             continue;
16364          }
16365       }
16366       confp->chan.echocancel.head.param_count++;
16367    }
16368 }
16369 
16370 /*! process_dahdi() - ignore keyword 'channel' and similar */
16371 #define PROC_DAHDI_OPT_NOCHAN  (1 << 0)
16372 /*! process_dahdi() - No warnings on non-existing cofiguration keywords */
16373 #define PROC_DAHDI_OPT_NOWARN  (1 << 1)
16374 
16375 static int process_dahdi(struct dahdi_chan_conf *confp, const char *cat, struct ast_variable *v, int reload, int options)
16376 {
16377    struct dahdi_pvt *tmp;
16378    int y;
16379    int found_pseudo = 0;
16380    char dahdichan[MAX_CHANLIST_LEN] = {};
16381 
16382    for (; v; v = v->next) {
16383       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
16384          continue;
16385 
16386       /* must have parkinglot in confp before build_channels is called */
16387       if (!strcasecmp(v->name, "parkinglot")) {
16388          ast_copy_string(confp->chan.parkinglot, v->value, sizeof(confp->chan.parkinglot));
16389       }
16390 
16391       /* Create the interface list */
16392       if (!strcasecmp(v->name, "channel")
16393 #ifdef HAVE_PRI
16394          || !strcasecmp(v->name, "crv")
16395 #endif
16396          ) {
16397          int iscrv;
16398          if (options & PROC_DAHDI_OPT_NOCHAN) {
16399             ast_log(LOG_WARNING, "Channel '%s' ignored.\n", v->value);
16400             continue;
16401          }
16402          iscrv = !strcasecmp(v->name, "crv");
16403          if (build_channels(confp, iscrv, v->value, reload, v->lineno, &found_pseudo))
16404                return -1;
16405          ast_log(LOG_DEBUG, "Channel '%s' configured.\n", v->value);
16406       } else if (!strcasecmp(v->name, "buffers")) {
16407          if (parse_buffers_policy(v->value, &confp->chan.buf_no, &confp->chan.buf_policy)) {
16408             ast_log(LOG_WARNING, "Using default buffer policy.\n");
16409             confp->chan.buf_no = numbufs;
16410             confp->chan.buf_policy = DAHDI_POLICY_IMMEDIATE;
16411          }
16412       } else if (!strcasecmp(v->name, "faxbuffers")) {
16413          if (!parse_buffers_policy(v->value, &confp->chan.faxbuf_no, &confp->chan.faxbuf_policy)) {
16414             confp->chan.usefaxbuffers = 1;
16415          }
16416       } else if (!strcasecmp(v->name, "dahdichan")) {
16417          ast_copy_string(dahdichan, v->value, sizeof(dahdichan));
16418       } else if (!strcasecmp(v->name, "usedistinctiveringdetection")) {
16419          usedistinctiveringdetection = ast_true(v->value);
16420       } else if (!strcasecmp(v->name, "distinctiveringaftercid")) {
16421          distinctiveringaftercid = ast_true(v->value);
16422       } else if (!strcasecmp(v->name, "dring1context")) {
16423          ast_copy_string(confp->chan.drings.ringContext[0].contextData,v->value,sizeof(confp->chan.drings.ringContext[0].contextData));
16424       } else if (!strcasecmp(v->name, "dring2context")) {
16425          ast_copy_string(confp->chan.drings.ringContext[1].contextData,v->value,sizeof(confp->chan.drings.ringContext[1].contextData));
16426       } else if (!strcasecmp(v->name, "dring3context")) {
16427          ast_copy_string(confp->chan.drings.ringContext[2].contextData,v->value,sizeof(confp->chan.drings.ringContext[2].contextData));
16428       } else if (!strcasecmp(v->name, "dring1range")) {
16429          confp->chan.drings.ringnum[0].range = atoi(v->value);
16430       } else if (!strcasecmp(v->name, "dring2range")) {
16431          confp->chan.drings.ringnum[1].range = atoi(v->value);
16432       } else if (!strcasecmp(v->name, "dring3range")) {
16433          confp->chan.drings.ringnum[2].range = atoi(v->value);
16434       } else if (!strcasecmp(v->name, "dring1")) {
16435          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]);
16436       } else if (!strcasecmp(v->name, "dring2")) {
16437          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]);
16438       } else if (!strcasecmp(v->name, "dring3")) {
16439          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]);
16440       } else if (!strcasecmp(v->name, "usecallerid")) {
16441          confp->chan.use_callerid = ast_true(v->value);
16442       } else if (!strcasecmp(v->name, "cidsignalling")) {
16443          if (!strcasecmp(v->value, "bell"))
16444             confp->chan.cid_signalling = CID_SIG_BELL;
16445          else if (!strcasecmp(v->value, "v23"))
16446             confp->chan.cid_signalling = CID_SIG_V23;
16447          else if (!strcasecmp(v->value, "dtmf"))
16448             confp->chan.cid_signalling = CID_SIG_DTMF;
16449          else if (!strcasecmp(v->value, "smdi"))
16450             confp->chan.cid_signalling = CID_SIG_SMDI;
16451          else if (!strcasecmp(v->value, "v23_jp"))
16452             confp->chan.cid_signalling = CID_SIG_V23_JP;
16453          else if (ast_true(v->value))
16454             confp->chan.cid_signalling = CID_SIG_BELL;
16455       } else if (!strcasecmp(v->name, "cidstart")) {
16456          if (!strcasecmp(v->value, "ring"))
16457             confp->chan.cid_start = CID_START_RING;
16458          else if (!strcasecmp(v->value, "polarity_in"))
16459             confp->chan.cid_start = CID_START_POLARITY_IN;
16460          else if (!strcasecmp(v->value, "polarity"))
16461             confp->chan.cid_start = CID_START_POLARITY;
16462          else if (ast_true(v->value))
16463             confp->chan.cid_start = CID_START_RING;
16464       } else if (!strcasecmp(v->name, "threewaycalling")) {
16465          confp->chan.threewaycalling = ast_true(v->value);
16466       } else if (!strcasecmp(v->name, "cancallforward")) {
16467          confp->chan.cancallforward = ast_true(v->value);
16468       } else if (!strcasecmp(v->name, "relaxdtmf")) {
16469          if (ast_true(v->value))
16470             confp->chan.dtmfrelax = DSP_DIGITMODE_RELAXDTMF;
16471          else
16472             confp->chan.dtmfrelax = 0;
16473       } else if (!strcasecmp(v->name, "mailbox")) {
16474          ast_copy_string(confp->chan.mailbox, v->value, sizeof(confp->chan.mailbox));
16475       } else if (!strcasecmp(v->name, "hasvoicemail")) {
16476          if (ast_true(v->value) && ast_strlen_zero(confp->chan.mailbox)) {
16477             ast_copy_string(confp->chan.mailbox, cat, sizeof(confp->chan.mailbox));
16478          }
16479       } else if (!strcasecmp(v->name, "adsi")) {
16480          confp->chan.adsi = ast_true(v->value);
16481       } else if (!strcasecmp(v->name, "usesmdi")) {
16482          confp->chan.use_smdi = ast_true(v->value);
16483       } else if (!strcasecmp(v->name, "smdiport")) {
16484          ast_copy_string(confp->smdi_port, v->value, sizeof(confp->smdi_port));
16485       } else if (!strcasecmp(v->name, "transfer")) {
16486          confp->chan.transfer = ast_true(v->value);
16487       } else if (!strcasecmp(v->name, "canpark")) {
16488          confp->chan.canpark = ast_true(v->value);
16489       } else if (!strcasecmp(v->name, "echocancelwhenbridged")) {
16490          confp->chan.echocanbridged = ast_true(v->value);
16491       } else if (!strcasecmp(v->name, "busydetect")) {
16492          confp->chan.busydetect = ast_true(v->value);
16493       } else if (!strcasecmp(v->name, "busycount")) {
16494          confp->chan.busycount = atoi(v->value);
16495       } else if (!strcasecmp(v->name, "busypattern")) {
16496          if (sscanf(v->value, "%30d,%30d", &confp->chan.busy_tonelength, &confp->chan.busy_quietlength) != 2) {
16497             ast_log(LOG_ERROR, "busypattern= expects busypattern=tonelength,quietlength at line %d.\n", v->lineno);
16498          }
16499       } else if (!strcasecmp(v->name, "callprogress")) {
16500          confp->chan.callprogress &= ~CALLPROGRESS_PROGRESS;
16501          if (ast_true(v->value))
16502             confp->chan.callprogress |= CALLPROGRESS_PROGRESS;
16503       } else if (!strcasecmp(v->name, "waitfordialtone")) {
16504          confp->chan.waitfordialtone = atoi(v->value);
16505       } else if (!strcasecmp(v->name, "faxdetect")) {
16506          confp->chan.callprogress &= ~CALLPROGRESS_FAX;
16507          if (!strcasecmp(v->value, "incoming")) {
16508             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING;
16509          } else if (!strcasecmp(v->value, "outgoing")) {
16510             confp->chan.callprogress |= CALLPROGRESS_FAX_OUTGOING;
16511          } else if (!strcasecmp(v->value, "both") || ast_true(v->value))
16512             confp->chan.callprogress |= CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING;
16513       } else if (!strcasecmp(v->name, "echocancel")) {
16514          process_echocancel(confp, v->value, v->lineno);
16515       } else if (!strcasecmp(v->name, "echotraining")) {
16516          if (sscanf(v->value, "%30d", &y) == 1) {
16517             if ((y < 10) || (y > 4000)) {
16518                ast_log(LOG_WARNING, "Echo training time must be within the range of 10 to 4000 ms at line %d.\n", v->lineno);
16519             } else {
16520                confp->chan.echotraining = y;
16521             }
16522          } else if (ast_true(v->value)) {
16523             confp->chan.echotraining = 400;
16524          } else
16525             confp->chan.echotraining = 0;
16526       } else if (!strcasecmp(v->name, "hidecallerid")) {
16527          confp->chan.hidecallerid = ast_true(v->value);
16528       } else if (!strcasecmp(v->name, "hidecalleridname")) {
16529          confp->chan.hidecalleridname = ast_true(v->value);
16530       } else if (!strcasecmp(v->name, "pulsedial")) {
16531          confp->chan.pulse = ast_true(v->value);
16532       } else if (!strcasecmp(v->name, "callreturn")) {
16533          confp->chan.callreturn = ast_true(v->value);
16534       } else if (!strcasecmp(v->name, "callwaiting")) {
16535          confp->chan.callwaiting = ast_true(v->value);
16536       } else if (!strcasecmp(v->name, "callwaitingcallerid")) {
16537          confp->chan.callwaitingcallerid = ast_true(v->value);
16538       } else if (!strcasecmp(v->name, "context")) {
16539          ast_copy_string(confp->chan.context, v->value, sizeof(confp->chan.context));
16540       } else if (!strcasecmp(v->name, "language")) {
16541          ast_copy_string(confp->chan.language, v->value, sizeof(confp->chan.language));
16542       } else if (!strcasecmp(v->name, "progzone")) {
16543          ast_copy_string(progzone, v->value, sizeof(progzone));
16544       } else if (!strcasecmp(v->name, "mohinterpret")
16545          ||!strcasecmp(v->name, "musiconhold") || !strcasecmp(v->name, "musicclass")) {
16546          ast_copy_string(confp->chan.mohinterpret, v->value, sizeof(confp->chan.mohinterpret));
16547       } else if (!strcasecmp(v->name, "mohsuggest")) {
16548          ast_copy_string(confp->chan.mohsuggest, v->value, sizeof(confp->chan.mohsuggest));
16549       } else if (!strcasecmp(v->name, "parkinglot")) {
16550          ast_copy_string(parkinglot, v->value, sizeof(parkinglot));
16551       } else if (!strcasecmp(v->name, "stripmsd")) {
16552          ast_log(LOG_NOTICE, "Configuration option \"%s\" has been deprecated. Please use dialplan instead\n", v->name);
16553          confp->chan.stripmsd = atoi(v->value);
16554       } else if (!strcasecmp(v->name, "jitterbuffers")) {
16555          numbufs = atoi(v->value);
16556       } else if (!strcasecmp(v->name, "group")) {
16557          confp->chan.group = ast_get_group(v->value);
16558       } else if (!strcasecmp(v->name, "callgroup")) {
16559          if (!strcasecmp(v->value, "none"))
16560             confp->chan.callgroup = 0;
16561          else
16562             confp->chan.callgroup = ast_get_group(v->value);
16563       } else if (!strcasecmp(v->name, "pickupgroup")) {
16564          if (!strcasecmp(v->value, "none"))
16565             confp->chan.pickupgroup = 0;
16566          else
16567             confp->chan.pickupgroup = ast_get_group(v->value);
16568       } else if (!strcasecmp(v->name, "setvar")) {
16569          char *varname = ast_strdupa(v->value), *varval = NULL;
16570          struct ast_variable *tmpvar;
16571          if (varname && (varval = strchr(varname, '='))) {
16572             *varval++ = '\0';
16573             if ((tmpvar = ast_variable_new(varname, varval, ""))) {
16574                tmpvar->next = confp->chan.vars;
16575                confp->chan.vars = tmpvar;
16576             }
16577          }
16578       } else if (!strcasecmp(v->name, "immediate")) {
16579          confp->chan.immediate = ast_true(v->value);
16580       } else if (!strcasecmp(v->name, "transfertobusy")) {
16581          confp->chan.transfertobusy = ast_true(v->value);
16582       } else if (!strcasecmp(v->name, "mwimonitor")) {
16583          confp->chan.mwimonitor_neon = 0;
16584          confp->chan.mwimonitor_fsk = 0;
16585          confp->chan.mwimonitor_rpas = 0;
16586          if (strcasestr(v->value, "fsk")) {
16587             confp->chan.mwimonitor_fsk = 1;
16588          }
16589          if (strcasestr(v->value, "rpas")) {
16590             confp->chan.mwimonitor_rpas = 1;
16591          }
16592          if (strcasestr(v->value, "neon")) {
16593             confp->chan.mwimonitor_neon = 1;
16594          }
16595          /* If set to true or yes, assume that simple fsk is desired */
16596          if (ast_true(v->value)) {
16597             confp->chan.mwimonitor_fsk = 1;
16598          }
16599       } else if (!strcasecmp(v->name, "cid_rxgain")) {
16600          if (sscanf(v->value, "%30f", &confp->chan.cid_rxgain) != 1) {
16601             ast_log(LOG_WARNING, "Invalid cid_rxgain: %s at line %d.\n", v->value, v->lineno);
16602          }
16603       } else if (!strcasecmp(v->name, "rxgain")) {
16604          if (sscanf(v->value, "%30f", &confp->chan.rxgain) != 1) {
16605             ast_log(LOG_WARNING, "Invalid rxgain: %s at line %d.\n", v->value, v->lineno);
16606          }
16607       } else if (!strcasecmp(v->name, "txgain")) {
16608          if (sscanf(v->value, "%30f", &confp->chan.txgain) != 1) {
16609             ast_log(LOG_WARNING, "Invalid txgain: %s at line %d.\n", v->value, v->lineno);
16610          }
16611       } else if (!strcasecmp(v->name, "tonezone")) {
16612          if (sscanf(v->value, "%30d", &confp->chan.tonezone) != 1) {
16613             ast_log(LOG_WARNING, "Invalid tonezone: %s at line %d.\n", v->value, v->lineno);
16614          }
16615       } else if (!strcasecmp(v->name, "callerid")) {
16616          if (!strcasecmp(v->value, "asreceived")) {
16617             confp->chan.cid_num[0] = '\0';
16618             confp->chan.cid_name[0] = '\0';
16619          } else {
16620             ast_callerid_split(v->value, confp->chan.cid_name, sizeof(confp->chan.cid_name), confp->chan.cid_num, sizeof(confp->chan.cid_num));
16621          }
16622       } else if (!strcasecmp(v->name, "fullname")) {
16623          ast_copy_string(confp->chan.cid_name, v->value, sizeof(confp->chan.cid_name));
16624       } else if (!strcasecmp(v->name, "cid_number")) {
16625          ast_copy_string(confp->chan.cid_num, v->value, sizeof(confp->chan.cid_num));
16626       } else if (!strcasecmp(v->name, "useincomingcalleridondahditransfer")) {
16627          confp->chan.dahditrcallerid = ast_true(v->value);
16628       } else if (!strcasecmp(v->name, "restrictcid")) {
16629          confp->chan.restrictcid = ast_true(v->value);
16630       } else if (!strcasecmp(v->name, "usecallingpres")) {
16631          confp->chan.use_callingpres = ast_true(v->value);
16632       } else if (!strcasecmp(v->name, "accountcode")) {
16633          ast_copy_string(confp->chan.accountcode, v->value, sizeof(confp->chan.accountcode));
16634       } else if (!strcasecmp(v->name, "amaflags")) {
16635          y = ast_cdr_amaflags2int(v->value);
16636          if (y < 0)
16637             ast_log(LOG_WARNING, "Invalid AMA flags: %s at line %d.\n", v->value, v->lineno);
16638          else
16639             confp->chan.amaflags = y;
16640       } else if (!strcasecmp(v->name, "polarityonanswerdelay")) {
16641          confp->chan.polarityonanswerdelay = atoi(v->value);
16642       } else if (!strcasecmp(v->name, "answeronpolarityswitch")) {
16643          confp->chan.answeronpolarityswitch = ast_true(v->value);
16644       } else if (!strcasecmp(v->name, "hanguponpolarityswitch")) {
16645          confp->chan.hanguponpolarityswitch = ast_true(v->value);
16646       } else if (!strcasecmp(v->name, "sendcalleridafter")) {
16647          confp->chan.sendcalleridafter = atoi(v->value);
16648       } else if (!strcasecmp(v->name, "mwimonitornotify")) {
16649          ast_copy_string(mwimonitornotify, v->value, sizeof(mwimonitornotify));
16650       } else if (!strcasecmp(v->name, "mwisendtype")) {
16651 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI  /* backward compatibility for older dahdi VMWI implementation */
16652          if (!strcasecmp(v->value, "rpas")) { /* Ring Pulse Alert Signal */
16653             mwisend_rpas = 1;
16654          } else {
16655             mwisend_rpas = 0;
16656          }
16657 #else
16658          /* Default is fsk, to turn it off you must specify nofsk */
16659          memset(&confp->chan.mwisend_setting, 0, sizeof(confp->chan.mwisend_setting));
16660          if (strcasestr(v->value, "nofsk")) {      /* NoFSK */
16661             confp->chan.mwisend_fsk = 0;
16662          } else {             /* Default FSK */
16663             confp->chan.mwisend_fsk = 1;
16664          }
16665          if (strcasestr(v->value, "rpas")) {       /* Ring Pulse Alert Signal, normally followed by FSK */
16666             confp->chan.mwisend_rpas = 1;
16667          } else {
16668             confp->chan.mwisend_rpas = 0;
16669          }
16670          if (strcasestr(v->value, "lrev")) {       /* Line Reversal */
16671             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_LREV;
16672          }
16673          if (strcasestr(v->value, "hvdc")) {       /* HV 90VDC */
16674             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVDC;
16675          }
16676          if ( (strcasestr(v->value, "neon")) || (strcasestr(v->value, "hvac")) ){   /* 90V DC pulses */
16677             confp->chan.mwisend_setting.vmwi_type |= DAHDI_VMWI_HVAC;
16678          }
16679 #endif
16680       } else if (reload != 1) {
16681           if (!strcasecmp(v->name, "signalling") || !strcasecmp(v->name, "signaling")) {
16682             int orig_radio = confp->chan.radio;
16683             int orig_outsigmod = confp->chan.outsigmod;
16684             int orig_auto = confp->is_sig_auto;
16685 
16686             confp->chan.radio = 0;
16687             confp->chan.outsigmod = -1;
16688             confp->is_sig_auto = 0;
16689             if (!strcasecmp(v->value, "em")) {
16690                confp->chan.sig = SIG_EM;
16691             } else if (!strcasecmp(v->value, "em_e1")) {
16692                confp->chan.sig = SIG_EM_E1;
16693             } else if (!strcasecmp(v->value, "em_w")) {
16694                confp->chan.sig = SIG_EMWINK;
16695             } else if (!strcasecmp(v->value, "fxs_ls")) {
16696                confp->chan.sig = SIG_FXSLS;
16697             } else if (!strcasecmp(v->value, "fxs_gs")) {
16698                confp->chan.sig = SIG_FXSGS;
16699             } else if (!strcasecmp(v->value, "fxs_ks")) {
16700                confp->chan.sig = SIG_FXSKS;
16701             } else if (!strcasecmp(v->value, "fxo_ls")) {
16702                confp->chan.sig = SIG_FXOLS;
16703             } else if (!strcasecmp(v->value, "fxo_gs")) {
16704                confp->chan.sig = SIG_FXOGS;
16705             } else if (!strcasecmp(v->value, "fxo_ks")) {
16706                confp->chan.sig = SIG_FXOKS;
16707             } else if (!strcasecmp(v->value, "fxs_rx")) {
16708                confp->chan.sig = SIG_FXSKS;
16709                confp->chan.radio = 1;
16710             } else if (!strcasecmp(v->value, "fxo_rx")) {
16711                confp->chan.sig = SIG_FXOLS;
16712                confp->chan.radio = 1;
16713             } else if (!strcasecmp(v->value, "fxs_tx")) {
16714                confp->chan.sig = SIG_FXSLS;
16715                confp->chan.radio = 1;
16716             } else if (!strcasecmp(v->value, "fxo_tx")) {
16717                confp->chan.sig = SIG_FXOGS;
16718                confp->chan.radio = 1;
16719             } else if (!strcasecmp(v->value, "em_rx")) {
16720                confp->chan.sig = SIG_EM;
16721                confp->chan.radio = 1;
16722             } else if (!strcasecmp(v->value, "em_tx")) {
16723                confp->chan.sig = SIG_EM;
16724                confp->chan.radio = 1;
16725             } else if (!strcasecmp(v->value, "em_rxtx")) {
16726                confp->chan.sig = SIG_EM;
16727                confp->chan.radio = 2;
16728             } else if (!strcasecmp(v->value, "em_txrx")) {
16729                confp->chan.sig = SIG_EM;
16730                confp->chan.radio = 2;
16731             } else if (!strcasecmp(v->value, "sf")) {
16732                confp->chan.sig = SIG_SF;
16733             } else if (!strcasecmp(v->value, "sf_w")) {
16734                confp->chan.sig = SIG_SFWINK;
16735             } else if (!strcasecmp(v->value, "sf_featd")) {
16736                confp->chan.sig = SIG_FEATD;
16737             } else if (!strcasecmp(v->value, "sf_featdmf")) {
16738                confp->chan.sig = SIG_FEATDMF;
16739             } else if (!strcasecmp(v->value, "sf_featb")) {
16740                confp->chan.sig = SIG_SF_FEATB;
16741             } else if (!strcasecmp(v->value, "sf")) {
16742                confp->chan.sig = SIG_SF;
16743             } else if (!strcasecmp(v->value, "sf_rx")) {
16744                confp->chan.sig = SIG_SF;
16745                confp->chan.radio = 1;
16746             } else if (!strcasecmp(v->value, "sf_tx")) {
16747                confp->chan.sig = SIG_SF;
16748                confp->chan.radio = 1;
16749             } else if (!strcasecmp(v->value, "sf_rxtx")) {
16750                confp->chan.sig = SIG_SF;
16751                confp->chan.radio = 2;
16752             } else if (!strcasecmp(v->value, "sf_txrx")) {
16753                confp->chan.sig = SIG_SF;
16754                confp->chan.radio = 2;
16755             } else if (!strcasecmp(v->value, "featd")) {
16756                confp->chan.sig = SIG_FEATD;
16757             } else if (!strcasecmp(v->value, "featdmf")) {
16758                confp->chan.sig = SIG_FEATDMF;
16759             } else if (!strcasecmp(v->value, "featdmf_ta")) {
16760                confp->chan.sig = SIG_FEATDMF_TA;
16761             } else if (!strcasecmp(v->value, "e911")) {
16762                confp->chan.sig = SIG_E911;
16763             } else if (!strcasecmp(v->value, "fgccama")) {
16764                confp->chan.sig = SIG_FGC_CAMA;
16765             } else if (!strcasecmp(v->value, "fgccamamf")) {
16766                confp->chan.sig = SIG_FGC_CAMAMF;
16767             } else if (!strcasecmp(v->value, "featb")) {
16768                confp->chan.sig = SIG_FEATB;
16769 #ifdef HAVE_PRI
16770             } else if (!strcasecmp(v->value, "pri_net")) {
16771                confp->chan.sig = SIG_PRI;
16772                confp->pri.nodetype = PRI_NETWORK;
16773             } else if (!strcasecmp(v->value, "pri_cpe")) {
16774                confp->chan.sig = SIG_PRI;
16775                confp->pri.nodetype = PRI_CPE;
16776             } else if (!strcasecmp(v->value, "bri_cpe")) {
16777                confp->chan.sig = SIG_BRI;
16778                confp->pri.nodetype = PRI_CPE;
16779             } else if (!strcasecmp(v->value, "bri_net")) {
16780                confp->chan.sig = SIG_BRI;
16781                confp->pri.nodetype = PRI_NETWORK;
16782             } else if (!strcasecmp(v->value, "bri_cpe_ptmp")) {
16783                confp->chan.sig = SIG_BRI_PTMP;
16784                confp->pri.nodetype = PRI_CPE;
16785             } else if (!strcasecmp(v->value, "bri_net_ptmp")) {
16786                ast_log(LOG_WARNING, "How cool would it be if someone implemented this mode!  For now, sucks for you. (line %d)\n", v->lineno);
16787             } else if (!strcasecmp(v->value, "gr303fxoks_net")) {
16788                confp->chan.sig = SIG_GR303FXOKS;
16789                confp->pri.nodetype = PRI_NETWORK;
16790             } else if (!strcasecmp(v->value, "gr303fxsks_cpe")) {
16791                confp->chan.sig = SIG_GR303FXSKS;
16792                confp->pri.nodetype = PRI_CPE;
16793 #endif
16794 #ifdef HAVE_SS7
16795             } else if (!strcasecmp(v->value, "ss7")) {
16796                confp->chan.sig = SIG_SS7;
16797 #endif
16798 #ifdef HAVE_OPENR2
16799             } else if (!strcasecmp(v->value, "mfcr2")) {
16800                confp->chan.sig = SIG_MFCR2;
16801 #endif
16802             } else if (!strcasecmp(v->value, "auto")) {
16803                confp->is_sig_auto = 1;
16804             } else {
16805                confp->chan.outsigmod = orig_outsigmod;
16806                confp->chan.radio = orig_radio;
16807                confp->is_sig_auto = orig_auto;
16808                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
16809             }
16810           } else if (!strcasecmp(v->name, "outsignalling") || !strcasecmp(v->name, "outsignaling")) {
16811             if (!strcasecmp(v->value, "em")) {
16812                confp->chan.outsigmod = SIG_EM;
16813             } else if (!strcasecmp(v->value, "em_e1")) {
16814                confp->chan.outsigmod = SIG_EM_E1;
16815             } else if (!strcasecmp(v->value, "em_w")) {
16816                confp->chan.outsigmod = SIG_EMWINK;
16817             } else if (!strcasecmp(v->value, "sf")) {
16818                confp->chan.outsigmod = SIG_SF;
16819             } else if (!strcasecmp(v->value, "sf_w")) {
16820                confp->chan.outsigmod = SIG_SFWINK;
16821             } else if (!strcasecmp(v->value, "sf_featd")) {
16822                confp->chan.outsigmod = SIG_FEATD;
16823             } else if (!strcasecmp(v->value, "sf_featdmf")) {
16824                confp->chan.outsigmod = SIG_FEATDMF;
16825             } else if (!strcasecmp(v->value, "sf_featb")) {
16826                confp->chan.outsigmod = SIG_SF_FEATB;
16827             } else if (!strcasecmp(v->value, "sf")) {
16828                confp->chan.outsigmod = SIG_SF;
16829             } else if (!strcasecmp(v->value, "featd")) {
16830                confp->chan.outsigmod = SIG_FEATD;
16831             } else if (!strcasecmp(v->value, "featdmf")) {
16832                confp->chan.outsigmod = SIG_FEATDMF;
16833             } else if (!strcasecmp(v->value, "featdmf_ta")) {
16834                confp->chan.outsigmod = SIG_FEATDMF_TA;
16835             } else if (!strcasecmp(v->value, "e911")) {
16836                confp->chan.outsigmod = SIG_E911;
16837             } else if (!strcasecmp(v->value, "fgccama")) {
16838                confp->chan.outsigmod = SIG_FGC_CAMA;
16839             } else if (!strcasecmp(v->value, "fgccamamf")) {
16840                confp->chan.outsigmod = SIG_FGC_CAMAMF;
16841             } else if (!strcasecmp(v->value, "featb")) {
16842                confp->chan.outsigmod = SIG_FEATB;
16843             } else {
16844                ast_log(LOG_ERROR, "Unknown signalling method '%s' at line %d.\n", v->value, v->lineno);
16845             }
16846 #ifdef HAVE_PRI
16847          } else if (!strcasecmp(v->name, "pridialplan")) {
16848             if (!strcasecmp(v->value, "national")) {
16849                confp->pri.dialplan = PRI_NATIONAL_ISDN + 1;
16850             } else if (!strcasecmp(v->value, "unknown")) {
16851                confp->pri.dialplan = PRI_UNKNOWN + 1;
16852             } else if (!strcasecmp(v->value, "private")) {
16853                confp->pri.dialplan = PRI_PRIVATE + 1;
16854             } else if (!strcasecmp(v->value, "international")) {
16855                confp->pri.dialplan = PRI_INTERNATIONAL_ISDN + 1;
16856             } else if (!strcasecmp(v->value, "local")) {
16857                confp->pri.dialplan = PRI_LOCAL_ISDN + 1;
16858             } else if (!strcasecmp(v->value, "dynamic")) {
16859                confp->pri.dialplan = -1;
16860             } else if (!strcasecmp(v->value, "redundant")) {
16861                confp->pri.dialplan = -2;
16862             } else {
16863                ast_log(LOG_WARNING, "Unknown PRI dialplan '%s' at line %d.\n", v->value, v->lineno);
16864             }
16865          } else if (!strcasecmp(v->name, "prilocaldialplan")) {
16866             if (!strcasecmp(v->value, "national")) {
16867                confp->pri.localdialplan = PRI_NATIONAL_ISDN + 1;
16868             } else if (!strcasecmp(v->value, "unknown")) {
16869                confp->pri.localdialplan = PRI_UNKNOWN + 1;
16870             } else if (!strcasecmp(v->value, "private")) {
16871                confp->pri.localdialplan = PRI_PRIVATE + 1;
16872             } else if (!strcasecmp(v->value, "international")) {
16873                confp->pri.localdialplan = PRI_INTERNATIONAL_ISDN + 1;
16874             } else if (!strcasecmp(v->value, "local")) {
16875                confp->pri.localdialplan = PRI_LOCAL_ISDN + 1;
16876             } else if (!strcasecmp(v->value, "dynamic")) {
16877                confp->pri.localdialplan = -1;
16878             } else if (!strcasecmp(v->value, "redundant")) {
16879                confp->pri.localdialplan = -2;
16880             } else {
16881                ast_log(LOG_WARNING, "Unknown PRI localdialplan '%s' at line %d.\n", v->value, v->lineno);
16882             }
16883          } else if (!strcasecmp(v->name, "switchtype")) {
16884             if (!strcasecmp(v->value, "national"))
16885                confp->pri.switchtype = PRI_SWITCH_NI2;
16886             else if (!strcasecmp(v->value, "ni1"))
16887                confp->pri.switchtype = PRI_SWITCH_NI1;
16888             else if (!strcasecmp(v->value, "dms100"))
16889                confp->pri.switchtype = PRI_SWITCH_DMS100;
16890             else if (!strcasecmp(v->value, "4ess"))
16891                confp->pri.switchtype = PRI_SWITCH_ATT4ESS;
16892             else if (!strcasecmp(v->value, "5ess"))
16893                confp->pri.switchtype = PRI_SWITCH_LUCENT5E;
16894             else if (!strcasecmp(v->value, "euroisdn"))
16895                confp->pri.switchtype = PRI_SWITCH_EUROISDN_E1;
16896             else if (!strcasecmp(v->value, "qsig"))
16897                confp->pri.switchtype = PRI_SWITCH_QSIG;
16898             else {
16899                ast_log(LOG_ERROR, "Unknown switchtype '%s' at line %d.\n", v->value, v->lineno);
16900                return -1;
16901             }
16902          } else if (!strcasecmp(v->name, "nsf")) {
16903             if (!strcasecmp(v->value, "sdn"))
16904                confp->pri.nsf = PRI_NSF_SDN;
16905             else if (!strcasecmp(v->value, "megacom"))
16906                confp->pri.nsf = PRI_NSF_MEGACOM;
16907             else if (!strcasecmp(v->value, "tollfreemegacom"))
16908                confp->pri.nsf = PRI_NSF_TOLL_FREE_MEGACOM;
16909             else if (!strcasecmp(v->value, "accunet"))
16910                confp->pri.nsf = PRI_NSF_ACCUNET;
16911             else if (!strcasecmp(v->value, "none"))
16912                confp->pri.nsf = PRI_NSF_NONE;
16913             else {
16914                ast_log(LOG_WARNING, "Unknown network-specific facility '%s' at line %d.\n", v->value, v->lineno);
16915                confp->pri.nsf = PRI_NSF_NONE;
16916             }
16917          } else if (!strcasecmp(v->name, "priindication")) {
16918             if (!strcasecmp(v->value, "outofband"))
16919                confp->chan.priindication_oob = 1;
16920             else if (!strcasecmp(v->value, "inband"))
16921                confp->chan.priindication_oob = 0;
16922             else
16923                ast_log(LOG_WARNING, "'%s' is not a valid pri indication value, should be 'inband' or 'outofband' at line %d.\n",
16924                   v->value, v->lineno);
16925          } else if (!strcasecmp(v->name, "priexclusive")) {
16926             confp->chan.priexclusive = ast_true(v->value);
16927          } else if (!strcasecmp(v->name, "internationalprefix")) {
16928             ast_copy_string(confp->pri.internationalprefix, v->value, sizeof(confp->pri.internationalprefix));
16929          } else if (!strcasecmp(v->name, "nationalprefix")) {
16930             ast_copy_string(confp->pri.nationalprefix, v->value, sizeof(confp->pri.nationalprefix));
16931          } else if (!strcasecmp(v->name, "localprefix")) {
16932             ast_copy_string(confp->pri.localprefix, v->value, sizeof(confp->pri.localprefix));
16933          } else if (!strcasecmp(v->name, "privateprefix")) {
16934             ast_copy_string(confp->pri.privateprefix, v->value, sizeof(confp->pri.privateprefix));
16935          } else if (!strcasecmp(v->name, "unknownprefix")) {
16936             ast_copy_string(confp->pri.unknownprefix, v->value, sizeof(confp->pri.unknownprefix));
16937          } else if (!strcasecmp(v->name, "resetinterval")) {
16938             if (!strcasecmp(v->value, "never"))
16939                confp->pri.resetinterval = -1;
16940             else if (atoi(v->value) >= 60)
16941                confp->pri.resetinterval = atoi(v->value);
16942             else
16943                ast_log(LOG_WARNING, "'%s' is not a valid reset interval, should be >= 60 seconds or 'never' at line %d.\n",
16944                   v->value, v->lineno);
16945          } else if (!strcasecmp(v->name, "minunused")) {
16946             confp->pri.minunused = atoi(v->value);
16947          } else if (!strcasecmp(v->name, "minidle")) {
16948             confp->pri.minidle = atoi(v->value);
16949          } else if (!strcasecmp(v->name, "idleext")) {
16950             ast_copy_string(confp->pri.idleext, v->value, sizeof(confp->pri.idleext));
16951          } else if (!strcasecmp(v->name, "idledial")) {
16952             ast_copy_string(confp->pri.idledial, v->value, sizeof(confp->pri.idledial));
16953          } else if (!strcasecmp(v->name, "overlapdial")) {
16954             if (ast_true(v->value)) {
16955                confp->pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
16956             } else if (!strcasecmp(v->value, "incoming")) {
16957                confp->pri.overlapdial = DAHDI_OVERLAPDIAL_INCOMING;
16958             } else if (!strcasecmp(v->value, "outgoing")) {
16959                confp->pri.overlapdial = DAHDI_OVERLAPDIAL_OUTGOING;
16960             } else if (!strcasecmp(v->value, "both") || ast_true(v->value)) {
16961                confp->pri.overlapdial = DAHDI_OVERLAPDIAL_BOTH;
16962             } else {
16963                confp->pri.overlapdial = DAHDI_OVERLAPDIAL_NONE;
16964             }
16965 #ifdef HAVE_PRI_PROG_W_CAUSE
16966          } else if (!strcasecmp(v->name, "qsigchannelmapping")) {
16967             if (!strcasecmp(v->value, "logical")) {
16968                confp->pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_LOGICAL;
16969             } else if (!strcasecmp(v->value, "physical")) {
16970                confp->pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
16971             } else {
16972                confp->pri.qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL;
16973             }
16974 #endif
16975          } else if (!strcasecmp(v->name, "discardremoteholdretrieval")) {
16976             confp->pri.discardremoteholdretrieval = ast_true(v->value);
16977 #ifdef HAVE_PRI_INBANDDISCONNECT
16978          } else if (!strcasecmp(v->name, "inbanddisconnect")) {
16979             confp->pri.inbanddisconnect = ast_true(v->value);
16980 #endif
16981          } else if (!strcasecmp(v->name, "pritimer")) {
16982 #ifdef PRI_GETSET_TIMERS
16983             char tmp[20];
16984             char *timerc;
16985             char *c;
16986             int timer;
16987             int timeridx;
16988 
16989             ast_copy_string(tmp, v->value, sizeof(tmp));
16990             c = tmp;
16991             timerc = strsep(&c, ",");
16992             if (!ast_strlen_zero(timerc) && !ast_strlen_zero(c)) {
16993                timeridx = pri_timer2idx(timerc);
16994                timer = atoi(c);
16995                if (timeridx < 0 || PRI_MAX_TIMERS <= timeridx) {
16996                   ast_log(LOG_WARNING,
16997                      "'%s' is not a valid ISDN timer at line %d.\n", timerc,
16998                      v->lineno);
16999                } else if (!timer) {
17000                   ast_log(LOG_WARNING,
17001                      "'%s' is not a valid value for ISDN timer '%s' at line %d.\n",
17002                      c, timerc, v->lineno);
17003                } else {
17004                   pritimers[timeridx] = timer;
17005                }
17006             } else {
17007                ast_log(LOG_WARNING,
17008                   "'%s' is not a valid ISDN timer configuration string at line %d.\n",
17009                   v->value, v->lineno);
17010             }
17011 
17012          } else if (!strcasecmp(v->name, "facilityenable")) {
17013             confp->pri.facilityenable = ast_true(v->value);
17014 #endif /* PRI_GETSET_TIMERS */
17015 #endif /* HAVE_PRI */
17016 #ifdef HAVE_SS7
17017          } else if (!strcasecmp(v->name, "ss7type")) {
17018             if (!strcasecmp(v->value, "itu")) {
17019                cur_ss7type = SS7_ITU;
17020             } else if (!strcasecmp(v->value, "ansi")) {
17021                cur_ss7type = SS7_ANSI;
17022             } else
17023                ast_log(LOG_WARNING, "'%s' is an unknown ss7 switch type at line %d.!\n", v->value, v->lineno);
17024          } else if (!strcasecmp(v->name, "linkset")) {
17025             cur_linkset = atoi(v->value);
17026          } else if (!strcasecmp(v->name, "pointcode")) {
17027             cur_pointcode = parse_pointcode(v->value);
17028          } else if (!strcasecmp(v->name, "adjpointcode")) {
17029             cur_adjpointcode = parse_pointcode(v->value);
17030          } else if (!strcasecmp(v->name, "defaultdpc")) {
17031             cur_defaultdpc = parse_pointcode(v->value);
17032          } else if (!strcasecmp(v->name, "cicbeginswith")) {
17033             cur_cicbeginswith = atoi(v->value);
17034          } else if (!strcasecmp(v->name, "networkindicator")) {
17035             if (!strcasecmp(v->value, "national"))
17036                cur_networkindicator = SS7_NI_NAT;
17037             else if (!strcasecmp(v->value, "national_spare"))
17038                cur_networkindicator = SS7_NI_NAT_SPARE;
17039             else if (!strcasecmp(v->value, "international"))
17040                cur_networkindicator = SS7_NI_INT;
17041             else if (!strcasecmp(v->value, "international_spare"))
17042                cur_networkindicator = SS7_NI_INT_SPARE;
17043             else
17044                cur_networkindicator = -1;
17045          } else if (!strcasecmp(v->name, "ss7_internationalprefix")) {
17046             ast_copy_string(confp->ss7.internationalprefix, v->value, sizeof(confp->ss7.internationalprefix));
17047          } else if (!strcasecmp(v->name, "ss7_nationalprefix")) {
17048             ast_copy_string(confp->ss7.nationalprefix, v->value, sizeof(confp->ss7.nationalprefix));
17049          } else if (!strcasecmp(v->name, "ss7_subscriberprefix")) {
17050             ast_copy_string(confp->ss7.subscriberprefix, v->value, sizeof(confp->ss7.subscriberprefix));
17051          } else if (!strcasecmp(v->name, "ss7_unknownprefix")) {
17052             ast_copy_string(confp->ss7.unknownprefix, v->value, sizeof(confp->ss7.unknownprefix));
17053          } else if (!strcasecmp(v->name, "ss7_called_nai")) {
17054             if (!strcasecmp(v->value, "national")) {
17055                confp->ss7.called_nai = SS7_NAI_NATIONAL;
17056             } else if (!strcasecmp(v->value, "international")) {
17057                confp->ss7.called_nai = SS7_NAI_INTERNATIONAL;
17058             } else if (!strcasecmp(v->value, "subscriber")) {
17059                confp->ss7.called_nai = SS7_NAI_SUBSCRIBER;
17060             } else if (!strcasecmp(v->value, "unknown")) {
17061                confp->ss7.called_nai = SS7_NAI_UNKNOWN;
17062             } else if (!strcasecmp(v->value, "dynamic")) {
17063                confp->ss7.called_nai = SS7_NAI_DYNAMIC;
17064             } else {
17065                ast_log(LOG_WARNING, "Unknown SS7 called_nai '%s' at line %d.\n", v->value, v->lineno);
17066             }
17067          } else if (!strcasecmp(v->name, "ss7_calling_nai")) {
17068             if (!strcasecmp(v->value, "national")) {
17069                confp->ss7.calling_nai = SS7_NAI_NATIONAL;
17070             } else if (!strcasecmp(v->value, "international")) {
17071                confp->ss7.calling_nai = SS7_NAI_INTERNATIONAL;
17072             } else if (!strcasecmp(v->value, "subscriber")) {
17073                confp->ss7.calling_nai = SS7_NAI_SUBSCRIBER;
17074             } else if (!strcasecmp(v->value, "unknown")) {
17075                confp->ss7.calling_nai = SS7_NAI_UNKNOWN;
17076             } else if (!strcasecmp(v->value, "dynamic")) {
17077                confp->ss7.calling_nai = SS7_NAI_DYNAMIC;
17078             } else {
17079                ast_log(LOG_WARNING, "Unknown SS7 calling_nai '%s' at line %d.\n", v->value, v->lineno);
17080             }
17081          } else if (!strcasecmp(v->name, "sigchan")) {
17082             int sigchan, res;
17083             sigchan = atoi(v->value);
17084             res = linkset_addsigchan(sigchan);
17085             if (res < 0)
17086                return -1;
17087 
17088          } else if (!strcasecmp(v->name, "ss7_explicitacm")) {
17089             struct dahdi_ss7 *link;
17090             link = ss7_resolve_linkset(cur_linkset);
17091             if (!link) {
17092                ast_log(LOG_ERROR, "Invalid linkset number.  Must be between 1 and %d\n", NUM_SPANS + 1);
17093                return -1;
17094             }
17095             if (ast_true(v->value))
17096                link->flags |= LINKSET_FLAG_EXPLICITACM;
17097 #endif /* HAVE_SS7 */
17098 #ifdef HAVE_OPENR2
17099          } else if (!strcasecmp(v->name, "mfcr2_advanced_protocol_file")) {
17100             ast_copy_string(confp->mfcr2.r2proto_file, v->value, sizeof(confp->mfcr2.r2proto_file));
17101             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);
17102          } else if (!strcasecmp(v->name, "mfcr2_logdir")) {
17103             ast_copy_string(confp->mfcr2.logdir, v->value, sizeof(confp->mfcr2.logdir));
17104          } else if (!strcasecmp(v->name, "mfcr2_variant")) {
17105             confp->mfcr2.variant = openr2_proto_get_variant(v->value);
17106             if (OR2_VAR_UNKNOWN == confp->mfcr2.variant) {
17107                ast_log(LOG_WARNING, "Unknown MFC/R2 variant '%s' at line %d, defaulting to ITU.\n", v->value, v->lineno);
17108                confp->mfcr2.variant = OR2_VAR_ITU;
17109             }
17110          } else if (!strcasecmp(v->name, "mfcr2_mfback_timeout")) {
17111             confp->mfcr2.mfback_timeout = atoi(v->value);
17112             if (!confp->mfcr2.mfback_timeout) {
17113                ast_log(LOG_WARNING, "MF timeout of 0? hum, I will protect you from your ignorance. Setting default.\n");
17114                confp->mfcr2.mfback_timeout = -1;
17115             } else if (confp->mfcr2.mfback_timeout > 0 && confp->mfcr2.mfback_timeout < 500) {
17116                ast_log(LOG_WARNING, "MF timeout less than 500ms is not recommended, you have been warned!\n");
17117             }
17118          } else if (!strcasecmp(v->name, "mfcr2_metering_pulse_timeout")) {
17119             confp->mfcr2.metering_pulse_timeout = atoi(v->value);
17120             if (confp->mfcr2.metering_pulse_timeout > 500) {
17121                ast_log(LOG_WARNING, "Metering pulse timeout greater than 500ms is not recommended, you have been warned!\n");
17122             }
17123          } else if (!strcasecmp(v->name, "mfcr2_get_ani_first")) {
17124             confp->mfcr2.get_ani_first = ast_true(v->value) ? 1 : 0;
17125          } else if (!strcasecmp(v->name, "mfcr2_double_answer")) {
17126             confp->mfcr2.double_answer = ast_true(v->value) ? 1 : 0;
17127          } else if (!strcasecmp(v->name, "mfcr2_charge_calls")) {
17128             confp->mfcr2.charge_calls = ast_true(v->value) ? 1 : 0;
17129          } else if (!strcasecmp(v->name, "mfcr2_accept_on_offer")) {
17130             confp->mfcr2.accept_on_offer = ast_true(v->value) ? 1 : 0;
17131          } else if (!strcasecmp(v->name, "mfcr2_allow_collect_calls")) {
17132             confp->mfcr2.allow_collect_calls = ast_true(v->value) ? 1 : 0;
17133          } else if (!strcasecmp(v->name, "mfcr2_forced_release")) {
17134             confp->mfcr2.forced_release = ast_true(v->value) ? 1 : 0;
17135          } else if (!strcasecmp(v->name, "mfcr2_immediate_accept")) {
17136             confp->mfcr2.immediate_accept = ast_true(v->value) ? 1 : 0;
17137 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
17138          } else if (!strcasecmp(v->name, "mfcr2_skip_category")) {
17139             confp->mfcr2.skip_category_request = ast_true(v->value) ? 1 : 0;
17140 #endif
17141          } else if (!strcasecmp(v->name, "mfcr2_call_files")) {
17142             confp->mfcr2.call_files = ast_true(v->value) ? 1 : 0;
17143          } else if (!strcasecmp(v->name, "mfcr2_max_ani")) {
17144             confp->mfcr2.max_ani = atoi(v->value);
17145             if (confp->mfcr2.max_ani >= AST_MAX_EXTENSION){
17146                confp->mfcr2.max_ani = AST_MAX_EXTENSION - 1;
17147             }
17148          } else if (!strcasecmp(v->name, "mfcr2_max_dnis")) {
17149             confp->mfcr2.max_dnis = atoi(v->value);
17150             if (confp->mfcr2.max_dnis >= AST_MAX_EXTENSION){
17151                confp->mfcr2.max_dnis = AST_MAX_EXTENSION - 1;
17152             }
17153          } else if (!strcasecmp(v->name, "mfcr2_category")) {
17154             confp->mfcr2.category = openr2_proto_get_category(v->value);
17155             if (OR2_CALLING_PARTY_CATEGORY_UNKNOWN == confp->mfcr2.category) {
17156                confp->mfcr2.category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER;
17157                ast_log(LOG_WARNING, "Invalid MFC/R2 caller category '%s' at line %d. Using national subscriber as default.\n",
17158                      v->value, v->lineno);
17159             }
17160          } else if (!strcasecmp(v->name, "mfcr2_logging")) {
17161             openr2_log_level_t tmplevel;
17162             char *clevel;
17163             char *logval = ast_strdupa(v->value);
17164             while (logval) {
17165                clevel = strsep(&logval,",");
17166                if (-1 == (tmplevel = openr2_log_get_level(clevel))) {
17167                   ast_log(LOG_WARNING, "Ignoring invalid logging level: '%s' at line %d.\n", clevel, v->lineno);
17168                   continue;
17169                }
17170                confp->mfcr2.loglevel |= tmplevel;
17171             }
17172 #endif /* HAVE_OPENR2 */
17173          } else if (!strcasecmp(v->name, "cadence")) {
17174             /* setup to scan our argument */
17175             int element_count, c[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
17176             int i;
17177             struct dahdi_ring_cadence new_cadence;
17178             int cid_location = -1;
17179             int firstcadencepos = 0;
17180             char original_args[80];
17181             int cadence_is_ok = 1;
17182 
17183             ast_copy_string(original_args, v->value, sizeof(original_args));
17184             /* 16 cadences allowed (8 pairs) */
17185             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]);
17186 
17187             /* Cadence must be even (on/off) */
17188             if (element_count % 2 == 1) {
17189                ast_log(LOG_ERROR, "Must be a silence duration for each ring duration: %s at line %d.\n", original_args, v->lineno);
17190                cadence_is_ok = 0;
17191             }
17192 
17193             /* Ring cadences cannot be negative */
17194             for (i = 0; i < element_count; i++) {
17195                if (c[i] == 0) {
17196                   ast_log(LOG_ERROR, "Ring or silence duration cannot be zero: %s at line %d.\n", original_args, v->lineno);
17197                   cadence_is_ok = 0;
17198                   break;
17199                } else if (c[i] < 0) {
17200                   if (i % 2 == 1) {
17201                      /* Silence duration, negative possibly okay */
17202                      if (cid_location == -1) {
17203                         cid_location = i;
17204                         c[i] *= -1;
17205                      } else {
17206                         ast_log(LOG_ERROR, "CID location specified twice: %s at line %d.\n", original_args, v->lineno);
17207                         cadence_is_ok = 0;
17208                         break;
17209                      }
17210                   } else {
17211                      if (firstcadencepos == 0) {
17212                         firstcadencepos = i; /* only recorded to avoid duplicate specification */
17213                                  /* duration will be passed negative to the DAHDI driver */
17214                      } else {
17215                          ast_log(LOG_ERROR, "First cadence position specified twice: %s at line %d.\n", original_args, v->lineno);
17216                         cadence_is_ok = 0;
17217                         break;
17218                      }
17219                   }
17220                }
17221             }
17222 
17223             /* Substitute our scanned cadence */
17224             for (i = 0; i < 16; i++) {
17225                new_cadence.ringcadence[i] = c[i];
17226             }
17227 
17228             if (cadence_is_ok) {
17229                /* ---we scanned it without getting annoyed; now some sanity checks--- */
17230                if (element_count < 2) {
17231                   ast_log(LOG_ERROR, "Minimum cadence is ring,pause: %s at line %d.\n", original_args, v->lineno);
17232                } else {
17233                   if (cid_location == -1) {
17234                      /* user didn't say; default to first pause */
17235                      cid_location = 1;
17236                   } else {
17237                      /* convert element_index to cidrings value */
17238                      cid_location = (cid_location + 1) / 2;
17239                   }
17240                   /* ---we like their cadence; try to install it--- */
17241                   if (!user_has_defined_cadences++)
17242                      /* this is the first user-defined cadence; clear the default user cadences */
17243                      num_cadence = 0;
17244                   if ((num_cadence+1) >= NUM_CADENCE_MAX)
17245                      ast_log(LOG_ERROR, "Already %d cadences; can't add another: %s at line %d.\n", NUM_CADENCE_MAX, original_args, v->lineno);
17246                   else {
17247                      cadences[num_cadence] = new_cadence;
17248                      cidrings[num_cadence++] = cid_location;
17249                      ast_verb(3, "cadence 'r%d' added: %s\n",num_cadence,original_args);
17250                   }
17251                }
17252             }
17253          } else if (!strcasecmp(v->name, "ringtimeout")) {
17254             ringt_base = (atoi(v->value) * 8) / READ_SIZE;
17255          } else if (!strcasecmp(v->name, "prewink")) {
17256             confp->timing.prewinktime = atoi(v->value);
17257          } else if (!strcasecmp(v->name, "preflash")) {
17258             confp->timing.preflashtime = atoi(v->value);
17259          } else if (!strcasecmp(v->name, "wink")) {
17260             confp->timing.winktime = atoi(v->value);
17261          } else if (!strcasecmp(v->name, "flash")) {
17262             confp->timing.flashtime = atoi(v->value);
17263          } else if (!strcasecmp(v->name, "start")) {
17264             confp->timing.starttime = atoi(v->value);
17265          } else if (!strcasecmp(v->name, "rxwink")) {
17266             confp->timing.rxwinktime = atoi(v->value);
17267          } else if (!strcasecmp(v->name, "rxflash")) {
17268             confp->timing.rxflashtime = atoi(v->value);
17269          } else if (!strcasecmp(v->name, "debounce")) {
17270             confp->timing.debouncetime = atoi(v->value);
17271          } else if (!strcasecmp(v->name, "toneduration")) {
17272             int toneduration;
17273             int ctlfd;
17274             int res;
17275             struct dahdi_dialparams dps;
17276 
17277             ctlfd = open("/dev/dahdi/ctl", O_RDWR);
17278             if (ctlfd == -1) {
17279                ast_log(LOG_ERROR, "Unable to open /dev/dahdi/ctl to set toneduration at line %d.\n", v->lineno);
17280                return -1;
17281             }
17282 
17283             toneduration = atoi(v->value);
17284             if (toneduration > -1) {
17285                memset(&dps, 0, sizeof(dps));
17286 
17287                dps.dtmf_tonelen = dps.mfv1_tonelen = toneduration;
17288                res = ioctl(ctlfd, DAHDI_SET_DIALPARAMS, &dps);
17289                if (res < 0) {
17290                   ast_log(LOG_ERROR, "Invalid tone duration: %d ms at line %d: %s\n", toneduration, v->lineno, strerror(errno));
17291                   close(ctlfd);
17292                   return -1;
17293                }
17294             }
17295             close(ctlfd);
17296          } else if (!strcasecmp(v->name, "defaultcic")) {
17297             ast_copy_string(defaultcic, v->value, sizeof(defaultcic));
17298          } else if (!strcasecmp(v->name, "defaultozz")) {
17299             ast_copy_string(defaultozz, v->value, sizeof(defaultozz));
17300          } else if (!strcasecmp(v->name, "mwilevel")) {
17301             mwilevel = atoi(v->value);
17302          }
17303       } else if (!(options & PROC_DAHDI_OPT_NOWARN) )
17304          ast_log(LOG_WARNING, "Ignoring any changes to '%s' (on reload) at line %d.\n", v->name, v->lineno);
17305    }
17306    if (dahdichan[0]) {
17307       /* The user has set 'dahdichan' */
17308       /*< \todo pass proper line number instead of 0 */
17309       if (build_channels(confp, 0, dahdichan, reload, 0, &found_pseudo)) {
17310          return -1;
17311       }
17312    }
17313    /*< \todo why check for the pseudo in the per-channel section.
17314     * Any actual use for manual setup of the pseudo channel? */
17315    if (!found_pseudo && reload != 1) {
17316       /* use the default configuration for a channel, so
17317          that any settings from real configured channels
17318          don't "leak" into the pseudo channel config
17319       */
17320       struct dahdi_chan_conf conf = dahdi_chan_conf_default();
17321 
17322       tmp = mkintf(CHAN_PSEUDO, &conf, NULL, reload);
17323 
17324       if (tmp) {
17325          ast_verb(3, "Automatically generated pseudo channel\n");
17326       } else {
17327          ast_log(LOG_WARNING, "Unable to register pseudo channel!\n");
17328       }
17329    }
17330    return 0;
17331 }
17332 
17333 static int setup_dahdi(int reload)
17334 {
17335    struct ast_config *cfg, *ucfg;
17336    struct ast_variable *v;
17337    struct dahdi_chan_conf base_conf = dahdi_chan_conf_default();
17338    struct dahdi_chan_conf conf;
17339    struct ast_flags config_flags = { reload == 1 ? CONFIG_FLAG_FILEUNCHANGED : 0 };
17340    const char *cat;
17341    int res;
17342 
17343 #ifdef HAVE_PRI
17344    char *c;
17345    int spanno;
17346    int i;
17347    int logicalspan;
17348    int trunkgroup;
17349    int dchannels[NUM_DCHANS];
17350 #endif
17351 
17352    cfg = ast_config_load(config, config_flags);
17353 
17354    /* Error if we have no config file */
17355    if (!cfg) {
17356       ast_log(LOG_ERROR, "Unable to load config %s\n", config);
17357       return 0;
17358    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
17359       ucfg = ast_config_load("users.conf", config_flags);
17360       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
17361          return 0;
17362       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
17363          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
17364          return 0;
17365       }
17366       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
17367       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
17368          ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
17369          ast_config_destroy(ucfg);
17370          return 0;
17371       }
17372    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
17373       ast_log(LOG_ERROR, "File %s cannot be parsed.  Aborting.\n", config);
17374       return 0;
17375    } else {
17376       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
17377       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
17378          ast_log(LOG_ERROR, "File users.conf cannot be parsed.  Aborting.\n");
17379          ast_config_destroy(cfg);
17380          return 0;
17381       }
17382    }
17383 
17384    /* It's a little silly to lock it, but we mind as well just to be sure */
17385    ast_mutex_lock(&iflock);
17386 #ifdef HAVE_PRI
17387    if (reload != 1) {
17388       /* Process trunkgroups first */
17389       v = ast_variable_browse(cfg, "trunkgroups");
17390       while (v) {
17391          if (!strcasecmp(v->name, "trunkgroup")) {
17392             trunkgroup = atoi(v->value);
17393             if (trunkgroup > 0) {
17394                if ((c = strchr(v->value, ','))) {
17395                   i = 0;
17396                   memset(dchannels, 0, sizeof(dchannels));
17397                   while (c && (i < NUM_DCHANS)) {
17398                      dchannels[i] = atoi(c + 1);
17399                      if (dchannels[i] < 0) {
17400                         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);
17401                      } else
17402                         i++;
17403                      c = strchr(c + 1, ',');
17404                   }
17405                   if (i) {
17406                      if (pri_create_trunkgroup(trunkgroup, dchannels)) {
17407                         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);
17408                   } else
17409                         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");
17410                   } else
17411                      ast_log(LOG_WARNING, "Trunk group %d lacks any valid D-channels at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
17412                } else
17413                   ast_log(LOG_WARNING, "Trunk group %d lacks a primary D-channel at line %d of chan_dahdi.conf\n", trunkgroup, v->lineno);
17414             } else
17415                ast_log(LOG_WARNING, "Trunk group identifier must be a positive integer at line %d of chan_dahdi.conf\n", v->lineno);
17416          } else if (!strcasecmp(v->name, "spanmap")) {
17417             spanno = atoi(v->value);
17418             if (spanno > 0) {
17419                if ((c = strchr(v->value, ','))) {
17420                   trunkgroup = atoi(c + 1);
17421                   if (trunkgroup > 0) {
17422                      if ((c = strchr(c + 1, ',')))
17423                         logicalspan = atoi(c + 1);
17424                      else
17425                         logicalspan = 0;
17426                      if (logicalspan >= 0) {
17427                         if (pri_create_spanmap(spanno - 1, trunkgroup, logicalspan)) {
17428                            ast_log(LOG_WARNING, "Failed to map span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
17429                      } else
17430                            ast_verb(2, "Mapped span %d to trunk group %d (logical span %d)\n", spanno, trunkgroup, logicalspan);
17431                      } else
17432                         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);
17433                   } else
17434                      ast_log(LOG_WARNING, "Trunk group must be a postive number at line %d of chan_dahdi.conf\n", v->lineno);
17435                } else
17436                   ast_log(LOG_WARNING, "Missing trunk group for span map at line %d of chan_dahdi.conf\n", v->lineno);
17437             } else
17438                ast_log(LOG_WARNING, "Span number must be a postive integer at line %d of chan_dahdi.conf\n", v->lineno);
17439          } else {
17440             ast_log(LOG_NOTICE, "Ignoring unknown keyword '%s' in trunkgroups\n", v->name);
17441          }
17442          v = v->next;
17443       }
17444    }
17445 #endif
17446 
17447    /* Copy the default jb config over global_jbconf */
17448    memcpy(&global_jbconf, &default_jbconf, sizeof(global_jbconf));
17449 
17450    mwimonitornotify[0] = '\0';
17451 
17452    v = ast_variable_browse(cfg, "channels");
17453    if ((res = process_dahdi(&base_conf, "", v, reload, 0))) {
17454       ast_mutex_unlock(&iflock);
17455       ast_config_destroy(cfg);
17456       if (ucfg) {
17457          ast_config_destroy(ucfg);
17458       }
17459       return res;
17460    }
17461 
17462    /* Now get configuration from all normal sections in chan_dahdi.conf: */
17463    for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
17464       /* [channels] and [trunkgroups] are used. Let's also reserve
17465        * [globals] and [general] for future use
17466        */
17467       if (!strcasecmp(cat, "general") ||
17468          !strcasecmp(cat, "trunkgroups") ||
17469          !strcasecmp(cat, "globals") ||
17470          !strcasecmp(cat, "channels")) {
17471          continue;
17472       }
17473 
17474       memcpy(&conf, &base_conf, sizeof(conf));
17475 
17476       if ((res = process_dahdi(&conf, cat, ast_variable_browse(cfg, cat), reload, PROC_DAHDI_OPT_NOCHAN))) {
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 
17486    ast_config_destroy(cfg);
17487 
17488    if (ucfg) {
17489       const char *chans;
17490 
17491       process_dahdi(&base_conf, "", ast_variable_browse(ucfg, "general"), 1, 0);
17492 
17493       for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
17494          if (!strcasecmp(cat, "general")) {
17495             continue;
17496          }
17497 
17498          chans = ast_variable_retrieve(ucfg, cat, "dahdichan");
17499 
17500          if (ast_strlen_zero(chans)) {
17501             continue;
17502          }
17503 
17504          memcpy(&conf, &base_conf, sizeof(conf));
17505 
17506          if ((res = process_dahdi(&conf, cat, ast_variable_browse(ucfg, cat), reload, PROC_DAHDI_OPT_NOCHAN | PROC_DAHDI_OPT_NOWARN))) {
17507             ast_config_destroy(ucfg);
17508             ast_mutex_unlock(&iflock);
17509             return res;
17510          }
17511       }
17512       ast_config_destroy(ucfg);
17513    }
17514    ast_mutex_unlock(&iflock);
17515 
17516 #ifdef HAVE_PRI
17517    if (reload != 1) {
17518       int x;
17519       for (x = 0; x < NUM_SPANS; x++) {
17520          if (pris[x].pvts[0]) {
17521             if (start_pri(pris + x)) {
17522                ast_log(LOG_ERROR, "Unable to start D-channel on span %d\n", x + 1);
17523                return -1;
17524             } else
17525                ast_verb(2, "Starting D-Channel on span %d\n", x + 1);
17526          }
17527       }
17528    }
17529 #endif
17530 #ifdef HAVE_SS7
17531    if (reload != 1) {
17532       int x;
17533       for (x = 0; x < NUM_SPANS; x++) {
17534          if (linksets[x].ss7) {
17535             if (ast_pthread_create(&linksets[x].master, NULL, ss7_linkset, &linksets[x])) {
17536                ast_log(LOG_ERROR, "Unable to start SS7 linkset on span %d\n", x + 1);
17537                return -1;
17538             } else
17539                ast_verb(2, "Starting SS7 linkset on span %d\n", x + 1);
17540          }
17541       }
17542    }
17543 #endif
17544 #ifdef HAVE_OPENR2
17545    if (reload != 1) {
17546       int x;
17547       for (x = 0; x < r2links_count; x++) {
17548          if (ast_pthread_create(&r2links[x]->r2master, NULL, mfcr2_monitor, r2links[x])) {
17549             ast_log(LOG_ERROR, "Unable to start R2 monitor on channel group %d\n", x + 1);
17550             return -1;
17551          } else {
17552             ast_verb(2, "Starting R2 monitor on channel group %d\n", x + 1);
17553          }
17554       }
17555    }
17556 #endif
17557    /* And start the monitor for the first time */
17558    restart_monitor();
17559    return 0;
17560 }
17561 
17562 static int load_module(void)
17563 {
17564    int res;
17565 #if defined(HAVE_PRI) || defined(HAVE_SS7)
17566    int y, i;
17567 #endif
17568 
17569 #ifdef HAVE_PRI
17570    memset(pris, 0, sizeof(pris));
17571    for (y = 0; y < NUM_SPANS; y++) {
17572       ast_mutex_init(&pris[y].lock);
17573       pris[y].offset = -1;
17574       pris[y].master = AST_PTHREADT_NULL;
17575       for (i = 0; i < NUM_DCHANS; i++)
17576          pris[y].fds[i] = -1;
17577    }
17578    pri_set_error(dahdi_pri_error);
17579    pri_set_message(dahdi_pri_message);
17580    ast_register_application_xml(dahdi_send_keypad_facility_app, dahdi_send_keypad_facility_exec);
17581 #ifdef HAVE_PRI_PROG_W_CAUSE
17582    ast_register_application_xml(dahdi_send_callrerouting_facility_app, dahdi_send_callrerouting_facility_exec);
17583 #endif
17584 #endif
17585 #ifdef HAVE_SS7
17586    memset(linksets, 0, sizeof(linksets));
17587    for (y = 0; y < NUM_SPANS; y++) {
17588       ast_mutex_init(&linksets[y].lock);
17589       linksets[y].master = AST_PTHREADT_NULL;
17590       for (i = 0; i < NUM_DCHANS; i++)
17591          linksets[y].fds[i] = -1;
17592    }
17593    ss7_set_error(dahdi_ss7_error);
17594    ss7_set_message(dahdi_ss7_message);
17595 #endif /* HAVE_SS7 */
17596    res = setup_dahdi(0);
17597    /* Make sure we can register our DAHDI channel type */
17598    if (res)
17599       return AST_MODULE_LOAD_DECLINE;
17600    if (ast_channel_register(&dahdi_tech)) {
17601       ast_log(LOG_ERROR, "Unable to register channel class 'DAHDI'\n");
17602       __unload_module();
17603       return AST_MODULE_LOAD_FAILURE;
17604    }
17605 #ifdef HAVE_PRI
17606    ast_string_field_init(&inuse, 16);
17607    ast_string_field_set(&inuse, name, "GR-303InUse");
17608    ast_cli_register_multiple(dahdi_pri_cli, ARRAY_LEN(dahdi_pri_cli));
17609 #endif
17610 #ifdef HAVE_SS7
17611    ast_cli_register_multiple(dahdi_ss7_cli, ARRAY_LEN(dahdi_ss7_cli));
17612 #endif
17613 #ifdef HAVE_OPENR2
17614    ast_cli_register_multiple(dahdi_mfcr2_cli, sizeof(dahdi_mfcr2_cli)/sizeof(dahdi_mfcr2_cli[0]));
17615    ast_register_application_xml(dahdi_accept_r2_call_app, dahdi_accept_r2_call_exec);
17616 #endif
17617 
17618    ast_cli_register_multiple(dahdi_cli, ARRAY_LEN(dahdi_cli));
17619 
17620    memset(round_robin, 0, sizeof(round_robin));
17621    ast_manager_register( "DAHDITransfer", 0, action_transfer, "Transfer DAHDI Channel" );
17622    ast_manager_register( "DAHDIHangup", 0, action_transferhangup, "Hangup DAHDI Channel" );
17623    ast_manager_register( "DAHDIDialOffhook", 0, action_dahdidialoffhook, "Dial over DAHDI channel while offhook" );
17624    ast_manager_register( "DAHDIDNDon", 0, action_dahdidndon, "Toggle DAHDI channel Do Not Disturb status ON" );
17625    ast_manager_register( "DAHDIDNDoff", 0, action_dahdidndoff, "Toggle DAHDI channel Do Not Disturb status OFF" );
17626    ast_manager_register("DAHDIShowChannels", 0, action_dahdishowchannels, "Show status DAHDI channels");
17627    ast_manager_register("DAHDIRestart", 0, action_dahdirestart, "Fully Restart DAHDI channels (terminates calls)");
17628 
17629    ast_cond_init(&ss_thread_complete, NULL);
17630 
17631    return res;
17632 }
17633 
17634 static int dahdi_sendtext(struct ast_channel *c, const char *text)
17635 {
17636 #define  END_SILENCE_LEN 400
17637 #define  HEADER_MS 50
17638 #define  TRAILER_MS 5
17639 #define  HEADER_LEN ((HEADER_MS + TRAILER_MS) * 8)
17640 #define  ASCII_BYTES_PER_CHAR 80
17641 
17642    unsigned char *buf,*mybuf;
17643    struct dahdi_pvt *p = c->tech_pvt;
17644    struct pollfd fds[1];
17645    int size,res,fd,len,x;
17646    int bytes=0;
17647    /* Initial carrier (imaginary) */
17648    float cr = 1.0;
17649    float ci = 0.0;
17650    float scont = 0.0;
17651    int idx;
17652 
17653    idx = dahdi_get_index(c, p, 0);
17654    if (idx < 0) {
17655       ast_log(LOG_WARNING, "Huh?  I don't exist?\n");
17656       return -1;
17657    }
17658    if (!text[0]) return(0); /* if nothing to send, dont */
17659    if ((!p->tdd) && (!p->mate)) return(0);  /* if not in TDD mode, just return */
17660    if (p->mate)
17661       buf = ast_malloc(((strlen(text) + 1) * ASCII_BYTES_PER_CHAR) + END_SILENCE_LEN + HEADER_LEN);
17662    else
17663       buf = ast_malloc(((strlen(text) + 1) * TDD_BYTES_PER_CHAR) + END_SILENCE_LEN);
17664    if (!buf)
17665       return -1;
17666    mybuf = buf;
17667    if (p->mate) {
17668       int codec = AST_LAW(p);
17669       for (x = 0; x < HEADER_MS; x++) {   /* 50 ms of Mark */
17670          PUT_CLID_MARKMS;
17671       }
17672       /* Put actual message */
17673       for (x = 0; text[x]; x++) {
17674          PUT_CLID(text[x]);
17675       }
17676       for (x = 0; x < TRAILER_MS; x++) {  /* 5 ms of Mark */
17677          PUT_CLID_MARKMS;
17678       }
17679       len = bytes;
17680       buf = mybuf;
17681    } else {
17682       len = tdd_generate(p->tdd, buf, text);
17683       if (len < 1) {
17684          ast_log(LOG_ERROR, "TDD generate (len %d) failed!!\n", (int)strlen(text));
17685          ast_free(mybuf);
17686          return -1;
17687       }
17688    }
17689    memset(buf + len, 0x7f, END_SILENCE_LEN);
17690    len += END_SILENCE_LEN;
17691    fd = p->subs[idx].dfd;
17692    while (len) {
17693       if (ast_check_hangup(c)) {
17694          ast_free(mybuf);
17695          return -1;
17696       }
17697       size = len;
17698       if (size > READ_SIZE)
17699          size = READ_SIZE;
17700       fds[0].fd = fd;
17701       fds[0].events = POLLOUT | POLLPRI;
17702       fds[0].revents = 0;
17703       res = poll(fds, 1, -1);
17704       if (!res) {
17705          ast_debug(1, "poll (for write) ret. 0 on channel %d\n", p->channel);
17706          continue;
17707       }
17708       /* if got exception */
17709       if (fds[0].revents & POLLPRI) {
17710          ast_free(mybuf);
17711          return -1;
17712       }
17713       if (!(fds[0].revents & POLLOUT)) {
17714          ast_debug(1, "write fd not ready on channel %d\n", p->channel);
17715          continue;
17716       }
17717       res = write(fd, buf, size);
17718       if (res != size) {
17719          if (res == -1) {
17720             ast_free(mybuf);
17721             return -1;
17722          }
17723          ast_debug(1, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
17724          break;
17725       }
17726       len -= size;
17727       buf += size;
17728    }
17729    ast_free(mybuf);
17730    return(0);
17731 }
17732 
17733 
17734 static int reload(void)
17735 {
17736    int res = 0;
17737 
17738    res = setup_dahdi(1);
17739    if (res) {
17740       ast_log(LOG_WARNING, "Reload of chan_dahdi.so is unsuccessful!\n");
17741       return -1;
17742    }
17743    return 0;
17744 }
17745 
17746 /* This is a workaround so that menuselect displays a proper description
17747  * AST_MODULE_INFO(, , "DAHDI Telephony"
17748  */
17749 
17750 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
17751    .load = load_module,
17752    .unload = unload_module,
17753    .reload = reload,
17754    );

Generated on Sat Mar 26 11:07:49 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9