Codename Pineapple

Home page | Mailing list | Docs

Last updated: Sat Feb 3 05:00:42 2007

Asterisk developer's documentation :: Codename Pineapple


chan_zap.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 Zaptel Pseudo TDM interface 
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  * 
00025  * Connects to the zaptel 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 zaptel channel.
00031  *
00032  * \par See also
00033  * \arg \ref Config_zap
00034  *
00035  * \ingroup channel_drivers
00036  *
00037  * \todo Deprecate the "musiconhold" configuration option post 1.4
00038  */
00039 
00040 /*** MODULEINFO
00041    <depend>zaptel_vldtmf</depend>
00042    <depend>zaptel</depend>
00043    <depend>tonezone</depend>
00044    <use>pri</use>
00045    <use>ss7</use>
00046  ***/
00047 
00048 #include "asterisk.h"
00049 
00050 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 51806 $")
00051 
00052 #include <stdio.h>
00053 #include <string.h>
00054 #ifdef __NetBSD__
00055 #include <pthread.h>
00056 #include <signal.h>
00057 #else
00058 #include <sys/signal.h>
00059 #endif
00060 #include <errno.h>
00061 #include <stdlib.h>
00062 #if !defined(SOLARIS) && !defined(__FreeBSD__)
00063 #include <stdint.h>
00064 #endif
00065 #include <unistd.h>
00066 #include <sys/ioctl.h>
00067 #include <math.h>
00068 #include <ctype.h>
00069 #include "asterisk/zapata.h"
00070 
00071 #ifdef HAVE_PRI
00072 #include <libpri.h>
00073 #endif
00074 
00075 #ifdef HAVE_SS7
00076 #include <libss7.h>
00077 #endif
00078 
00079 #include "asterisk/lock.h"
00080 #include "asterisk/channel.h"
00081 #include "asterisk/config.h"
00082 #include "asterisk/logger.h"
00083 #include "asterisk/module.h"
00084 #include "asterisk/pbx.h"
00085 #include "asterisk/options.h"
00086 #include "asterisk/file.h"
00087 #include "asterisk/ulaw.h"
00088 #include "asterisk/alaw.h"
00089 #include "asterisk/callerid.h"
00090 #include "asterisk/adsi.h"
00091 #include "asterisk/cli.h"
00092 #include "asterisk/cdr.h"
00093 #include "asterisk/features.h"
00094 #include "asterisk/musiconhold.h"
00095 #include "asterisk/say.h"
00096 #include "asterisk/tdd.h"
00097 #include "asterisk/app.h"
00098 #include "asterisk/dsp.h"
00099 #include "asterisk/astdb.h"
00100 #include "asterisk/manager.h"
00101 #include "asterisk/causes.h"
00102 #include "asterisk/term.h"
00103 #include "asterisk/utils.h"
00104 #include "asterisk/transcap.h"
00105 #include "asterisk/stringfields.h"
00106 #include "asterisk/abstract_jb.h"
00107 #include "asterisk/smdi.h"
00108 #include "asterisk/astobj.h"
00109 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
00110 
00111 /*! Global jitterbuffer configuration - by default, jb is disabled */
00112 static struct ast_jb_conf default_jbconf =
00113 {
00114    .flags = 0,
00115    .max_size = -1,
00116    .resync_threshold = -1,
00117    .impl = ""
00118 };
00119 static struct ast_jb_conf global_jbconf;
00120 
00121 #if !defined(ZT_SIG_EM_E1) || (defined(HAVE_PRI) && !defined(ZT_SIG_HARDHDLC))
00122 #error "Your zaptel is too old.  Please update"
00123 #endif
00124 
00125 #ifndef ZT_TONEDETECT
00126 /* Work around older code with no tone detect */
00127 #define ZT_EVENT_DTMFDOWN 0
00128 #define ZT_EVENT_DTMFUP 0
00129 #endif
00130 
00131 /* define this to send PRI user-user information elements */
00132 #undef SUPPORT_USERUSER
00133 
00134 /*! 
00135  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
00136  * the user hangs up to reset the state machine so ring works properly.
00137  * This is used to be able to support kewlstart by putting the zhone in
00138  * groundstart mode since their forward disconnect supervision is entirely
00139  * broken even though their documentation says it isn't and their support
00140  * is entirely unwilling to provide any assistance with their channel banks
00141  * even though their web site says they support their products for life.
00142  */
00143 /* #define ZHONE_HACK */
00144 
00145 /*! \note
00146  * Define if you want to check the hook state for an FXO (FXS signalled) interface
00147  * before dialing on it.  Certain FXO interfaces always think they're out of
00148  * service with this method however.
00149  */
00150 /* #define ZAP_CHECK_HOOKSTATE */
00151 
00152 /*! \brief Typically, how many rings before we should send Caller*ID */
00153 #define DEFAULT_CIDRINGS 1
00154 
00155 #define CHANNEL_PSEUDO -12
00156 
00157 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
00158 
00159 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
00160 #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)) 
00161 
00162 static const char tdesc[] = "Zapata Telephony Driver"
00163 #ifdef HAVE_PRI
00164                " w/PRI"
00165 #endif
00166 #ifdef HAVEL_LIBSS7
00167           "w/SS7"
00168 #endif
00169 ;
00170 
00171 static const char config[] = "zapata.conf";
00172 
00173 #define SIG_EM    ZT_SIG_EM
00174 #define SIG_EMWINK   (0x0100000 | ZT_SIG_EM)
00175 #define SIG_FEATD (0x0200000 | ZT_SIG_EM)
00176 #define  SIG_FEATDMF (0x0400000 | ZT_SIG_EM)
00177 #define  SIG_FEATB   (0x0800000 | ZT_SIG_EM)
00178 #define  SIG_E911 (0x1000000 | ZT_SIG_EM)
00179 #define  SIG_FEATDMF_TA (0x2000000 | ZT_SIG_EM)
00180 #define  SIG_FGC_CAMA   (0x4000000 | ZT_SIG_EM)
00181 #define  SIG_FGC_CAMAMF (0x8000000 | ZT_SIG_EM)
00182 #define SIG_FXSLS ZT_SIG_FXSLS
00183 #define SIG_FXSGS ZT_SIG_FXSGS
00184 #define SIG_FXSKS ZT_SIG_FXSKS
00185 #define SIG_FXOLS ZT_SIG_FXOLS
00186 #define SIG_FXOGS ZT_SIG_FXOGS
00187 #define SIG_FXOKS ZT_SIG_FXOKS
00188 #define SIG_PRI      ZT_SIG_CLEAR
00189 #define SIG_SS7      (0x1000000 | ZT_SIG_CLEAR)
00190 #define  SIG_SF      ZT_SIG_SF
00191 #define SIG_SFWINK   (0x0100000 | ZT_SIG_SF)
00192 #define SIG_SF_FEATD (0x0200000 | ZT_SIG_SF)
00193 #define  SIG_SF_FEATDMF (0x0400000 | ZT_SIG_SF)
00194 #define  SIG_SF_FEATB   (0x0800000 | ZT_SIG_SF)
00195 #define SIG_EM_E1 ZT_SIG_EM_E1
00196 #define SIG_GR303FXOKS  (0x0100000 | ZT_SIG_FXOKS)
00197 #define SIG_GR303FXSKS  (0x0100000 | ZT_SIG_FXSKS)
00198 
00199 #define NUM_SPANS       32
00200 #define NUM_DCHANS      4  /*!< No more than 4 d-channels */
00201 #define MAX_CHANNELS 672      /*!< No more than a DS3 per trunk group */
00202 
00203 #define CHAN_PSEUDO  -2
00204 
00205 #define DCHAN_PROVISIONED (1 << 0)
00206 #define DCHAN_NOTINALARM  (1 << 1)
00207 #define DCHAN_UP          (1 << 2)
00208 
00209 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
00210 
00211 static char defaultcic[64] = "";
00212 static char defaultozz[64] = "";
00213 
00214 static char language[MAX_LANGUAGE] = "";
00215 static char progzone[10] = "";
00216 
00217 static int usedistinctiveringdetection = 0;
00218 static int distinctiveringaftercid = 0;
00219 
00220 static int numbufs = 4;
00221 
00222 #ifdef HAVE_PRI
00223 static struct ast_channel inuse;
00224 #ifdef PRI_GETSET_TIMERS
00225 static int pritimers[PRI_MAX_TIMERS];
00226 #endif
00227 static int pridebugfd = -1;
00228 static char pridebugfilename[1024] = "";
00229 #endif
00230 
00231 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
00232 static int firstdigittimeout = 16000;
00233 
00234 /*! \brief How long to wait for following digits (FXO logic) */
00235 static int gendigittimeout = 8000;
00236 
00237 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
00238 static int matchdigittimeout = 3000;
00239 
00240 /*! \brief Protect the interface list (of zt_pvt's) */
00241 AST_MUTEX_DEFINE_STATIC(iflock);
00242 
00243 
00244 static int ifcount = 0;
00245 
00246 #ifdef HAVE_PRI
00247 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
00248 #endif
00249 
00250 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00251    when it's doing something critical. */
00252 AST_MUTEX_DEFINE_STATIC(monlock);
00253 
00254 /*! \brief This is the thread for the monitor which checks for input on the channels
00255    which are not currently in use. */
00256 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00257 
00258 static int restart_monitor(void);
00259 
00260 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
00261 
00262 static int zt_sendtext(struct ast_channel *c, const char *text);
00263 
00264 /*! \brief Avoid the silly zt_getevent which ignores a bunch of events */
00265 static inline int zt_get_event(int fd)
00266 {
00267    int j;
00268    if (ioctl(fd, ZT_GETEVENT, &j) == -1)
00269       return -1;
00270    return j;
00271 }
00272 
00273 /*! \brief Avoid the silly zt_waitevent which ignores a bunch of events */
00274 static inline int zt_wait_event(int fd)
00275 {
00276    int i, j = 0;
00277    i = ZT_IOMUX_SIGEVENT;
00278    if (ioctl(fd, ZT_IOMUX, &i) == -1)
00279       return -1;
00280    if (ioctl(fd, ZT_GETEVENT, &j) == -1)
00281       return -1;
00282    return j;
00283 }
00284 
00285 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
00286 #define READ_SIZE 160
00287 
00288 #define MASK_AVAIL      (1 << 0) /*!< Channel available for PRI use */
00289 #define MASK_INUSE      (1 << 1) /*!< Channel currently in use */
00290 
00291 #define CALLWAITING_SILENT_SAMPLES  ( (300 * 8) / READ_SIZE) /*!< 300 ms */
00292 #define CALLWAITING_REPEAT_SAMPLES  ( (10000 * 8) / READ_SIZE) /*!< 300 ms */
00293 #define CIDCW_EXPIRE_SAMPLES     ( (500 * 8) / READ_SIZE) /*!< 500 ms */
00294 #define MIN_MS_SINCE_FLASH       ( (2000) )  /*!< 2000 ms */
00295 #define DEFAULT_RINGT            ( (8000 * 8) / READ_SIZE)
00296 
00297 struct zt_pvt;
00298 
00299 static int ringt_base = DEFAULT_RINGT;
00300 
00301 #ifdef HAVE_SS7
00302 
00303 #define LINKSTATE_INALARM  (1 << 0)
00304 #define LINKSTATE_STARTING (1 << 1)
00305 #define LINKSTATE_UP    (1 << 2)
00306 #define LINKSTATE_DOWN     (1 << 3)
00307 
00308 struct zt_ss7 {
00309    pthread_t master;                /*!< Thread of master */
00310    ast_mutex_t lock;
00311    int fds[NUM_DCHANS];
00312    int numsigchans;
00313    int linkstate[NUM_DCHANS];
00314    int numchans;
00315    int type;
00316    enum {
00317       LINKSET_STATE_DOWN = 0,
00318       LINKSET_STATE_UP
00319    } state;
00320    struct ss7 *ss7;
00321    struct zt_pvt *pvts[MAX_CHANNELS];           /*!< Member channel pvt structs */
00322 };
00323 
00324 static struct zt_ss7 linksets[NUM_SPANS];
00325 
00326 static int cur_ss7type = -1;
00327 static int cur_linkset = -1;
00328 static int cur_pointcode = -1;
00329 static int cur_cicbeginswith = -1;
00330 static int cur_adjpointcode = -1;
00331 static int cur_networkindicator = -1;
00332 static int cur_defaultdpc = -1;
00333 #endif /* HAVE_SS7 */
00334 
00335 #ifdef HAVE_PRI
00336 
00337 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
00338 #define PRI_CHANNEL(p) ((p) & 0xff)
00339 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
00340 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
00341 
00342 struct zt_pri {
00343    pthread_t master;                /*!< Thread of master */
00344    ast_mutex_t lock;                /*!< Mutex */
00345    char idleext[AST_MAX_EXTENSION];          /*!< Where to idle extra calls */
00346    char idlecontext[AST_MAX_CONTEXT];           /*!< What context to use for idle */
00347    char idledial[AST_MAX_EXTENSION];            /*!< What to dial before dumping */
00348    int minunused;                   /*!< Min # of channels to keep empty */
00349    int minidle;                     /*!< Min # of "idling" calls to keep active */
00350    int nodetype;                    /*!< Node type */
00351    int switchtype;                     /*!< Type of switch to emulate */
00352    int nsf;                   /*!< Network-Specific Facilities */
00353    int dialplan;                    /*!< Dialing plan */
00354    int localdialplan;                  /*!< Local dialing plan */
00355    char internationalprefix[10];             /*!< country access code ('00' for european dialplans) */
00356    char nationalprefix[10];               /*!< area access code ('0' for european dialplans) */
00357    char localprefix[20];                  /*!< area access code + area code ('0'+area code for european dialplans) */
00358    char privateprefix[20];                /*!< for private dialplans */
00359    char unknownprefix[20];                /*!< for unknown dialplans */
00360    int dchannels[NUM_DCHANS];             /*!< What channel are the dchannels on */
00361    int trunkgroup;                     /*!< What our trunkgroup is */
00362    int mastertrunkgroup;                  /*!< What trunk group is our master */
00363    int prilogicalspan;                 /*!< Logical span number within trunk group */
00364    int numchans;                    /*!< Num of channels we represent */
00365    int overlapdial;                 /*!< In overlap dialing mode */
00366    int facilityenable;                 /*!< Enable facility IEs */
00367    struct pri *dchans[NUM_DCHANS];              /*!< Actual d-channels */
00368    int dchanavail[NUM_DCHANS];               /*!< Whether each channel is available */
00369    struct pri *pri;                 /*!< Currently active D-channel */
00370    int debug;
00371    int fds[NUM_DCHANS];                /*!< FD's for d-channels */
00372    int offset;
00373    int span;
00374    int resetting;
00375    int resetpos;
00376    time_t lastreset;                /*!< time when unused channels were last reset */
00377    long resetinterval;                 /*!< Interval (in seconds) for resetting unused channels */
00378    struct zt_pvt *pvts[MAX_CHANNELS];           /*!< Member channel pvt structs */
00379    struct zt_pvt *crvs;                /*!< Member CRV structs */
00380    struct zt_pvt *crvend;                 /*!< Pointer to end of CRV structs */
00381 };
00382 
00383 
00384 static struct zt_pri pris[NUM_SPANS];
00385 
00386 #if 0
00387 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
00388 #else
00389 #define DEFAULT_PRI_DEBUG 0
00390 #endif
00391 
00392 static inline void pri_rel(struct zt_pri *pri)
00393 {
00394    ast_mutex_unlock(&pri->lock);
00395 }
00396 
00397 #else
00398 /*! Shut up the compiler */
00399 struct zt_pri;
00400 #endif
00401 
00402 #define SUB_REAL  0        /*!< Active call */
00403 #define SUB_CALLWAIT 1        /*!< Call-Waiting call on hold */
00404 #define SUB_THREEWAY 2        /*!< Three-way call */
00405 
00406 /* Polarity states */
00407 #define POLARITY_IDLE   0
00408 #define POLARITY_REV    1
00409 
00410 
00411 static struct zt_distRings drings;
00412 
00413 struct distRingData {
00414    int ring[3];
00415    int range;
00416 };
00417 struct ringContextData {
00418    char contextData[AST_MAX_CONTEXT];
00419 };
00420 struct zt_distRings {
00421    struct distRingData ringnum[3];
00422    struct ringContextData ringContext[3];
00423 };
00424 
00425 static char *subnames[] = {
00426    "Real",
00427    "Callwait",
00428    "Threeway"
00429 };
00430 
00431 struct zt_subchannel {
00432    int zfd;
00433    struct ast_channel *owner;
00434    int chan;
00435    short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
00436    struct ast_frame f;     /*!< One frame for each channel.  How did this ever work before? */
00437    unsigned int needringing:1;
00438    unsigned int needbusy:1;
00439    unsigned int needcongestion:1;
00440    unsigned int needcallerid:1;
00441    unsigned int needanswer:1;
00442    unsigned int needflash:1;
00443    unsigned int needhold:1;
00444    unsigned int needunhold:1;
00445    unsigned int linear:1;
00446    unsigned int inthreeway:1;
00447    ZT_CONFINFO curconf;
00448 };
00449 
00450 #define CONF_USER_REAL     (1 << 0)
00451 #define CONF_USER_THIRDCALL   (1 << 1)
00452 
00453 #define MAX_SLAVES   4
00454 
00455 static struct zt_pvt {
00456    ast_mutex_t lock;
00457    struct ast_channel *owner;       /*!< Our current active owner (if applicable) */
00458                      /*!< Up to three channels can be associated with this call */
00459       
00460    struct zt_subchannel sub_unused;    /*!< Just a safety precaution */
00461    struct zt_subchannel subs[3];       /*!< Sub-channels */
00462    struct zt_confinfo saveconf;        /*!< Saved conference info */
00463 
00464    struct zt_pvt *slaves[MAX_SLAVES];     /*!< Slave to us (follows our conferencing) */
00465    struct zt_pvt *master;           /*!< Master to us (we follow their conferencing) */
00466    int inconference;          /*!< If our real should be in the conference */
00467    
00468    int sig;             /*!< Signalling style */
00469    int radio;              /*!< radio type */
00470    int outsigmod;             /*!< Outbound Signalling style (modifier) */
00471    int oprmode;               /*!< "Operator Services" mode */
00472    struct zt_pvt *oprpeer;          /*!< "Operator Services" peer tech_pvt ptr */
00473    float rxgain;
00474    float txgain;
00475    int tonezone;              /*!< tone zone for this chan, or -1 for default */
00476    struct zt_pvt *next;          /*!< Next channel in list */
00477    struct zt_pvt *prev;          /*!< Prev channel in list */
00478 
00479    /* flags */
00480    unsigned int adsi:1;
00481    unsigned int answeronpolarityswitch:1;
00482    unsigned int busydetect:1;
00483    unsigned int callreturn:1;
00484    unsigned int callwaiting:1;
00485    unsigned int callwaitingcallerid:1;
00486    unsigned int cancallforward:1;
00487    unsigned int canpark:1;
00488    unsigned int confirmanswer:1;       /*!< Wait for '#' to confirm answer */
00489    unsigned int destroy:1;
00490    unsigned int didtdd:1;           /*!< flag to say its done it once */
00491    unsigned int dialednone:1;
00492    unsigned int dialing:1;
00493    unsigned int digital:1;
00494    unsigned int dnd:1;
00495    unsigned int echobreak:1;
00496    unsigned int echocanbridged:1;
00497    unsigned int echocanon:1;
00498    unsigned int faxhandled:1;       /*!< Has a fax tone already been handled? */
00499    unsigned int firstradio:1;
00500    unsigned int hanguponpolarityswitch:1;
00501    unsigned int hardwaredtmf:1;
00502    unsigned int hidecallerid:1;
00503    unsigned int hidecalleridname:1;      /*!< Hide just the name not the number for legacy PBX use */
00504    unsigned int ignoredtmf:1;
00505    unsigned int immediate:1;        /*!< Answer before getting digits? */
00506    unsigned int inalarm:1;
00507    unsigned int mate:1;          /*!< flag to say its in MATE mode */
00508    unsigned int outgoing:1;
00509    unsigned int overlapdial:1;
00510    unsigned int permcallwaiting:1;
00511    unsigned int permhidecallerid:1;    /*!< Whether to hide our outgoing caller ID or not */
00512    unsigned int priindication_oob:1;
00513    unsigned int priexclusive:1;
00514    unsigned int pulse:1;
00515    unsigned int pulsedial:1;        /*!< whether a pulse dial phone is detected */
00516    unsigned int restrictcid:1;         /*!< Whether restrict the callerid -> only send ANI */
00517    unsigned int threewaycalling:1;
00518    unsigned int transfer:1;
00519    unsigned int use_callerid:1;        /*!< Whether or not to use caller id on this channel */
00520    unsigned int use_callingpres:1;        /*!< Whether to use the callingpres the calling switch sends */
00521    unsigned int usedistinctiveringdetection:1;
00522    unsigned int zaptrcallerid:1;       /*!< should we use the callerid from incoming call on zap transfer or not */
00523    unsigned int transfertobusy:1;         /*!< allow flash-transfers to busy channels */
00524    /* Channel state or unavilability flags */
00525    unsigned int inservice:1;
00526    unsigned int locallyblocked:1;
00527    unsigned int remotelyblocked:1;
00528 #if defined(HAVE_PRI)
00529    unsigned int alerting:1;
00530    unsigned int alreadyhungup:1;
00531    unsigned int isidlecall:1;
00532    unsigned int proceeding:1;
00533    unsigned int progress:1;
00534    unsigned int resetting:1;
00535    unsigned int setup_ack:1;
00536 #endif
00537    unsigned int use_smdi:1;      /* Whether to use SMDI on this channel */
00538    struct ast_smdi_interface *smdi_iface; /* The serial port to listen for SMDI data on */
00539 
00540    struct zt_distRings drings;
00541 
00542    char context[AST_MAX_CONTEXT];
00543    char defcontext[AST_MAX_CONTEXT];
00544    char exten[AST_MAX_EXTENSION];
00545    char language[MAX_LANGUAGE];
00546    char mohinterpret[MAX_MUSICCLASS];
00547    char mohsuggest[MAX_MUSICCLASS];
00548 #ifdef PRI_ANI
00549    char cid_ani[AST_MAX_EXTENSION];
00550 #endif
00551    char cid_num[AST_MAX_EXTENSION];
00552    int cid_ton;               /*!< Type Of Number (TON) */
00553    char cid_name[AST_MAX_EXTENSION];
00554    char lastcid_num[AST_MAX_EXTENSION];
00555    char lastcid_name[AST_MAX_EXTENSION];
00556    char *origcid_num;            /*!< malloced original callerid */
00557    char *origcid_name;           /*!< malloced original callerid */
00558    char callwait_num[AST_MAX_EXTENSION];
00559    char callwait_name[AST_MAX_EXTENSION];
00560    char rdnis[AST_MAX_EXTENSION];
00561    char dnid[AST_MAX_EXTENSION];
00562    unsigned int group;
00563    int law;
00564    int confno;             /*!< Our conference */
00565    int confusers;             /*!< Who is using our conference */
00566    int propconfno;               /*!< Propagated conference number */
00567    ast_group_t callgroup;
00568    ast_group_t pickupgroup;
00569    int channel;               /*!< Channel Number or CRV */
00570    int span;               /*!< Span number */
00571    time_t guardtime;          /*!< Must wait this much time before using for new call */
00572    int cid_signalling;           /*!< CID signalling type bell202 or v23 */
00573    int cid_start;             /*!< CID start indicator, polarity or ring */
00574    int callingpres;           /*!< The value of callling presentation that we're going to use when placing a PRI call */
00575    int callwaitingrepeat;           /*!< How many samples to wait before repeating call waiting */
00576    int cidcwexpire;           /*!< When to expire our muting for CID/CW */
00577    unsigned char *cidspill;
00578    int cidpos;
00579    int cidlen;
00580    int ringt;
00581    int ringt_base;
00582    int stripmsd;
00583    int callwaitcas;
00584    int callwaitrings;
00585    int echocancel;
00586    int echotraining;
00587    char echorest[20];
00588    int busycount;
00589    int busy_tonelength;
00590    int busy_quietlength;
00591    int callprogress;
00592    struct timeval flashtime;        /*!< Last flash-hook time */
00593    struct ast_dsp *dsp;
00594    int cref;               /*!< Call reference number */
00595    ZT_DIAL_OPERATION dop;
00596    int whichwink;             /*!< SIG_FEATDMF_TA Which wink are we on? */
00597    char finaldial[64];
00598    char accountcode[AST_MAX_ACCOUNT_CODE];      /*!< Account code */
00599    int amaflags;              /*!< AMA Flags */
00600    struct tdd_state *tdd;           /*!< TDD flag */
00601    char call_forward[AST_MAX_EXTENSION];
00602    char mailbox[AST_MAX_EXTENSION];
00603    char dialdest[256];
00604    int onhooktime;
00605    int msgstate;
00606    int distinctivering;          /*!< Which distinctivering to use */
00607    int cidrings;              /*!< Which ring to deliver CID on */
00608    int dtmfrelax;             /*!< whether to run in relaxed DTMF mode */
00609    int fake_event;
00610    int polarityonanswerdelay;
00611    struct timeval polaritydelaytv;
00612    int sendcalleridafter;
00613 #ifdef HAVE_PRI
00614    struct zt_pri *pri;
00615    struct zt_pvt *bearer;
00616    struct zt_pvt *realcall;
00617    q931_call *call;
00618    int prioffset;
00619    int logicalspan;
00620 #endif   
00621    int polarity;
00622    int dsp_features;
00623 #ifdef HAVE_SS7
00624    struct zt_ss7 *ss7;
00625    struct isup_call *ss7call;
00626    int transcap;
00627    int cic;                   /*!< CIC associated with channel */
00628 #endif
00629    char begindigit;
00630 } *iflist = NULL, *ifend = NULL;
00631 
00632 /*! \brief Channel configuration from zapata.conf .
00633  * This struct is used for parsing the [channels] section of zapata.conf.
00634  * Generally there is a field here for every possible configuration item.
00635  *
00636  * The state of fields is saved along the parsing and whenever a 'channel'
00637  * statement is reached, the current zt_chan_conf is used to configure the 
00638  * channel (struct zt_pvt)
00639  *
00640  * @seealso zt_chan_init for the default values.
00641  */
00642 struct zt_chan_conf {
00643    struct zt_pvt chan;
00644 #ifdef HAVE_PRI
00645    struct zt_pri pri;
00646 #endif
00647    ZT_PARAMS timing;
00648 
00649    char smdi_port[SMDI_MAX_FILENAME_LEN];
00650 };
00651 
00652 /** returns a new zt_chan_conf with default values (by-value) */
00653 static struct zt_chan_conf zt_chan_conf_default(void) {
00654    /* recall that if a field is not included here it is initialized
00655     * to 0 or equivalent
00656     */
00657    struct zt_chan_conf conf = {
00658 #ifdef HAVE_PRI
00659       .pri = {
00660          .nsf = PRI_NSF_NONE,
00661          .switchtype = PRI_SWITCH_NI2,
00662          .dialplan = PRI_NATIONAL_ISDN + 1,
00663          .localdialplan = PRI_NATIONAL_ISDN + 1,
00664          .nodetype = PRI_CPE,
00665 
00666          .minunused = 2,
00667          .idleext = "",
00668          .idledial = "",
00669          .internationalprefix = "",
00670          .nationalprefix = "",
00671          .localprefix = "",
00672          .privateprefix = "",
00673          .unknownprefix = "",
00674 
00675          .resetinterval = 3600
00676       },
00677 #endif
00678       .chan = {
00679          .context = "default",
00680          .cid_num = "",
00681          .cid_name = "",
00682          .mohinterpret = "default",
00683          .mohsuggest = "",
00684          .transfertobusy = 1,
00685 
00686          .cid_signalling = CID_SIG_BELL,
00687          .cid_start = CID_START_RING,
00688          .zaptrcallerid = 0,
00689          .use_callerid = 1,
00690          .sig = -1,
00691          .outsigmod = -1,
00692 
00693          .tonezone = -1,
00694 
00695          .echocancel = 1,
00696 
00697          .busycount = 3,
00698 
00699          .accountcode = "",
00700 
00701          .mailbox = "",
00702 
00703 
00704          .polarityonanswerdelay = 600,
00705 
00706          .sendcalleridafter = DEFAULT_CIDRINGS
00707       },
00708       .timing = {
00709          .prewinktime = -1,
00710          .preflashtime = -1,
00711          .winktime = -1,
00712          .flashtime = -1,
00713          .starttime = -1,
00714          .rxwinktime = -1,
00715          .rxflashtime = -1,
00716          .debouncetime = -1
00717       },
00718       .smdi_port = "/dev/ttyS0",
00719    };
00720 
00721    return conf;
00722 }
00723 
00724 
00725 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
00726 static int zt_digit_begin(struct ast_channel *ast, char digit);
00727 static int zt_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
00728 static int zt_sendtext(struct ast_channel *c, const char *text);
00729 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
00730 static int zt_hangup(struct ast_channel *ast);
00731 static int zt_answer(struct ast_channel *ast);
00732 static struct ast_frame *zt_read(struct ast_channel *ast);
00733 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
00734 static struct ast_frame *zt_exception(struct ast_channel *ast);
00735 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
00736 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00737 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
00738 static int zt_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
00739 
00740 static const struct ast_channel_tech zap_tech = {
00741    .type = "Zap",
00742    .description = tdesc,
00743    .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
00744    .requester = zt_request,
00745    .send_digit_begin = zt_digit_begin,
00746    .send_digit_end = zt_digit_end,
00747    .send_text = zt_sendtext,
00748    .call = zt_call,
00749    .hangup = zt_hangup,
00750    .answer = zt_answer,
00751    .read = zt_read,
00752    .write = zt_write,
00753    .bridge = zt_bridge,
00754    .exception = zt_exception,
00755    .indicate = zt_indicate,
00756    .fixup = zt_fixup,
00757    .setoption = zt_setoption,
00758    .func_channel_read = zt_func_read,
00759 };
00760 
00761 #ifdef HAVE_PRI
00762 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
00763 #else
00764 #define GET_CHANNEL(p) ((p)->channel)
00765 #endif
00766 
00767 struct zt_pvt *round_robin[32];
00768 
00769 #ifdef HAVE_PRI
00770 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
00771 {
00772    int res;
00773    /* Grab the lock first */
00774    do {
00775       res = ast_mutex_trylock(&pri->lock);
00776       if (res) {
00777          ast_mutex_unlock(&pvt->lock);
00778          /* Release the lock and try again */
00779          usleep(1);
00780          ast_mutex_lock(&pvt->lock);
00781       }
00782    } while (res);
00783    /* Then break the poll */
00784    pthread_kill(pri->master, SIGURG);
00785    return 0;
00786 }
00787 #endif
00788 
00789 #ifdef HAVE_SS7
00790 static inline void ss7_rel(struct zt_ss7 *ss7)
00791 {
00792    ast_mutex_unlock(&ss7->lock);
00793 }
00794 
00795 static inline int ss7_grab(struct zt_pvt *pvt, struct zt_ss7 *pri)
00796 {
00797    int res;
00798    /* Grab the lock first */
00799    do {
00800       res = ast_mutex_trylock(&pri->lock);
00801       if (res) {
00802          ast_mutex_unlock(&pvt->lock);
00803          /* Release the lock and try again */
00804          usleep(1);
00805          ast_mutex_lock(&pvt->lock);
00806       }
00807    } while (res);
00808    /* Then break the poll */
00809    pthread_kill(pri->master, SIGURG);
00810    return 0;
00811 }
00812 #endif
00813 #define NUM_CADENCE_MAX 25
00814 static int num_cadence = 4;
00815 static int user_has_defined_cadences = 0;
00816 
00817 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
00818    { { 125, 125, 2000, 4000 } },       /*!< Quick chirp followed by normal ring */
00819    { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
00820    { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
00821    { { 1000, 500, 2500, 5000 } },   /*!< Long ring */
00822 };
00823 
00824 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
00825  * is 1, the second pause is 2 and so on.
00826  */
00827 
00828 static int cidrings[NUM_CADENCE_MAX] = {
00829    2,                            /*!< Right after first long ring */
00830    4,                            /*!< Right after long part */
00831    3,                            /*!< After third chirp */
00832    2,                            /*!< Second spell */
00833 };
00834 
00835 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
00836          (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
00837 
00838 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
00839 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
00840 
00841 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
00842 {
00843    int res;
00844    if (p->subs[0].owner == ast)
00845       res = 0;
00846    else if (p->subs[1].owner == ast)
00847       res = 1;
00848    else if (p->subs[2].owner == ast)
00849       res = 2;
00850    else {
00851       res = -1;
00852       if (!nullok)
00853          ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
00854    }
00855    return res;
00856 }
00857 
00858 #ifdef HAVE_PRI
00859 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
00860 #else
00861 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
00862 #endif
00863 {
00864 #ifdef HAVE_PRI
00865    if (pri)
00866       ast_mutex_unlock(&pri->lock);
00867 #endif         
00868    for (;;) {
00869       if (p->subs[a].owner) {
00870          if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
00871             ast_mutex_unlock(&p->lock);
00872             usleep(1);
00873             ast_mutex_lock(&p->lock);
00874          } else {
00875             ast_queue_frame(p->subs[a].owner, &ast_null_frame);
00876             ast_mutex_unlock(&p->subs[a].owner->lock);
00877             break;
00878          }
00879       } else
00880          break;
00881    }
00882 #ifdef HAVE_PRI
00883    if (pri)
00884       ast_mutex_lock(&pri->lock);
00885 #endif         
00886 }
00887 
00888 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *data)
00889 {
00890 #ifdef HAVE_PRI
00891    struct zt_pri *pri = (struct zt_pri*) data;
00892 #endif
00893 #ifdef HAVE_SS7
00894    struct zt_ss7 *ss7 = (struct zt_ss7*) data;
00895 #endif
00896    /* We must unlock the PRI to avoid the possibility of a deadlock */
00897 #if defined(HAVE_PRI) || defined(HAVE_SS7)
00898    if (data) {
00899       switch (p->sig) {
00900 #ifdef HAVE_PRI
00901       case SIG_PRI:
00902          ast_mutex_unlock(&pri->lock);
00903          break;
00904 #endif
00905 #ifdef HAVE_SS7
00906       case SIG_SS7:
00907          ast_mutex_unlock(&ss7->lock);
00908          break;
00909 #endif
00910       default:
00911          break;
00912       }
00913    }
00914 #endif      
00915    for (;;) {
00916       if (p->owner) {
00917          if (ast_mutex_trylock(&p->owner->lock)) {
00918             ast_mutex_unlock(&p->lock);
00919             usleep(1);
00920             ast_mutex_lock(&p->lock);
00921          } else {
00922             ast_queue_frame(p->owner, f);
00923             ast_mutex_unlock(&p->owner->lock);
00924             break;
00925          }
00926       } else
00927          break;
00928    }
00929 #if defined(HAVE_PRI) || defined(HAVE_SS7)
00930    if (data) {
00931       switch (p->sig) {
00932 #ifdef HAVE_PRI
00933       case SIG_PRI:
00934          ast_mutex_lock(&pri->lock);
00935          break;
00936 #endif
00937 #ifdef HAVE_SS7
00938       case SIG_SS7:
00939          ast_mutex_lock(&ss7->lock);
00940          break;
00941 #endif
00942       default:
00943          break;
00944       }
00945    }
00946 
00947 #endif      
00948 }
00949 
00950 static int restore_gains(struct zt_pvt *p);
00951 
00952 static void swap_subs(struct zt_pvt *p, int a, int b)
00953 {
00954    int tchan;
00955    int tinthreeway;
00956    struct ast_channel *towner;
00957 
00958    if (option_debug)
00959       ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
00960 
00961    tchan = p->subs[a].chan;
00962    towner = p->subs[a].owner;
00963    tinthreeway = p->subs[a].inthreeway;
00964 
00965    p->subs[a].chan = p->subs[b].chan;
00966    p->subs[a].owner = p->subs[b].owner;
00967    p->subs[a].inthreeway = p->subs[b].inthreeway;
00968 
00969    p->subs[b].chan = tchan;
00970    p->subs[b].owner = towner;
00971    p->subs[b].inthreeway = tinthreeway;
00972 
00973    if (p->subs[a].owner) 
00974       p->subs[a].owner->fds[0] = p->subs[a].zfd;
00975    if (p->subs[b].owner) 
00976       p->subs[b].owner->fds[0] = p->subs[b].zfd;
00977    wakeup_sub(p, a, NULL);
00978    wakeup_sub(p, b, NULL);
00979 }
00980 
00981 static int zt_open(char *fn)
00982 {
00983    int fd;
00984    int isnum;
00985    int chan = 0;
00986    int bs;
00987    int x;
00988    isnum = 1;
00989    for (x = 0; x < strlen(fn); x++) {
00990       if (!isdigit(fn[x])) {
00991          isnum = 0;
00992          break;
00993       }
00994    }
00995    if (isnum) {
00996       chan = atoi(fn);
00997       if (chan < 1) {
00998          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
00999          return -1;
01000       }
01001       fn = "/dev/zap/channel";
01002    }
01003    fd = open(fn, O_RDWR | O_NONBLOCK);
01004    if (fd < 0) {
01005       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
01006       return -1;
01007    }
01008    if (chan) {
01009       if (ioctl(fd, ZT_SPECIFY, &chan)) {
01010          x = errno;
01011          close(fd);
01012          errno = x;
01013          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
01014          return -1;
01015       }
01016    }
01017    bs = READ_SIZE;
01018    if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
01019    return fd;
01020 }
01021 
01022 static void zt_close(int fd)
01023 {
01024    if (fd > 0)
01025       close(fd);
01026 }
01027 
01028 static int zt_setlinear(int zfd, int linear)
01029 {
01030    int res;
01031    res = ioctl(zfd, ZT_SETLINEAR, &linear);
01032    if (res)
01033       return res;
01034    return 0;
01035 }
01036 
01037 
01038 static int alloc_sub(struct zt_pvt *p, int x)
01039 {
01040    ZT_BUFFERINFO bi;
01041    int res;
01042    if (p->subs[x].zfd < 0) {
01043       p->subs[x].zfd = zt_open("/dev/zap/pseudo");
01044       if (p->subs[x].zfd > -1) {
01045          res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
01046          if (!res) {
01047             bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
01048             bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
01049             bi.numbufs = numbufs;
01050             res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
01051             if (res < 0) {
01052                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
01053             }
01054          } else 
01055             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
01056          if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
01057             ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
01058             zt_close(p->subs[x].zfd);
01059             p->subs[x].zfd = -1;
01060             return -1;
01061          }
01062          if (option_debug)
01063             ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
01064          return 0;
01065       } else
01066          ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
01067       return -1;
01068    }
01069    ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
01070    return -1;
01071 }
01072 
01073 static int unalloc_sub(struct zt_pvt *p, int x)
01074 {
01075    if (!x) {
01076       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
01077       return -1;
01078    }
01079    if (option_debug)
01080       ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
01081    if (p->subs[x].zfd > -1) {
01082       zt_close(p->subs[x].zfd);
01083    }
01084    p->subs[x].zfd = -1;
01085    p->subs[x].linear = 0;
01086    p->subs[x].chan = 0;
01087    p->subs[x].owner = NULL;
01088    p->subs[x].inthreeway = 0;
01089    p->polarity = POLARITY_IDLE;
01090    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
01091    return 0;
01092 }
01093 
01094 static int digit_to_dtmfindex(char digit)
01095 {
01096    if (isdigit(digit))
01097       return ZT_TONE_DTMF_BASE + (digit - '0');
01098    else if (digit >= 'A' && digit <= 'D')
01099       return ZT_TONE_DTMF_A + (digit - 'A');
01100    else if (digit >= 'a' && digit <= 'd')
01101       return ZT_TONE_DTMF_A + (digit - 'a');
01102    else if (digit == '*')
01103       return ZT_TONE_DTMF_s;
01104    else if (digit == '#')
01105       return ZT_TONE_DTMF_p;
01106    else
01107       return -1;
01108 }
01109 
01110 static int zt_digit_begin(struct ast_channel *chan, char digit)
01111 {
01112    struct zt_pvt *pvt;
01113    int index;
01114    int dtmf = -1;
01115    
01116    pvt = chan->tech_pvt;
01117 
01118    ast_mutex_lock(&pvt->lock);
01119 
01120    index = zt_get_index(chan, pvt, 0);
01121 
01122    if ((index != SUB_REAL) || !pvt->owner)
01123       goto out;
01124 
01125 #ifdef HAVE_PRI
01126    if ((pvt->sig == SIG_PRI) && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
01127       if (pvt->setup_ack) {
01128          if (!pri_grab(pvt, pvt->pri)) {
01129             pri_information(pvt->pri->pri, pvt->call, digit);
01130             pri_rel(pvt->pri);
01131          } else
01132             ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
01133       } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
01134          int res;
01135          if (option_debug)
01136             ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
01137          res = strlen(pvt->dialdest);
01138          pvt->dialdest[res++] = digit;
01139          pvt->dialdest[res] = '\0';
01140       }
01141       goto out;
01142    }
01143 #endif
01144    if ((dtmf = digit_to_dtmfindex(digit)) == -1)
01145       goto out;
01146 
01147    if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &dtmf)) {
01148       int res;
01149       ZT_DIAL_OPERATION zo = {
01150          .op = ZT_DIAL_OP_APPEND,
01151       };
01152 
01153       zo.dialstr[0] = 'T';
01154       zo.dialstr[1] = digit;
01155       zo.dialstr[2] = '\0';
01156       if ((res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
01157          ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
01158       else
01159          pvt->dialing = 1;
01160    } else {
01161       if (option_debug)
01162          ast_log(LOG_DEBUG, "Started VLDTMF digit '%c'\n", digit);
01163       pvt->dialing = 1;
01164       pvt->begindigit = digit;
01165    }
01166 
01167 out:
01168    ast_mutex_unlock(&pvt->lock);
01169 
01170    return 0;
01171 }
01172 
01173 static int zt_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
01174 {
01175    struct zt_pvt *pvt;
01176    int res = 0;
01177    int index;
01178    int x;
01179    
01180    pvt = chan->tech_pvt;
01181 
01182    ast_mutex_lock(&pvt->lock);
01183    
01184    index = zt_get_index(chan, pvt, 0);
01185 
01186    if ((index != SUB_REAL) || !pvt->owner || pvt->pulse)
01187       goto out;
01188 
01189 #ifdef HAVE_PRI
01190    /* This means that the digit was already sent via PRI signalling */
01191    if (pvt->sig == SIG_PRI && !pvt->begindigit)
01192       goto out;
01193 #endif
01194 
01195    if (pvt->begindigit) {
01196       x = -1;
01197       if (option_debug)
01198          ast_log(LOG_DEBUG, "Ending VLDTMF digit '%c'\n", digit);
01199       res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &x);
01200       pvt->dialing = 0;
01201       pvt->begindigit = 0;
01202    }
01203 
01204 out:
01205    ast_mutex_unlock(&pvt->lock);
01206 
01207    return res;
01208 }
01209 
01210 static char *events[] = {
01211    "No event",
01212    "On hook",
01213    "Ring/Answered",
01214    "Wink/Flash",
01215    "Alarm",
01216    "No more alarm",
01217    "HDLC Abort",
01218    "HDLC Overrun",
01219    "HDLC Bad FCS",
01220    "Dial Complete",
01221    "Ringer On",
01222    "Ringer Off",
01223    "Hook Transition Complete",
01224    "Bits Changed",
01225    "Pulse Start",
01226    "Timer Expired",
01227    "Timer Ping",
01228    "Polarity Reversal",
01229    "Ring Begin",
01230 };
01231 
01232 static struct {
01233    int alarm;
01234    char *name;
01235 } alarms[] = {
01236    { ZT_ALARM_RED, "Red Alarm" },
01237    { ZT_ALARM_YELLOW, "Yellow Alarm" },
01238    { ZT_ALARM_BLUE, "Blue Alarm" },
01239    { ZT_ALARM_RECOVER, "Recovering" },
01240    { ZT_ALARM_LOOPBACK, "Loopback" },
01241    { ZT_ALARM_NOTOPEN, "Not Open" },
01242    { ZT_ALARM_NONE, "None" },
01243 };
01244 
01245 static char *alarm2str(int alarm)
01246 {
01247    int x;
01248    for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
01249       if (alarms[x].alarm & alarm)
01250          return alarms[x].name;
01251    }
01252    return alarm ? "Unknown Alarm" : "No Alarm";
01253 }
01254 
01255 static char *event2str(int event)
01256 {
01257    static char buf[256];
01258    if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
01259       return events[event];
01260    sprintf(buf, "Event %d", event); /* safe */
01261    return buf;
01262 }
01263 
01264 #ifdef HAVE_PRI
01265 static char *dialplan2str(int dialplan)
01266 {
01267    if (dialplan == -1) {
01268       return("Dynamically set dialplan in ISDN");
01269    }
01270    return (pri_plan2str(dialplan));
01271 }
01272 #endif
01273 
01274 static char *zap_sig2str(int sig)
01275 {
01276    static char buf[256];
01277    switch (sig) {
01278    case SIG_EM:
01279       return "E & M Immediate";
01280    case SIG_EMWINK:
01281       return "E & M Wink";
01282    case SIG_EM_E1:
01283       return "E & M E1";
01284    case SIG_FEATD:
01285       return "Feature Group D (DTMF)";
01286    case SIG_FEATDMF:
01287       return "Feature Group D (MF)";
01288    case SIG_FEATDMF_TA:
01289       return "Feature Groud D (MF) Tandem Access";
01290    case SIG_FEATB:
01291       return "Feature Group B (MF)";
01292    case SIG_E911:
01293       return "E911 (MF)";
01294    case SIG_FGC_CAMA:
01295       return "FGC/CAMA (Dialpulse)";
01296    case SIG_FGC_CAMAMF:
01297       return "FGC/CAMA (MF)";
01298    case SIG_FXSLS:
01299       return "FXS Loopstart";
01300    case SIG_FXSGS:
01301       return "FXS Groundstart";
01302    case SIG_FXSKS:
01303       return "FXS Kewlstart";
01304    case SIG_FXOLS:
01305       return "FXO Loopstart";
01306    case SIG_FXOGS:
01307       return "FXO Groundstart";
01308    case SIG_FXOKS:
01309       return "FXO Kewlstart";
01310    case SIG_PRI:
01311       return "PRI Signalling";
01312    case SIG_SS7:
01313       return "SS7 Signalling";
01314    case SIG_SF:
01315       return "SF (Tone) Signalling Immediate";
01316    case SIG_SFWINK:
01317       return "SF (Tone) Signalling Wink";
01318    case SIG_SF_FEATD:
01319       return "SF (Tone) Signalling with Feature Group D (DTMF)";
01320    case SIG_SF_FEATDMF:
01321       return "SF (Tone) Signalling with Feature Group D (MF)";
01322    case SIG_SF_FEATB:
01323       return "SF (Tone) Signalling with Feature Group B (MF)";
01324    case SIG_GR303FXOKS:
01325       return "GR-303 Signalling with FXOKS";
01326    case SIG_GR303FXSKS:
01327       return "GR-303 Signalling with FXSKS";
01328    case 0:
01329       return "Pseudo Signalling";
01330    default:
01331       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
01332       return buf;
01333    }
01334 }
01335 
01336 #define sig2str zap_sig2str
01337 
01338 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
01339 {
01340    /* If the conference already exists, and we're already in it
01341       don't bother doing anything */
01342    ZT_CONFINFO zi;
01343    
01344    memset(&zi, 0, sizeof(zi));
01345    zi.chan = 0;
01346 
01347    if (slavechannel > 0) {
01348       /* If we have only one slave, do a digital mon */
01349       zi.confmode = ZT_CONF_DIGITALMON;
01350       zi.confno = slavechannel;
01351    } else {
01352       if (!index) {
01353          /* Real-side and pseudo-side both participate in conference */
01354          zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
01355             ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
01356       } else
01357          zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
01358       zi.confno = p->confno;
01359    }
01360    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
01361       return 0;
01362    if (c->zfd < 0)
01363       return 0;
01364    if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
01365       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
01366       return -1;
01367    }
01368    if (slavechannel < 1) {
01369       p->confno = zi.confno;
01370    }
01371    memcpy(&c->curconf, &zi, sizeof(c->curconf));
01372    if (option_debug)
01373       ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
01374    return 0;
01375 }
01376 
01377 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
01378 {
01379    /* If they're listening to our channel, they're ours */  
01380    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
01381       return 1;
01382    /* If they're a talker on our (allocated) conference, they're ours */
01383    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
01384       return 1;
01385    return 0;
01386 }
01387 
01388 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
01389 {
01390    ZT_CONFINFO zi;
01391    if (/* Can't delete if there's no zfd */
01392       (c->zfd < 0) ||
01393       /* Don't delete from the conference if it's not our conference */
01394       !isourconf(p, c)
01395       /* Don't delete if we don't think it's conferenced at all (implied) */
01396       ) return 0;
01397    memset(&zi, 0, sizeof(zi));
01398    zi.chan = 0;
01399    zi.confno = 0;
01400    zi.confmode = 0;
01401    if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
01402       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
01403       return -1;
01404    }
01405    if (option_debug)
01406       ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
01407    memcpy(&c->curconf, &zi, sizeof(c->curconf));
01408    return 0;
01409 }
01410 
01411 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
01412 {
01413    int x;
01414    int useslavenative;
01415    struct zt_pvt *slave = NULL;
01416    /* Start out optimistic */
01417    useslavenative = 1;
01418    /* Update conference state in a stateless fashion */
01419    for (x = 0; x < 3; x++) {
01420       /* Any three-way calling makes slave native mode *definitely* out
01421          of the question */
01422       if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
01423          useslavenative = 0;
01424    }
01425    /* If we don't have any 3-way calls, check to see if we have
01426       precisely one slave */
01427    if (useslavenative) {
01428       for (x = 0; x < MAX_SLAVES; x++) {
01429          if (p->slaves[x]) {
01430             if (slave) {
01431                /* Whoops already have a slave!  No 
01432                   slave native and stop right away */
01433                slave = NULL;
01434                useslavenative = 0;
01435                break;
01436             } else {
01437                /* We have one slave so far */
01438                slave = p->slaves[x];
01439             }
01440          }
01441       }
01442    }
01443    /* If no slave, slave native definitely out */
01444    if (!slave)
01445       useslavenative = 0;
01446    else if (slave->law != p->law) {
01447       useslavenative = 0;
01448       slave = NULL;
01449    }
01450    if (out)
01451       *out = slave;
01452    return useslavenative;
01453 }
01454 
01455 static int reset_conf(struct zt_pvt *p)
01456 {
01457    ZT_CONFINFO zi;
01458    memset(&zi, 0, sizeof(zi));
01459    p->confno = -1;
01460    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
01461    if (p->subs[SUB_REAL].zfd > -1) {
01462       if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
01463          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
01464    }
01465    return 0;
01466 }
01467 
01468 static int update_conf(struct zt_pvt *p)
01469 {
01470    int needconf = 0;
01471    int x;
01472    int useslavenative;
01473    struct zt_pvt *slave = NULL;
01474 
01475    useslavenative = isslavenative(p, &slave);
01476    /* Start with the obvious, general stuff */
01477    for (x = 0; x < 3; x++) {
01478       /* Look for three way calls */
01479       if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
01480          conf_add(p, &p->subs[x], x, 0);
01481          needconf++;
01482       } else {
01483          conf_del(p, &p->subs[x], x);
01484       }
01485    }
01486    /* If we have a slave, add him to our conference now. or DAX
01487       if this is slave native */
01488    for (x = 0; x < MAX_SLAVES; x++) {
01489       if (p->slaves[x]) {
01490          if (useslavenative)
01491             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
01492          else {
01493             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
01494             needconf++;
01495          }
01496       }
01497    }
01498    /* If we're supposed to be in there, do so now */
01499    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
01500       if (useslavenative)
01501          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
01502       else {
01503          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
01504          needconf++;
01505       }
01506    }
01507    /* If we have a master, add ourselves to his conference */
01508    if (p->master) {
01509       if (isslavenative(p->master, NULL)) {
01510          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
01511       } else {
01512          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
01513       }
01514    }
01515    if (!needconf) {
01516       /* Nobody is left (or should be left) in our conference.
01517          Kill it. */
01518       p->confno = -1;
01519    }
01520    if (option_debug)
01521       ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
01522    return 0;
01523 }
01524 
01525 static void zt_enable_ec(struct zt_pvt *p)
01526 {
01527    int x;
01528    int res;
01529    if (!p)
01530       return;
01531    if (p->echocanon) {
01532       if (option_debug)
01533          ast_log(LOG_DEBUG, "Echo cancellation already on\n");
01534       return;
01535    }
01536    if (p->digital) {
01537       if (option_debug)
01538          ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
01539       return;
01540    }
01541    if (p->echocancel) {
01542       if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
01543          x = 1;
01544          res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
01545          if (res)
01546             ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
01547       }
01548       x = p->echocancel;
01549       res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
01550       if (res) 
01551          ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
01552       else {
01553          p->echocanon = 1;
01554          if (option_debug)
01555             ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
01556       }
01557    } else {
01558       if (option_debug)
01559          ast_log(LOG_DEBUG, "No echo cancellation requested\n");
01560    }
01561 }
01562 
01563 static void zt_train_ec(struct zt_pvt *p)
01564 {
01565    int x;
01566    int res;
01567    if (p && p->echocancel && p->echotraining) {
01568       x = p->echotraining;
01569       res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
01570       if (res)
01571          ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
01572       else {
01573          if (option_debug)
01574             ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
01575       }
01576    } else {
01577       if (option_debug)
01578          ast_log(LOG_DEBUG, "No echo training requested\n");
01579    }
01580 }
01581 
01582 static void zt_disable_ec(struct zt_pvt *p)
01583 {
01584    int x;
01585    int res;
01586    if (p->echocancel) {
01587       x = 0;
01588       res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
01589       if (res)
01590          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
01591       else {
01592          if (option_debug)
01593             ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
01594       }
01595    }
01596    p->echocanon = 0;
01597 }
01598 
01599 static void fill_txgain(struct zt_gains *g, float gain, int law)
01600 {
01601    int j;
01602    int k;
01603    float linear_gain = pow(10.0, gain / 20.0);
01604 
01605    switch (law) {
01606    case ZT_LAW_ALAW:
01607       for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
01608          if (gain) {
01609             k = (int) (((float) AST_ALAW(j)) * linear_gain);
01610             if (k > 32767) k = 32767;
01611             if (k < -32767) k = -32767;
01612             g->txgain[j] = AST_LIN2A(k);
01613          } else {
01614             g->txgain[j] = j;
01615          }
01616       }
01617       break;
01618    case ZT_LAW_MULAW:
01619       for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
01620          if (gain) {
01621             k = (int) (((float) AST_MULAW(j)) * linear_gain);
01622             if (k > 32767) k = 32767;
01623             if (k < -32767) k = -32767;
01624             g->txgain[j] = AST_LIN2MU(k);
01625          } else {
01626             g->txgain[j] = j;
01627          }
01628       }
01629       break;
01630    }
01631 }
01632 
01633 static void fill_rxgain(struct zt_gains *g, float gain, int law)
01634 {
01635    int j;
01636    int k;
01637    float linear_gain = pow(10.0, gain / 20.0);
01638 
01639    switch (law) {
01640    case ZT_LAW_ALAW:
01641       for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
01642          if (gain) {
01643             k = (int) (((float) AST_ALAW(j)) * linear_gain);
01644             if (k > 32767) k = 32767;
01645             if (k < -32767) k = -32767;
01646             g->rxgain[j] = AST_LIN2A(k);
01647          } else {
01648             g->rxgain[j] = j;
01649          }
01650       }
01651       break;
01652    case ZT_LAW_MULAW:
01653       for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
01654          if (gain) {
01655             k = (int) (((float) AST_MULAW(j)) * linear_gain);
01656             if (k > 32767) k = 32767;
01657             if (k < -32767) k = -32767;
01658             g->rxgain[j] = AST_LIN2MU(k);
01659          } else {
01660             g->rxgain[j] = j;
01661          }
01662       }
01663       break;
01664    }
01665 }
01666 
01667 static int set_actual_txgain(int fd, int chan, float gain, int law)
01668 {
01669    struct zt_gains g;
01670    int res;
01671 
01672    memset(&g, 0, sizeof(g));
01673    g.chan = chan;
01674    res = ioctl(fd, ZT_GETGAINS, &g);
01675    if (res) {
01676       if (option_debug)
01677          ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
01678       return res;
01679    }
01680 
01681    fill_txgain(&g, gain, law);
01682 
01683    return ioctl(fd, ZT_SETGAINS, &g);
01684 }
01685 
01686 static int set_actual_rxgain(int fd, int chan, float gain, int law)
01687 {
01688    struct zt_gains g;
01689    int res;
01690 
01691    memset(&g, 0, sizeof(g));
01692    g.chan = chan;
01693    res = ioctl(fd, ZT_GETGAINS, &g);
01694    if (res) {
01695       if (option_debug)
01696          ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
01697       return res;
01698    }
01699 
01700    fill_rxgain(&g, gain, law);
01701 
01702    return ioctl(fd, ZT_SETGAINS, &g);
01703 }
01704 
01705 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
01706 {
01707    return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
01708 }
01709 
01710 static int bump_gains(struct zt_pvt *p)
01711 {
01712    int res;
01713 
01714    /* Bump receive gain by 5.0db */
01715    res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + 5.0, p->txgain, p->law);
01716    if (res) {
01717       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
01718       return -1;
01719    }
01720 
01721    return 0;
01722 }
01723 
01724 static int restore_gains(struct zt_pvt *p)
01725 {
01726    int res;
01727 
01728    res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
01729    if (res) {
01730       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
01731       return -1;
01732    }
01733 
01734    return 0;
01735 }
01736 
01737 static inline int zt_set_hook(int fd, int hs)
01738 {
01739    int x, res;
01740    x = hs;
01741    res = ioctl(fd, ZT_HOOK, &x);
01742    if (res < 0) 
01743    {
01744       if (errno == EINPROGRESS) return 0;
01745       ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
01746    }
01747    return res;
01748 }
01749 
01750 static inline int zt_confmute(struct zt_pvt *p, int muted)
01751 {
01752    int x, y, res;
01753    x = muted;
01754    if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
01755       y = 1;
01756       res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
01757       if (res)
01758          ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
01759    }
01760    res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
01761    if (res < 0)
01762       ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
01763    return res;
01764 }
01765 
01766 static int save_conference(struct zt_pvt *p)
01767 {
01768    struct zt_confinfo c;
01769    int res;
01770    if (p->saveconf.confmode) {
01771       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
01772       return -1;
01773    }
01774    p->saveconf.chan = 0;
01775    res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
01776    if (res) {
01777       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
01778       p->saveconf.confmode = 0;
01779       return -1;
01780    }
01781    c.chan = 0;
01782    c.confno = 0;
01783    c.confmode = ZT_CONF_NORMAL;
01784    res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
01785    if (res) {
01786       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
01787       return -1;
01788    }
01789    if (option_debug)
01790       ast_log(LOG_DEBUG, "Disabled conferencing\n");
01791    return 0;
01792 }
01793 
01794 static int restore_conference(struct zt_pvt *p)
01795 {
01796    int res;
01797    if (p->saveconf.confmode) {
01798       res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
01799       p->saveconf.confmode = 0;
01800       if (res) {
01801          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
01802          return -1;
01803       }
01804    }
01805    if (option_debug)
01806       ast_log(LOG_DEBUG, "Restored conferencing\n");
01807    return 0;
01808 }
01809 
01810 static int send_callerid(struct zt_pvt *p);
01811 
01812 static int send_cwcidspill(struct zt_pvt *p)
01813 {
01814    p->callwaitcas = 0;
01815    p->cidcwexpire = 0;
01816    if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
01817       return -1;
01818    p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
01819    /* Make sure we account for the end */
01820    p->cidlen += READ_SIZE * 4;
01821    p->cidpos = 0;
01822    send_callerid(p);
01823    if (option_verbose > 2)
01824       ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
01825    return 0;
01826 }
01827 
01828 static int has_voicemail(struct zt_pvt *p)
01829 {
01830 
01831    return ast_app_has_voicemail(p->mailbox, NULL);
01832 }
01833 
01834 static int send_callerid(struct zt_pvt *p)
01835 {
01836    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
01837    int res;
01838    /* Take out of linear mode if necessary */
01839    if (p->subs[SUB_REAL].linear) {
01840       p->subs[SUB_REAL].linear = 0;
01841       zt_setlinear(p->subs[SUB_REAL].zfd, 0);
01842    }
01843    while (p->cidpos < p->cidlen) {
01844       res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
01845       if (res < 0) {
01846          if (errno == EAGAIN)
01847             return 0;
01848          else {
01849             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
01850             return -1;
01851          }
01852       }
01853       if (!res)
01854          return 0;
01855       p->cidpos += res;
01856    }
01857    free(p->cidspill);
01858    p->cidspill = NULL;
01859    if (p->callwaitcas) {
01860       /* Wait for CID/CW to expire */
01861       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
01862    } else
01863       restore_conference(p);
01864    return 0;
01865 }
01866 
01867 static int zt_callwait(struct ast_channel *ast)
01868 {
01869    struct zt_pvt *p = ast->tech_pvt;
01870    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
01871    if (p->cidspill) {
01872       ast_log(LOG_WARNING, "Spill already exists?!?\n");
01873       free(p->cidspill);
01874    }
01875    if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
01876       return -1;
01877    save_conference(p);
01878    /* Silence */
01879    memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
01880    if (!p->callwaitrings && p->callwaitingcallerid) {
01881       ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
01882       p->callwaitcas = 1;
01883       p->cidlen = 2400 + 680 + READ_SIZE * 4;
01884    } else {
01885       ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
01886       p->callwaitcas = 0;
01887       p->cidlen = 2400 + READ_SIZE * 4;
01888    }
01889    p->cidpos = 0;
01890    send_callerid(p);
01891    
01892    return 0;
01893 }
01894 
01895 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
01896 {
01897    struct zt_pvt *p = ast->tech_pvt;
01898    int x, res, index,mysig;
01899    char *c, *n, *l;
01900 #ifdef HAVE_PRI
01901    char *s = NULL;
01902 #endif
01903    char dest[256]; /* must be same length as p->dialdest */
01904    ast_mutex_lock(&p->lock);
01905    ast_copy_string(dest, rdest, sizeof(dest));
01906    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
01907    if ((ast->_state == AST_STATE_BUSY)) {
01908       p->subs[SUB_REAL].needbusy = 1;
01909       ast_mutex_unlock(&p->lock);
01910       return 0;
01911    }
01912    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
01913       ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
01914       ast_mutex_unlock(&p->lock);
01915       return -1;
01916    }
01917    p->dialednone = 0;
01918    if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
01919    {
01920       /* Special pseudo -- automatically up */
01921       ast_setstate(ast, AST_STATE_UP); 
01922       ast_mutex_unlock(&p->lock);
01923       return 0;
01924    }
01925    x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
01926    res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
01927    if (res)
01928       ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
01929    p->outgoing = 1;
01930 
01931    set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
01932 
01933    mysig = p->sig;
01934    if (p->outsigmod > -1)
01935       mysig = p->outsigmod;
01936 
01937    switch (mysig) {
01938    case SIG_FXOLS:
01939    case SIG_FXOGS:
01940    case SIG_FXOKS:
01941       if (p->owner == ast) {
01942          /* Normal ring, on hook */
01943          
01944          /* Don't send audio while on hook, until the call is answered */
01945          p->dialing = 1;
01946          if (p->use_callerid) {
01947             /* Generate the Caller-ID spill if desired */
01948             if (p->cidspill) {
01949                ast_log(LOG_WARNING, "cidspill already exists??\n");
01950                free(p->cidspill);
01951             }
01952             p->callwaitcas = 0;
01953             if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
01954                p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
01955                p->cidpos = 0;
01956                send_callerid(p);
01957             }
01958          }
01959          /* Choose proper cadence */
01960          if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
01961             if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
01962                ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
01963             p->cidrings = cidrings[p->distinctivering - 1];
01964          } else {
01965             if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
01966                ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
01967             p->cidrings = p->sendcalleridafter;
01968          }
01969 
01970          /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
01971          c = strchr(dest, '/');
01972          if (c)
01973             c++;
01974          if (c && (strlen(c) < p->stripmsd)) {
01975             ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
01976             c = NULL;
01977          }
01978          if (c) {
01979             p->dop.op = ZT_DIAL_OP_REPLACE;
01980             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
01981             if (option_debug)
01982                ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
01983          } else {
01984             p->dop.dialstr[0] = '\0';
01985          }
01986          x = ZT_RING;
01987          if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
01988             ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
01989             ast_mutex_unlock(&p->lock);
01990             return -1;
01991          }
01992          p->dialing = 1;
01993       } else {
01994          /* Call waiting call */
01995          p->callwaitrings = 0;
01996          if (ast->cid.cid_num)
01997             ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
01998          else
01999             p->callwait_num[0] = '\0';
02000          if (ast->cid.cid_name)
02001             ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
02002          else
02003             p->callwait_name[0] = '\0';
02004          /* Call waiting tone instead */
02005          if (zt_callwait(ast)) {
02006             ast_mutex_unlock(&p->lock);
02007             return -1;
02008          }
02009          /* Make ring-back */
02010          if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
02011             ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
02012             
02013       }
02014       n = ast->cid.cid_name;
02015       l = ast->cid.cid_num;
02016       if (l)
02017          ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
02018       else
02019          p->lastcid_num[0] = '\0';
02020       if (n)
02021          ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
02022       else
02023          p->lastcid_name[0] = '\0';
02024       ast_setstate(ast, AST_STATE_RINGING);
02025       index = zt_get_index(ast, p, 0);
02026       if (index > -1) {
02027          p->subs[index].needringing = 1;
02028       }
02029       break;
02030    case SIG_FXSLS:
02031    case SIG_FXSGS:
02032    case SIG_FXSKS:
02033    case SIG_EMWINK:
02034    case SIG_EM:
02035    case SIG_EM_E1:
02036    case SIG_FEATD:
02037    case SIG_FEATDMF:
02038    case SIG_E911:
02039    case SIG_FGC_CAMA:
02040    case SIG_FGC_CAMAMF:
02041    case SIG_FEATB:
02042    case SIG_SFWINK:
02043    case SIG_SF:
02044    case SIG_SF_FEATD:
02045    case SIG_SF_FEATDMF:
02046    case SIG_FEATDMF_TA:
02047    case SIG_SF_FEATB:
02048       c = strchr(dest, '/');
02049       if (c)
02050          c++;
02051       else
02052          c = "";
02053       if (strlen(c) < p->stripmsd) {
02054          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
02055          ast_mutex_unlock(&p->lock);
02056          return -1;
02057       }
02058 #ifdef HAVE_PRI
02059       /* Start the trunk, if not GR-303 */
02060       if (!p->pri) {
02061 #endif
02062          x = ZT_START;
02063          res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
02064          if (res < 0) {
02065             if (errno != EINPROGRESS) {
02066                ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
02067                ast_mutex_unlock(&p->lock);
02068                return -1;
02069             }
02070          }
02071 #ifdef HAVE_PRI
02072       }
02073 #endif
02074       if (option_debug)
02075          ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
02076       p->dop.op = ZT_DIAL_OP_REPLACE;
02077 
02078       c += p->stripmsd;
02079 
02080       switch (mysig) {
02081       case SIG_FEATD:
02082          l = ast->cid.cid_num;
02083          if (l) 
02084             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
02085          else
02086             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
02087          break;
02088       case SIG_FEATDMF:
02089          l = ast->cid.cid_num;
02090          if (l) 
02091             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
02092          else
02093             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
02094          break;
02095       case SIG_FEATDMF_TA:
02096       {
02097          const char *cic, *ozz;
02098 
02099          /* If you have to go through a Tandem Access point you need to use this */
02100          ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
02101          if (!ozz)
02102             ozz = defaultozz;
02103          cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
02104          if (!cic)
02105             cic = defaultcic;
02106          if (!ozz || !cic) {
02107             ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
02108             ast_mutex_unlock(&p->lock);
02109             return -1;
02110          }
02111          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
02112          snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
02113          p->whichwink = 0;
02114       }
02115          break;
02116       case SIG_E911:
02117          ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
02118          break;
02119       case SIG_FGC_CAMA:
02120          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
02121          break;
02122       case SIG_FGC_CAMAMF:
02123       case SIG_FEATB:
02124          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
02125          break;
02126       default:
02127          if (p->pulse)
02128             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
02129          else
02130             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
02131          break;
02132       }
02133 
02134       if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
02135          memset(p->echorest, 'w', sizeof(p->echorest) - 1);
02136          strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
02137          p->echorest[sizeof(p->echorest) - 1] = '\0';
02138          p->echobreak = 1;
02139          p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
02140       } else
02141          p->echobreak = 0;
02142       if (!res) {
02143          if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
02144             x = ZT_ONHOOK;
02145             ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
02146             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
02147             ast_mutex_unlock(&p->lock);
02148             return -1;
02149          }
02150       } else {
02151          if (option_debug)
02152             ast_log(LOG_DEBUG, "Deferring dialing...\n");
02153       }
02154       p->dialing = 1;
02155       if (ast_strlen_zero(c))
02156          p->dialednone = 1;
02157       ast_setstate(ast, AST_STATE_DIALING);
02158       break;
02159    case 0:
02160       /* Special pseudo -- automatically up*/
02161       ast_setstate(ast, AST_STATE_UP);
02162       break;      
02163    case SIG_PRI:
02164    case SIG_SS7:
02165       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
02166       p->dialdest[0] = '\0';
02167       break;
02168    default:
02169       if (option_debug)
02170          ast_log(LOG_DEBUG, "not yet implemented\n");
02171       ast_mutex_unlock(&p->lock);
02172       return -1;
02173    }
02174 #ifdef HAVE_SS7
02175    if (p->ss7) {
02176       c = strchr(dest, '/');
02177       if (c)
02178          c++;
02179       else
02180          c = dest;
02181 
02182       if (!p->hidecallerid) {
02183          l = ast->cid.cid_num;
02184       } else {
02185          l = NULL;
02186       }
02187 
02188       ss7_grab(p, p->ss7);
02189       p->digital = IS_DIGITAL(ast->transfercapability);
02190       p->ss7call = isup_new_call(p->ss7->ss7);
02191 
02192       if (!p->ss7call) {
02193          ss7_rel(p->ss7);
02194          ast_mutex_unlock(&p->lock);
02195          ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
02196          return -1;
02197       }
02198 
02199       isup_init_call(p->ss7->ss7, p->ss7call, p->cic, c + p->stripmsd, l);
02200 
02201       isup_iam(p->ss7->ss7, p->ss7call);
02202       ss7_rel(p->ss7);
02203    }
02204 #endif /* HAVE_SS7 */
02205 #ifdef HAVE_PRI
02206    if (p->pri) {
02207       struct pri_sr *sr;
02208 #ifdef SUPPORT_USERUSER
02209       const char *useruser;
02210 #endif
02211       int pridialplan;
02212       int dp_strip;
02213       int prilocaldialplan;
02214       int ldp_strip;
02215       int exclusive;
02216       const char *rr_str;
02217       int redirect_reason;
02218 
02219       c = strchr(dest, '/');
02220       if (c)
02221          c++;
02222       else
02223          c = dest;
02224       if (!p->hidecalleridname)
02225          n = ast->cid.cid_name;
02226       else
02227          n = NULL;
02228       if (!p->hidecallerid) {
02229          l = ast->cid.cid_num;
02230          n = ast->cid.cid_name;
02231       } else {
02232          l = NULL;
02233          n = NULL;
02234       }
02235       if (strlen(c) < p->stripmsd) {
02236          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
02237          ast_mutex_unlock(&p->lock);
02238          return -1;
02239       }
02240       if (mysig != SIG_FXSKS) {
02241          p->dop.op = ZT_DIAL_OP_REPLACE;
02242          s = strchr(c + p->stripmsd, 'w');
02243          if (s) {
02244             if (strlen(s) > 1)
02245                snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
02246             else
02247                p->dop.dialstr[0] = '\0';
02248             *s = '\0';
02249          } else {
02250             p->dop.dialstr[0] = '\0';
02251          }
02252       }
02253       if (pri_grab(p, p->pri)) {
02254          ast_log(LOG_WARNING, "Failed to grab PRI!\n");
02255          ast_mutex_unlock(&p->lock);
02256          return -1;
02257       }
02258       if (!(p->call = pri_new_call(p->pri->pri))) {
02259          ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
02260          pri_rel(p->pri);
02261          ast_mutex_unlock(&p->lock);
02262          return -1;
02263       }
02264       if (!(sr = pri_sr_new())) {
02265          ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
02266          pri_rel(p->pri);
02267          ast_mutex_unlock(&p->lock);
02268       }
02269       if (p->bearer || (mysig == SIG_FXSKS)) {
02270          if (p->bearer) {
02271             if (option_debug)
02272                ast_log(LOG_DEBUG, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
02273             p->bearer->call = p->call;
02274          } else {
02275             if (option_debug)
02276                ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
02277          }
02278          pri_set_crv(p->pri->pri, p->call, p->channel, 0);
02279       }
02280       p->digital = IS_DIGITAL(ast->transfercapability);
02281       /* Add support for exclusive override */
02282       if (p->priexclusive)
02283          exclusive = 1;
02284       else {
02285       /* otherwise, traditional behavior */
02286          if (p->pri->nodetype == PRI_NETWORK)
02287             exclusive = 0;
02288          else
02289             exclusive = 1;
02290       }
02291       
02292       pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
02293       pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
02294                (p->digital ? -1 : 
02295                   ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
02296       if (p->pri->facilityenable)
02297          pri_facility_enable(p->pri->pri);
02298 
02299       if (option_verbose > 2)
02300          ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
02301       dp_strip = 0;
02302       pridialplan = p->pri->dialplan - 1;
02303       if (pridialplan == -2) { /* compute dynamically */
02304          if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
02305             dp_strip = strlen(p->pri->internationalprefix);
02306             pridialplan = PRI_INTERNATIONAL_ISDN;
02307          } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
02308             dp_strip = strlen(p->pri->nationalprefix);
02309             pridialplan = PRI_NATIONAL_ISDN;
02310          } else {
02311             pridialplan = PRI_LOCAL_ISDN;
02312          }
02313       }
02314       pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
02315 
02316       ldp_strip = 0;
02317       prilocaldialplan = p->pri->localdialplan - 1;
02318       if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
02319          if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
02320             ldp_strip = strlen(p->pri->internationalprefix);
02321             prilocaldialplan = PRI_INTERNATIONAL_ISDN;
02322          } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
02323             ldp_strip = strlen(p->pri->nationalprefix);
02324             prilocaldialplan = PRI_NATIONAL_ISDN;
02325          } else {
02326             prilocaldialplan = PRI_LOCAL_ISDN;
02327          }
02328       }
02329       pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
02330          p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
02331       if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
02332          if (!strcasecmp(rr_str, "UNKNOWN"))
02333             redirect_reason = 0;
02334          else if (!strcasecmp(rr_str, "BUSY"))
02335             redirect_reason = 1;
02336          else if (!strcasecmp(rr_str, "NO_REPLY"))
02337             redirect_reason = 2;
02338          else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
02339             redirect_reason = 15;
02340          else
02341             redirect_reason = PRI_REDIR_UNCONDITIONAL;
02342       } else
02343          redirect_reason = PRI_REDIR_UNCONDITIONAL;
02344       pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
02345 
02346 #ifdef SUPPORT_USERUSER
02347       /* User-user info */
02348       useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
02349 
02350       if (useruser)
02351          pri_sr_set_useruser(sr, useruser);
02352 #endif
02353 
02354       if (pri_setup(p->pri->pri, p->call, sr)) {
02355          ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
02356             c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
02357          pri_rel(p->pri);
02358          ast_mutex_unlock(&p->lock);
02359          pri_sr_free(sr);
02360          return -1;
02361       }
02362       pri_sr_free(sr);
02363       ast_setstate(ast, AST_STATE_DIALING);
02364       pri_rel(p->pri);
02365    }
02366 #endif      
02367    ast_mutex_unlock(&p->lock);
02368    return 0;
02369 }
02370 
02371 static void destroy_zt_pvt(struct zt_pvt **pvt)
02372 {
02373    struct zt_pvt *p = *pvt;
02374    /* Remove channel from the list */
02375    if (p->prev)
02376       p->prev->next = p->next;
02377    if (p->next)
02378       p->next->prev = p->prev;
02379    if (p->use_smdi)
02380       ASTOBJ_UNREF(p->smdi_iface, ast_smdi_interface_destroy);
02381    ast_mutex_destroy(&p->lock);
02382    free(p);
02383    *pvt = NULL;
02384 }
02385 
02386 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
02387 {
02388    int owned = 0;
02389    int i = 0;
02390 
02391    if (!now) {
02392       if (cur->owner) {
02393          owned = 1;
02394       }
02395 
02396       for (i = 0; i < 3; i++) {
02397          if (cur->subs[i].owner) {
02398             owned = 1;
02399          }
02400       }
02401       if (!owned) {
02402          if (prev) {
02403             prev->next = cur->next;
02404             if (prev->next)
02405                prev->next->prev = prev;
02406             else
02407                ifend = prev;
02408          } else {
02409             iflist = cur->next;
02410             if (iflist)
02411                iflist->prev = NULL;
02412             else
02413                ifend = NULL;
02414          }
02415          if (cur->subs[SUB_REAL].zfd > -1) {
02416             zt_close(cur->subs[SUB_REAL].zfd);
02417          }
02418          destroy_zt_pvt(&cur);
02419       }
02420    } else {
02421       if (prev) {
02422          prev->next = cur->next;
02423          if (prev->next)
02424             prev->next->prev = prev;
02425          else
02426             ifend = prev;
02427       } else {
02428          iflist = cur->next;
02429          if (iflist)
02430             iflist->prev = NULL;
02431          else
02432             ifend = NULL;
02433       }
02434       if (cur->subs[SUB_REAL].zfd > -1) {
02435          zt_close(cur->subs[SUB_REAL].zfd);
02436       }
02437       destroy_zt_pvt(&cur);
02438    }
02439    return 0;
02440 }
02441 
02442 #ifdef HAVE_PRI
02443 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
02444 
02445 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
02446 
02447 static char *zap_send_keypad_facility_descrip = 
02448 "  ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
02449 "  IE over the current channel.\n";
02450 
02451 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
02452 {
02453    /* Data will be our digit string */
02454    struct zt_pvt *p;
02455    char *digits = (char *) data;
02456 
02457    if (ast_strlen_zero(digits)) {
02458       if (option_debug)
02459          ast_log(LOG_DEBUG, "No digit string sent to application!\n");
02460       return -1;
02461    }
02462 
02463    p = (struct zt_pvt *)chan->tech_pvt;
02464 
02465    if (!p) {
02466       if (option_debug)
02467          ast_log(LOG_DEBUG, "Unable to find technology private\n");
02468       return -1;
02469    }
02470 
02471    ast_mutex_lock(&p->lock);
02472 
02473    if (!p->pri || !p->call) {
02474       if (option_debug)
02475          ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
02476       ast_mutex_unlock(&p->lock);
02477       return -1;
02478    }
02479 
02480    if (!pri_grab(p, p->pri)) {
02481       pri_keypad_facility(p->pri->pri, p->call, digits);
02482       pri_rel(p->pri);
02483    } else {
02484       if (option_debug)
02485          ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
02486       ast_mutex_unlock(&p->lock);
02487       return -1;
02488    }
02489 
02490    ast_mutex_unlock(&p->lock);
02491 
02492    return 0;
02493 }
02494 
02495 static int pri_is_up(struct zt_pri *pri)
02496 {
02497    int x;
02498    for (x = 0; x < NUM_DCHANS; x++) {
02499       if (pri->dchanavail[x] == DCHAN_AVAILABLE)
02500          return 1;
02501    }
02502    return 0;
02503 }
02504 
02505 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
02506 {
02507    bearer->owner = &inuse;
02508    bearer->realcall = crv;
02509    crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
02510    if (crv->subs[SUB_REAL].owner)
02511       crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
02512    crv->bearer = bearer;
02513    crv->call = bearer->call;
02514    crv->pri = pri;
02515    return 0;
02516 }
02517 
02518 static char *pri_order(int level)
02519 {
02520    switch (level) {
02521    case 0:
02522       return "Primary";
02523    case 1:
02524       return "Secondary";
02525    case 2:
02526       return "Tertiary";
02527    case 3:
02528       return "Quaternary";
02529    default:
02530       return "<Unknown>";
02531    }     
02532 }
02533 
02534 /* Returns fd of the active dchan */
02535 static int pri_active_dchan_fd(struct zt_pri *pri)
02536 {
02537    int x = -1;
02538 
02539    for (x = 0; x < NUM_DCHANS; x++) {
02540       if ((pri->dchans[x] == pri->pri))
02541          break;
02542    }
02543 
02544    return pri->fds[x];
02545 }
02546 
02547 static int pri_find_dchan(struct zt_pri *pri)
02548 {
02549    int oldslot = -1;
02550    struct pri *old;
02551    int newslot = -1;
02552    int x;
02553    old = pri->pri;
02554    for (x = 0; x < NUM_DCHANS; x++) {
02555       if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
02556          newslot = x;
02557       if (pri->dchans[x] == old) {
02558          oldslot = x;
02559       }
02560    }
02561    if (newslot < 0) {
02562       newslot = 0;
02563       ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
02564          pri->dchannels[newslot]);
02565    }
02566    if (old && (oldslot != newslot))
02567       ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
02568          pri->dchannels[oldslot], pri->dchannels[newslot]);
02569    pri->pri = pri->dchans[newslot];
02570    return 0;
02571 }
02572 #endif
02573 
02574 static int zt_hangup(struct ast_channel *ast)
02575 {
02576    int res;
02577    int index,x, law;
02578    /*static int restore_gains(struct zt_pvt *p);*/
02579    struct zt_pvt *p = ast->tech_pvt;
02580    struct zt_pvt *tmp = NULL;
02581    struct zt_pvt *prev = NULL;
02582    ZT_PARAMS par;
02583 
02584    if (option_debug)
02585       ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
02586    if (!ast->tech_pvt) {
02587       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
02588       return 0;
02589    }
02590    
02591    ast_mutex_lock(&p->lock);
02592    
02593    index = zt_get_index(ast, p, 1);
02594 
02595    if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
02596       x = 1;
02597       ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
02598    }
02599 
02600    x = 0;
02601    zt_confmute(p, 0);
02602    restore_gains(p);
02603    if (p->origcid_num) {
02604       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
02605       free(p->origcid_num);
02606       p->origcid_num = NULL;
02607    }  
02608    if (p->origcid_name) {
02609       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
02610       free(p->origcid_name);
02611       p->origcid_name = NULL;
02612    }  
02613    if (p->dsp)
02614       ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
02615    if (p->exten)
02616       p->exten[0] = '\0';
02617 
02618    if (option_debug)
02619       ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
02620          p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
02621    p->ignoredtmf = 0;
02622    
02623    if (index > -1) {
02624       /* Real channel, do some fixup */
02625       p->subs[index].owner = NULL;
02626       p->subs[index].needanswer = 0;
02627       p->subs[index].needflash = 0;
02628       p->subs[index].needringing = 0;
02629       p->subs[index].needbusy = 0;
02630       p->subs[index].needcongestion = 0;
02631       p->subs[index].linear = 0;
02632       p->subs[index].needcallerid = 0;
02633       p->polarity = POLARITY_IDLE;
02634       zt_setlinear(p->subs[index].zfd, 0);
02635       if (index == SUB_REAL) {
02636          if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
02637             if (option_debug)
02638                ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
02639             if (p->subs[SUB_CALLWAIT].inthreeway) {
02640                /* We had flipped over to answer a callwait and now it's gone */
02641                if (option_debug)
02642                   ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
02643                /* Move to the call-wait, but un-own us until they flip back. */
02644                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
02645                unalloc_sub(p, SUB_CALLWAIT);
02646                p->owner = NULL;
02647             } else {
02648                /* The three way hung up, but we still have a call wait */
02649                if (option_debug)
02650                   ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
02651                swap_subs(p, SUB_THREEWAY, SUB_REAL);
02652                unalloc_sub(p, SUB_THREEWAY);
02653                if (p->subs[SUB_REAL].inthreeway) {
02654                   /* This was part of a three way call.  Immediately make way for
02655                      another call */
02656                   if (option_debug)
02657                      ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
02658                   p->owner = p->subs[SUB_REAL].owner;
02659                } else {
02660                   /* This call hasn't been completed yet...  Set owner to NULL */
02661                   if (option_debug)
02662                      ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
02663                   p->owner = NULL;
02664                }
02665                p->subs[SUB_REAL].inthreeway = 0;
02666             }
02667          } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
02668             /* Move to the call-wait and switch back to them. */
02669             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
02670             unalloc_sub(p, SUB_CALLWAIT);
02671             p->owner = p->subs[SUB_REAL].owner;
02672             if (p->owner->_state != AST_STATE_UP)
02673                p->subs[SUB_REAL].needanswer = 1;
02674             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
02675                ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
02676          } else if (p->subs[SUB_THREEWAY].zfd > -1) {
02677             swap_subs(p, SUB_THREEWAY, SUB_REAL);
02678             unalloc_sub(p, SUB_THREEWAY);
02679             if (p->subs[SUB_REAL].inthreeway) {
02680                /* This was part of a three way call.  Immediately make way for
02681                   another call */
02682                if (option_debug)
02683                   ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
02684                p->owner = p->subs[SUB_REAL].owner;
02685             } else {
02686                /* This call hasn't been completed yet...  Set owner to NULL */
02687                if (option_debug)
02688                   ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
02689                p->owner = NULL;
02690             }
02691             p->subs[SUB_REAL].inthreeway = 0;
02692          }
02693       } else if (index == SUB_CALLWAIT) {
02694          /* Ditch the holding callwait call, and immediately make it availabe */
02695          if (p->subs[SUB_CALLWAIT].inthreeway) {
02696             /* This is actually part of a three way, placed on hold.  Place the third part
02697                on music on hold now */
02698             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
02699                ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD, 
02700                   S_OR(p->mohsuggest, NULL),
02701                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
02702             }
02703             p->subs[SUB_THREEWAY].inthreeway = 0;
02704             /* Make it the call wait now */
02705             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
02706             unalloc_sub(p, SUB_THREEWAY);
02707          } else
02708             unalloc_sub(p, SUB_CALLWAIT);
02709       } else if (index == SUB_THREEWAY) {
02710          if (p->subs[SUB_CALLWAIT].inthreeway) {
02711             /* The other party of the three way call is currently in a call-wait state.
02712                Start music on hold for them, and take the main guy out of the third call */
02713             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
02714                ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD, 
02715                   S_OR(p->mohsuggest, NULL),
02716                   !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
02717             }
02718             p->subs[SUB_CALLWAIT].inthreeway = 0;
02719          }
02720          p->subs[SUB_REAL].inthreeway = 0;
02721          /* If this was part of a three way call index, let us make
02722             another three way call */
02723          unalloc_sub(p, SUB_THREEWAY);
02724       } else {
02725          /* This wasn't any sort of call, but how are we an index? */
02726          ast_log(LOG_WARNING, "Index found but not any type of call?\n");
02727       }
02728    }
02729 
02730    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
02731       p->owner = NULL;
02732       p->ringt = 0;
02733       p->distinctivering = 0;
02734       p->confirmanswer = 0;
02735       p->cidrings = 1;
02736       p->outgoing = 0;
02737       p->digital = 0;
02738       p->faxhandled = 0;
02739       p->pulsedial = 0;
02740       p->onhooktime = time(NULL);
02741 #ifdef HAVE_PRI
02742       p->proceeding = 0;
02743       p->progress = 0;
02744       p->alerting = 0;
02745       p->setup_ack = 0;
02746 #endif      
02747       if (p->dsp) {
02748          ast_dsp_free(p->dsp);
02749          p->dsp = NULL;
02750       }
02751 
02752       law = ZT_LAW_DEFAULT;
02753       res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
02754       if (res < 0) 
02755          ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
02756       /* Perform low level hangup if no owner left */
02757 #ifdef HAVE_SS7
02758       if (p->ss7) {
02759          if (p->ss7call) {
02760             if (!ss7_grab(p, p->ss7)) {
02761                if (!p->alreadyhungup) {
02762                   isup_rel(p->ss7->ss7, p->ss7call, ast->hangupcause ? ast->hangupcause : -1);
02763                   ss7_rel(p->ss7);
02764                   p->alreadyhungup = 1;
02765                } else
02766                   ast_log(LOG_WARNING, "Trying to hangup twice!\n");
02767             } else {
02768                ast_log(LOG_WARNING, "Unable to grab SS7 on CIC %d\n", p->cic);
02769                res = -1;
02770             }
02771          }
02772       }
02773 #endif
02774 #ifdef HAVE_PRI
02775       if (p->pri) {
02776 #ifdef SUPPORT_USERUSER
02777          const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
02778 #endif
02779 
02780          /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
02781          if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
02782             if (!pri_grab(p, p->pri)) {
02783                if (p->alreadyhungup) {
02784                   if (option_debug)
02785                      ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
02786 
02787 #ifdef SUPPORT_USERUSER
02788                   pri_call_set_useruser(p->call, useruser);
02789 #endif
02790 
02791                   pri_hangup(p->pri->pri, p->call, -1);
02792                   p->call = NULL;
02793                   if (p->bearer) 
02794                      p->bearer->call = NULL;
02795                } else {
02796                   const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
02797                   int icause = ast->hangupcause ? ast->hangupcause : -1;
02798                   if (option_debug)
02799                      ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
02800 
02801 #ifdef SUPPORT_USERUSER
02802                   pri_call_set_useruser(p->call, useruser);
02803 #endif
02804 
02805                   p->alreadyhungup = 1;
02806                   if (p->bearer)
02807                      p->bearer->alreadyhungup = 1;
02808                   if (cause) {
02809                      if (atoi(cause))
02810                         icause = atoi(cause);
02811                   }
02812                   pri_hangup(p->pri->pri, p->call, icause);
02813                }
02814                if (res < 0) 
02815                   ast_log(LOG_WARNING, "pri_disconnect failed\n");
02816                pri_rel(p->pri);        
02817             } else {
02818                ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
02819                res = -1;
02820             }
02821          } else {
02822             if (p->bearer)
02823                if (option_debug)
02824                   ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
02825             p->call = NULL;
02826             res = 0;
02827          }
02828       }
02829 #endif
02830       if (p->sig && ((p->sig != SIG_PRI) && (p->sig != SIG_SS7)))
02831          res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
02832       if (res < 0) {
02833          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
02834       }
02835       switch (p->sig) {
02836       case SIG_FXOGS:
02837       case SIG_FXOLS:
02838       case SIG_FXOKS:
02839          res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
02840          if (!res) {
02841 #if 0
02842             if (option_debug)
02843                ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
02844 #endif
02845             /* If they're off hook, try playing congestion */
02846             if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
02847                tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
02848             else
02849                tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
02850          }
02851          break;
02852       case SIG_FXSGS:
02853       case SIG_FXSLS:
02854       case SIG_FXSKS:
02855          /* Make sure we're not made available for at least two seconds assuming
02856             we were actually used for an inbound or outbound call. */
02857          if (ast->_state != AST_STATE_RESERVED) {
02858             time(&p->guardtime);
02859             p->guardtime += 2;
02860          }
02861          break;
02862       default:
02863          tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
02864       }
02865       if (p->cidspill)
02866          free(p->cidspill);
02867       if (p->sig)
02868          zt_disable_ec(p);
02869       x = 0;
02870       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
02871       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
02872       p->didtdd = 0;
02873       p->cidspill = NULL;
02874       p->callwaitcas = 0;
02875       p->callwaiting = p->permcallwaiting;
02876       p->hidecallerid = p->permhidecallerid;
02877       p->dialing = 0;
02878       p->rdnis[0] = '\0';
02879       update_conf(p);
02880       reset_conf(p);
02881       /* Restore data mode */
02882       if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
02883          x = 0;
02884          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
02885       }
02886 #ifdef HAVE_PRI
02887       if (p->bearer) {
02888          if (option_debug)
02889             ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
02890          /* Free up the bearer channel as well, and
02891             don't use its file descriptor anymore */
02892          update_conf(p->bearer);
02893          reset_conf(p->bearer);
02894          p->bearer->owner = NULL;
02895          p->bearer->realcall = NULL;
02896          p->bearer = NULL;
02897          p->subs[SUB_REAL].zfd = -1;
02898          p->pri = NULL;
02899       }
02900 #endif
02901       restart_monitor();
02902    }
02903 
02904    p->callwaitingrepeat = 0;
02905    p->cidcwexpire = 0;
02906    p->oprmode = 0;
02907    ast->tech_pvt = NULL;
02908    ast_mutex_unlock(&p->lock);
02909    ast_module_unref(ast_module_info->self);
02910    if (option_verbose > 2) 
02911       ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
02912 
02913    ast_mutex_lock(&iflock);
02914    tmp = iflist;
02915    prev = NULL;
02916    if (p->destroy) {
02917       while (tmp) {
02918          if (tmp == p) {
02919             destroy_channel(prev, tmp, 0);
02920             break;
02921          } else {
02922             prev = tmp;
02923             tmp = tmp->next;
02924          }
02925       }
02926    }
02927    ast_mutex_unlock(&iflock);
02928    return 0;
02929 }
02930 
02931 static int zt_answer(struct ast_channel *ast)
02932 {
02933    struct zt_pvt *p = ast->tech_pvt;
02934    int res = 0;
02935    int index;
02936    int oldstate = ast->_state;
02937    ast_setstate(ast, AST_STATE_UP);
02938    ast_mutex_lock(&p->lock);
02939    index = zt_get_index(ast, p, 0);
02940    if (index < 0)
02941       index = SUB_REAL;
02942    /* nothing to do if a radio channel */
02943    if ((p->radio || (p->oprmode < 0))) {
02944       ast_mutex_unlock(&p->lock);
02945       return 0;
02946    }
02947    switch (p->sig) {
02948    case SIG_FXSLS:
02949    case SIG_FXSGS:
02950    case SIG_FXSKS:
02951       p->ringt = 0;
02952       /* Fall through */
02953    case SIG_EM:
02954    case SIG_EM_E1:
02955    case SIG_EMWINK:
02956    case SIG_FEATD:
02957    case SIG_FEATDMF:
02958    case SIG_FEATDMF_TA:
02959    case SIG_E911:
02960    case SIG_FGC_CAMA:
02961    case SIG_FGC_CAMAMF:
02962    case SIG_FEATB:
02963    case SIG_SF:
02964    case SIG_SFWINK:
02965    case SIG_SF_FEATD:
02966    case SIG_SF_FEATDMF:
02967    case SIG_SF_FEATB:
02968    case SIG_FXOLS:
02969    case SIG_FXOGS:
02970    case SIG_FXOKS:
02971       /* Pick up the line */
02972       if (option_debug)
02973          ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
02974       if (p->hanguponpolarityswitch) {
02975          gettimeofday(&p->polaritydelaytv, NULL);
02976       }
02977       res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
02978       tone_zone_play_tone(p->subs[index].zfd, -1);
02979       p->dialing = 0;
02980       if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
02981          if (oldstate == AST_STATE_RINGING) {
02982             if (option_debug)
02983                ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
02984             tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
02985             swap_subs(p, SUB_THREEWAY, SUB_REAL);
02986             p->owner = p->subs[SUB_REAL].owner;
02987          }
02988       }
02989       if (p->sig & __ZT_SIG_FXS) {
02990          zt_enable_ec(p);
02991          zt_train_ec(p);
02992       }
02993       break;
02994 #ifdef HAVE_PRI
02995    case SIG_PRI:
02996       /* Send a pri acknowledge */
02997       if (!pri_grab(p, p->pri)) {
02998          p->proceeding = 1;
02999          res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
03000          pri_rel(p->pri);
03001       } else {
03002          ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
03003          res = -1;
03004       }
03005       break;
03006 #endif
03007 #ifdef HAVE_SS7
03008    case SIG_SS7:
03009       if (!ss7_grab(p, p->ss7)) {
03010          p->proceeding = 1;
03011          res = isup_anm(p->ss7->ss7, p->ss7call);
03012          ss7_rel(p->ss7);
03013       } else {
03014          ast_log(LOG_WARNING, "Unable to grab SS7 on span %d\n", p->span);
03015          res = -1;
03016       }
03017       break;
03018 #endif
03019    case 0:
03020       ast_mutex_unlock(&p->lock);
03021       return 0;
03022    default:
03023       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
03024       res = -1;
03025    }
03026    ast_mutex_unlock(&p->lock);
03027    return res;
03028 }
03029 
03030 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
03031 {
03032    char *cp;
03033    signed char *scp;
03034    int x;
03035    int index;
03036    struct zt_pvt *p = chan->tech_pvt, *pp;
03037    struct oprmode *oprmode;
03038    
03039 
03040    /* all supported options require data */
03041    if (!data || (datalen < 1)) {
03042       errno = EINVAL;
03043       return -1;
03044    }
03045 
03046    switch (option) {
03047    case AST_OPTION_TXGAIN:
03048       scp = (signed char *) data;
03049       index = zt_get_index(chan, p, 0);
03050       if (index < 0) {
03051          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
03052          return -1;
03053       }
03054       if (option_debug)
03055          ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
03056       return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
03057    case AST_OPTION_RXGAIN:
03058       scp = (signed char *) data;
03059       index = zt_get_index(chan, p, 0);
03060       if (index < 0) {
03061          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
03062          return -1;
03063       }
03064       if (option_debug)
03065          ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
03066       return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
03067    case AST_OPTION_TONE_VERIFY:
03068       if (!p->dsp)
03069          break;
03070       cp = (char *) data;
03071       switch (*cp) {
03072       case 1:
03073          if (option_debug)
03074             ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
03075          ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
03076          break;
03077       case 2:
03078          if (option_debug)
03079             ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
03080          ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
03081          break;
03082       default:
03083          if (option_debug)
03084             ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
03085          ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
03086          break;
03087       }
03088       break;
03089    case AST_OPTION_TDD:
03090       /* turn on or off TDD */
03091       cp = (char *) data;
03092       p->mate = 0;
03093       if (!*cp) { /* turn it off */
03094          if (option_debug)
03095             ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
03096          if (p->tdd)
03097             tdd_free(p->tdd);
03098          p->tdd = 0;
03099          break;
03100       }
03101       if (option_debug)
03102          ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
03103             (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
03104       zt_disable_ec(p);
03105       /* otherwise, turn it on */
03106       if (!p->didtdd) { /* if havent done it yet */
03107          unsigned char mybuf[41000], *buf;
03108          int size, res, fd, len;
03109          struct pollfd fds[1];
03110 
03111          buf = mybuf;
03112          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
03113          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
03114          len = 40000;
03115          index = zt_get_index(chan, p, 0);
03116          if (index < 0) {
03117             ast_log(LOG_WARNING, "No index in TDD?\n");
03118             return -1;
03119          }
03120          fd = p->subs[index].zfd;
03121          while (len) {
03122             if (ast_check_hangup(chan))
03123                return -1;
03124             size = len;
03125             if (size > READ_SIZE)
03126                size = READ_SIZE;
03127             fds[0].fd = fd;
03128             fds[0].events = POLLPRI | POLLOUT;
03129             fds[0].revents = 0;
03130             res = poll(fds, 1, -1);
03131             if (!res) {
03132                if (option_debug)
03133                   ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
03134                continue;
03135             }
03136             /* if got exception */
03137             if (fds[0].revents & POLLPRI)
03138                return -1;
03139             if (!(fds[0].revents & POLLOUT)) {
03140                if (option_debug)
03141                   ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
03142                continue;
03143             }
03144             res = write(fd, buf, size);
03145             if (res != size) {
03146                if (res == -1) return -1;
03147                if (option_debug)
03148                   ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
03149                break;
03150             }
03151             len -= size;
03152             buf += size;
03153          }
03154          p->didtdd = 1; /* set to have done it now */    
03155       }
03156       if (*cp == 2) { /* Mate mode */
03157          if (p->tdd)
03158             tdd_free(p->tdd);
03159          p->tdd = 0;
03160          p->mate = 1;
03161          break;
03162       }     
03163       if (!p->tdd) { /* if we dont have one yet */
03164          p->tdd = tdd_new(); /* allocate one */
03165       }     
03166       break;
03167    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
03168       if (!p->dsp)
03169          break;
03170       cp = (char *) data;
03171       if (option_debug)
03172          ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
03173             *cp ? "ON" : "OFF", (int) *cp, chan->name);
03174       ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
03175       break;
03176    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
03177       cp = (char *) data;
03178       if (!*cp) {    
03179          if (option_debug)
03180             ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
03181          x = 0;
03182          zt_disable_ec(p);
03183       } else {    
03184          if (option_debug)
03185             ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
03186          x = 1;
03187       }
03188       if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
03189          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
03190       break;
03191    case AST_OPTION_OPRMODE:  /* Operator services mode */
03192       oprmode = (struct oprmode *) data;
03193       pp = oprmode->peer->tech_pvt;
03194       p->oprmode = pp->oprmode = 0;
03195       /* setup peers */
03196       p->oprpeer = pp;
03197       pp->oprpeer = p;
03198       /* setup modes, if any */
03199       if (oprmode->mode) 
03200       {
03201          pp->oprmode = oprmode->mode;
03202          p->oprmode = -oprmode->mode;
03203       }
03204       if (option_debug)
03205          ast_log(LOG_DEBUG, "Set Operator Services mode, value: %d on %s/%s\n",
03206             oprmode->mode, chan->name,oprmode->peer->name);
03207       break;
03208    case AST_OPTION_ECHOCAN:
03209       cp = (char *) data;
03210       if (*cp) {
03211          if (option_debug)
03212             ast_log(LOG_DEBUG, "Enabling echo cancelation on %s\n", chan->name);
03213          zt_enable_ec(p);
03214       } else {
03215          if (option_debug)
03216             ast_log(LOG_DEBUG, "Disabling echo cancelation on %s\n", chan->name);
03217          zt_disable_ec(p);
03218       }
03219       break;
03220    }
03221    errno = 0;
03222 
03223    return 0;
03224 }
03225 
03226 static int zt_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
03227 {
03228    struct zt_pvt *p = chan->tech_pvt;
03229    
03230    if (!strcasecmp(data, "rxgain")) {
03231       ast_mutex_lock(&p->lock);
03232       snprintf(buf, len, "%f", p->rxgain);
03233       ast_mutex_unlock(&p->lock);   
03234    } else if (!strcasecmp(data, "txgain")) {
03235       ast_mutex_lock(&p->lock);
03236       snprintf(buf, len, "%f", p->txgain);
03237       ast_mutex_unlock(&p->lock);   
03238    } else {
03239       ast_copy_string(buf, "", len);
03240    }
03241    return 0;
03242 }
03243 
03244 
03245 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
03246 {
03247    /* Unlink a specific slave or all slaves/masters from a given master */
03248    int x;
03249    int hasslaves;
03250    if (!master)
03251       return;
03252    if (needlock) {
03253       ast_mutex_lock(&master->lock);
03254       if (slave) {
03255          while (ast_mutex_trylock(&slave->lock)) {
03256             ast_mutex_unlock(&master->lock);
03257             usleep(1);
03258             ast_mutex_lock(&master->lock);
03259          }
03260       }
03261    }
03262    hasslaves = 0;
03263    for (x = 0; x < MAX_SLAVES; x++) {
03264       if (master->slaves[x]) {
03265          if (!slave || (master->slaves[x] == slave)) {
03266             /* Take slave out of the conference */
03267             if (option_debug)
03268                ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
03269             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
03270             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
03271             master->slaves[x]->master = NULL;
03272             master->slaves[x] = NULL;
03273          } else
03274             hasslaves = 1;
03275       }
03276       if (!hasslaves)
03277          master->inconference = 0;
03278    }
03279    if (!slave) {
03280       if (master->master) {
03281          /* Take master out of the conference */
03282          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
03283          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
03284          hasslaves = 0;
03285          for (x = 0; x < MAX_SLAVES; x++) {
03286             if (master->master->slaves[x] == master)
03287                master->master->slaves[x] = NULL;
03288             else if (master->master->slaves[x])
03289                hasslaves = 1;
03290          }
03291          if (!hasslaves)
03292             master->master->inconference = 0;
03293       }
03294       master->master = NULL;
03295    }
03296    update_conf(master);
03297    if (needlock) {
03298       if (slave)
03299          ast_mutex_unlock(&slave->lock);
03300       ast_mutex_unlock(&master->lock);
03301    }
03302 }
03303 
03304 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
03305    int x;
03306    if (!slave || !master) {
03307       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
03308       return;
03309    }
03310    for (x = 0; x < MAX_SLAVES; x++) {
03311       if (!master->slaves[x]) {
03312          master->slaves[x] = slave;
03313          break;
03314       }
03315    }
03316    if (x >= MAX_SLAVES) {
03317       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
03318       master->slaves[MAX_SLAVES - 1] = slave;
03319    }
03320    if (slave->master) 
03321       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
03322    slave->master = master;
03323    
03324    if (option_debug)
03325       ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
03326 }
03327 
03328 static void disable_dtmf_detect(struct zt_pvt *p)
03329 {
03330 #ifdef ZT_TONEDETECT
03331    int val;
03332 #endif
03333 
03334    p->ignoredtmf = 1;
03335 
03336 #ifdef ZT_TONEDETECT
03337    val = 0;
03338    ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
03339 #endif      
03340    if (!p->hardwaredtmf && p->dsp) {
03341       p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
03342       ast_dsp_set_features(p->dsp, p->dsp_features);
03343    }
03344 }
03345 
03346 static void enable_dtmf_detect(struct zt_pvt *p)
03347 {
03348 #ifdef ZT_TONEDETECT
03349    int val;
03350 #endif
03351 
03352    if (p->channel == CHAN_PSEUDO)
03353       return;
03354 
03355    p->ignoredtmf = 0;
03356 
03357 #ifdef ZT_TONEDETECT
03358    val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
03359    ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
03360 #endif      
03361    if (!p->hardwaredtmf && p->dsp) {
03362       p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
03363       ast_dsp_set_features(p->dsp, p->dsp_features);
03364    }
03365 }
03366 
03367 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
03368 {
03369    struct ast_channel *who;
03370    struct zt_pvt *p0, *p1, *op0, *op1;
03371    struct zt_pvt *master = NULL, *slave = NULL;
03372    struct ast_frame *f;
03373    int inconf = 0;
03374    int nothingok = 1;
03375    int ofd0, ofd1;
03376    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
03377    int os0 = -1, os1 = -1;
03378    int priority = 0;
03379    struct ast_channel *oc0, *oc1;
03380    enum ast_bridge_result res;
03381 
03382 #ifdef PRI_2BCT
03383    int triedtopribridge = 0;
03384    q931_call *q931c0 = NULL, *q931c1 = NULL;
03385 #endif
03386 
03387    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
03388       There is code below to handle it properly until DTMF is actually seen,
03389       but due to currently unresolved issues it's ignored...
03390    */
03391 
03392    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
03393       return AST_BRIDGE_FAILED_NOWARN;
03394 
03395    ast_mutex_lock(&c0->lock);
03396    ast_mutex_lock(&c1->lock);
03397 
03398    p0 = c0->tech_pvt;
03399    p1 = c1->tech_pvt;
03400    /* cant do pseudo-channels here */
03401    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
03402       ast_mutex_unlock(&c0->lock);
03403       ast_mutex_unlock(&c1->lock);
03404       return AST_BRIDGE_FAILED_NOWARN;
03405    }
03406 
03407    oi0 = zt_get_index(c0, p0, 0);
03408    oi1 = zt_get_index(c1, p1, 0);
03409    if ((oi0 < 0) || (oi1 < 0)) {
03410       ast_mutex_unlock(&c0->lock);
03411       ast_mutex_unlock(&c1->lock);
03412       return AST_BRIDGE_FAILED;
03413    }
03414 
03415    op0 = p0 = c0->tech_pvt;
03416    op1 = p1 = c1->tech_pvt;
03417    ofd0 = c0->fds[0];
03418    ofd1 = c1->fds[0];
03419    oc0 = p0->owner;
03420    oc1 = p1->owner;
03421 
03422    if (ast_mutex_trylock(&p0->lock)) {
03423       /* Don't block, due to potential for deadlock */
03424       ast_mutex_unlock(&c0->lock);
03425       ast_mutex_unlock(&c1->lock);
03426       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
03427       return AST_BRIDGE_RETRY;
03428    }
03429    if (ast_mutex_trylock(&p1->lock)) {
03430       /* Don't block, due to potential for deadlock */
03431       ast_mutex_unlock(&p0->lock);
03432       ast_mutex_unlock(&c0->lock);
03433       ast_mutex_unlock(&c1->lock);
03434       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
03435       return AST_BRIDGE_RETRY;
03436    }
03437 
03438    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
03439       if (p0->owner && p1->owner) {
03440          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
03441          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
03442             master = p0;
03443             slave = p1;
03444             inconf = 1;
03445          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
03446             master = p1;
03447             slave = p0;
03448             inconf = 1;
03449          } else {
03450             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
03451             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
03452                p0->channel,
03453                oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
03454                p0->subs[SUB_REAL].inthreeway, p0->channel,
03455                oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
03456                p1->subs[SUB_REAL].inthreeway);
03457          }
03458          nothingok = 0;
03459       }
03460    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
03461       if (p1->subs[SUB_THREEWAY].inthreeway) {
03462          master = p1;
03463          slave = p0;
03464          nothingok = 0;
03465       }
03466    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
03467       if (p0->subs[SUB_THREEWAY].inthreeway) {
03468          master = p0;
03469          slave = p1;
03470          nothingok = 0;
03471       }
03472    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
03473       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
03474          don't put us in anything */
03475       if (p1->subs[SUB_CALLWAIT].inthreeway) {
03476          master = p1;
03477          slave = p0;
03478          nothingok = 0;
03479       }
03480    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
03481       /* Same as previous */
03482       if (p0->subs[SUB_CALLWAIT].inthreeway) {
03483          master = p0;
03484          slave = p1;
03485          nothingok = 0;
03486       }
03487    }
03488    if (option_debug)
03489       ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
03490          master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
03491    if (master && slave) {
03492       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
03493          in an active threeway call with a channel that is ringing, we should
03494          indicate ringing. */
03495       if ((oi1 == SUB_THREEWAY) && 
03496           p1->subs[SUB_THREEWAY].inthreeway && 
03497           p1->subs[SUB_REAL].owner && 
03498           p1->subs[SUB_REAL].inthreeway && 
03499           (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
03500          if (option_debug)
03501             ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
03502          tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
03503          os1 = p1->subs[SUB_REAL].owner->_state;
03504       } else {
03505          if (option_debug)
03506             ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
03507          tone_zone_play_tone(p0->subs[oi0].zfd, -1);
03508       }
03509       if ((oi0 == SUB_THREEWAY) && 
03510           p0->subs[SUB_THREEWAY].inthreeway && 
03511           p0->subs[SUB_REAL].owner && 
03512           p0->subs[SUB_REAL].inthreeway && 
03513           (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
03514          if (option_debug)
03515             ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
03516          tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
03517          os0 = p0->subs[SUB_REAL].owner->_state;
03518       } else {
03519          if (option_debug)
03520             ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
03521          tone_zone_play_tone(p1->subs[oi0].zfd, -1);
03522       }
03523       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
03524          if (!p0->echocanbridged || !p1->echocanbridged) {
03525             /* Disable echo cancellation if appropriate */
03526             zt_disable_ec(p0);
03527             zt_disable_ec(p1);
03528          }
03529       }
03530       zt_link(slave, master);
03531       master->inconference = inconf;
03532    } else if (!nothingok)
03533       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
03534 
03535    update_conf(p0);
03536    update_conf(p1);
03537    t0 = p0->subs[SUB_REAL].inthreeway;
03538    t1 = p1->subs[SUB_REAL].inthreeway;
03539 
03540    ast_mutex_unlock(&p0->lock);
03541    ast_mutex_unlock(&p1->lock);
03542 
03543    ast_mutex_unlock(&c0->lock);
03544    ast_mutex_unlock(&c1->lock);
03545 
03546    /* Native bridge failed */
03547    if ((!master || !slave) && !nothingok) {
03548       zt_enable_ec(p0);
03549       zt_enable_ec(p1);
03550       return AST_BRIDGE_FAILED;
03551    }
03552    
03553    if (option_verbose > 2) 
03554       ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
03555 
03556    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
03557       disable_dtmf_detect(op0);
03558 
03559    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
03560       disable_dtmf_detect(op1);
03561 
03562    for (;;) {
03563       struct ast_channel *c0_priority[2] = {c0, c1};
03564       struct ast_channel *c1_priority[2] = {c1, c0};
03565 
03566       /* Here's our main loop...  Start by locking things, looking for private parts, 
03567          and then balking if anything is wrong */
03568       ast_mutex_lock(&c0->lock);
03569       ast_mutex_lock(&c1->lock);
03570       p0 = c0->tech_pvt;
03571       p1 = c1->tech_pvt;
03572 
03573       if (op0 == p0)
03574          i0 = zt_get_index(c0, p0, 1);
03575       if (op1 == p1)
03576          i1 = zt_get_index(c1, p1, 1);
03577       ast_mutex_unlock(&c0->lock);
03578       ast_mutex_unlock(&c1->lock);
03579 
03580       if (!timeoutms || 
03581           (op0 != p0) ||
03582           (op1 != p1) || 
03583           (ofd0 != c0->fds[0]) || 
03584           (ofd1 != c1->fds[0]) ||
03585           (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) || 
03586           (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) || 
03587           (oc0 != p0->owner) || 
03588           (oc1 != p1->owner) ||
03589           (t0 != p0->subs[SUB_REAL].inthreeway) ||
03590           (t1 != p1->subs[SUB_REAL].inthreeway) ||
03591           (oi0 != i0) ||
03592           (oi1 != i1)) {
03593          if (option_debug)
03594             ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
03595                op0->channel, oi0, op1->channel, oi1);
03596          res = AST_BRIDGE_RETRY;
03597          goto return_from_bridge;
03598       }
03599 
03600 #ifdef PRI_2BCT
03601       q931c0 = p0->call;
03602       q931c1 = p1->call;
03603       if (p0->transfer && p1->transfer 
03604           && q931c0 && q931c1 
03605           && !triedtopribridge) {
03606          pri_channel_bridge(q931c0, q931c1);
03607          triedtopribridge = 1;
03608       }
03609 #endif
03610 
03611       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
03612       if (!who) {
03613          if (option_debug)
03614             ast_log(LOG_DEBUG, "Ooh, empty read...\n");
03615          continue;
03616       }
03617       f = ast_read(who);
03618       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
03619          *fo = f;
03620          *rc = who;
03621          res = AST_BRIDGE_COMPLETE;
03622          goto return_from_bridge;
03623       }
03624       if (f->frametype ==