Wed Oct 28 15:47:52 2009

Asterisk developer's documentation


chan_zap.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, 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  * Connects to the zaptel telephony library as well as 
00024  * libpri. Libpri is optional and needed only if you are
00025  * going to use ISDN connections.
00026  *
00027  * You need to install libraries before you attempt to compile
00028  * and install the zaptel channel.
00029  *
00030  * \par See also
00031  * \arg \ref Config_zap
00032  *
00033  * \ingroup channel_drivers
00034  */
00035 
00036 #include <stdio.h>
00037 #include <string.h>
00038 #ifdef __NetBSD__
00039 #include <pthread.h>
00040 #include <signal.h>
00041 #else
00042 #include <sys/signal.h>
00043 #endif
00044 #include <errno.h>
00045 #include <stdlib.h>
00046 #if !defined(SOLARIS) && !defined(__FreeBSD__)
00047 #include <stdint.h>
00048 #endif
00049 #include <unistd.h>
00050 #include <sys/ioctl.h>
00051 #ifdef __linux__
00052 #include <linux/zaptel.h>
00053 #else
00054 #include <zaptel.h>
00055 #endif /* __linux__ */
00056 #include <math.h>
00057 #include <tonezone.h>
00058 #include <ctype.h>
00059 #ifdef ZAPATA_PRI
00060 #include <libpri.h>
00061 #ifndef PRI_USER_USER_TX
00062 #error "You need newer libpri"
00063 #endif
00064 #endif
00065 #ifdef ZAPATA_R2
00066 #include <libmfcr2.h>
00067 #endif
00068 
00069 #include "asterisk.h"
00070 
00071 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 211526 $")
00072 
00073 #include "asterisk/lock.h"
00074 #include "asterisk/channel.h"
00075 #include "asterisk/config.h"
00076 #include "asterisk/logger.h"
00077 #include "asterisk/module.h"
00078 #include "asterisk/pbx.h"
00079 #include "asterisk/options.h"
00080 #include "asterisk/file.h"
00081 #include "asterisk/ulaw.h"
00082 #include "asterisk/alaw.h"
00083 #include "asterisk/callerid.h"
00084 #include "asterisk/adsi.h"
00085 #include "asterisk/cli.h"
00086 #include "asterisk/cdr.h"
00087 #include "asterisk/features.h"
00088 #include "asterisk/musiconhold.h"
00089 #include "asterisk/say.h"
00090 #include "asterisk/tdd.h"
00091 #include "asterisk/app.h"
00092 #include "asterisk/dsp.h"
00093 #include "asterisk/astdb.h"
00094 #include "asterisk/manager.h"
00095 #include "asterisk/causes.h"
00096 #include "asterisk/term.h"
00097 #include "asterisk/utils.h"
00098 #include "asterisk/transcap.h"
00099 
00100 #ifndef ZT_SIG_EM_E1
00101 #error "Your zaptel is too old.  please cvs update"
00102 #endif
00103 
00104 #ifndef ZT_TONEDETECT
00105 /* Work around older code with no tone detect */
00106 #define ZT_EVENT_DTMFDOWN 0
00107 #define ZT_EVENT_DTMFUP 0
00108 #endif
00109 
00110 /* define this to send PRI user-user information elements */
00111 #undef SUPPORT_USERUSER
00112 
00113 /*! 
00114  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
00115  * the user hangs up to reset the state machine so ring works properly.
00116  * This is used to be able to support kewlstart by putting the zhone in
00117  * groundstart mode since their forward disconnect supervision is entirely
00118  * broken even though their documentation says it isn't and their support
00119  * is entirely unwilling to provide any assistance with their channel banks
00120  * even though their web site says they support their products for life.
00121  */
00122 /* #define ZHONE_HACK */
00123 
00124 /*! \note
00125  * Define if you want to check the hook state for an FXO (FXS signalled) interface
00126  * before dialing on it.  Certain FXO interfaces always think they're out of
00127  * service with this method however.
00128  */
00129 /* #define ZAP_CHECK_HOOKSTATE */
00130 
00131 /*! \brief Typically, how many rings before we should send Caller*ID */
00132 #define DEFAULT_CIDRINGS 1
00133 
00134 #define CHANNEL_PSEUDO -12
00135 
00136 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
00137 
00138 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
00139 #define NEED_MFDETECT(p) (((p)->sig == SIG_FEATDMF) || ((p)->sig == SIG_FEATDMF_TA) || ((p)->sig == SIG_E911) || ((p)->sig == SIG_FEATB)) 
00140 
00141 static const char desc[] = "Zapata Telephony"
00142 #ifdef ZAPATA_PRI
00143                " w/PRI"
00144 #endif
00145 #ifdef ZAPATA_R2
00146                " w/R2"
00147 #endif
00148 ;
00149 
00150 static const char tdesc[] = "Zapata Telephony Driver"
00151 #ifdef ZAPATA_PRI
00152                " w/PRI"
00153 #endif
00154 #ifdef ZAPATA_R2
00155                " w/R2"
00156 #endif
00157 ;
00158 
00159 static const char type[] = "Zap";
00160 static const char config[] = "zapata.conf";
00161 
00162 #define SIG_EM    ZT_SIG_EM
00163 #define SIG_EMWINK   (0x0100000 | ZT_SIG_EM)
00164 #define SIG_FEATD (0x0200000 | ZT_SIG_EM)
00165 #define  SIG_FEATDMF (0x0400000 | ZT_SIG_EM)
00166 #define  SIG_FEATB   (0x0800000 | ZT_SIG_EM)
00167 #define  SIG_E911 (0x1000000 | ZT_SIG_EM)
00168 #define  SIG_FEATDMF_TA (0x2000000 | ZT_SIG_EM)
00169 #define SIG_FXSLS ZT_SIG_FXSLS
00170 #define SIG_FXSGS ZT_SIG_FXSGS
00171 #define SIG_FXSKS ZT_SIG_FXSKS
00172 #define SIG_FXOLS ZT_SIG_FXOLS
00173 #define SIG_FXOGS ZT_SIG_FXOGS
00174 #define SIG_FXOKS ZT_SIG_FXOKS
00175 #define SIG_PRI      ZT_SIG_CLEAR
00176 #define SIG_R2    ZT_SIG_CAS
00177 #define  SIG_SF      ZT_SIG_SF
00178 #define SIG_SFWINK   (0x0100000 | ZT_SIG_SF)
00179 #define SIG_SF_FEATD (0x0200000 | ZT_SIG_SF)
00180 #define  SIG_SF_FEATDMF (0x0400000 | ZT_SIG_SF)
00181 #define  SIG_SF_FEATB   (0x0800000 | ZT_SIG_SF)
00182 #define SIG_EM_E1 ZT_SIG_EM_E1
00183 #define SIG_GR303FXOKS  (0x0100000 | ZT_SIG_FXOKS)
00184 #define SIG_GR303FXSKS  (0x0100000 | ZT_SIG_FXSKS)
00185 
00186 #define NUM_SPANS       32
00187 #define NUM_DCHANS      4  /*!< No more than 4 d-channels */
00188 #define MAX_CHANNELS 672      /*!< No more than a DS3 per trunk group */
00189 
00190 #define CHAN_PSEUDO  -2
00191 
00192 #define DCHAN_PROVISIONED (1 << 0)
00193 #define DCHAN_NOTINALARM  (1 << 1)
00194 #define DCHAN_UP          (1 << 2)
00195 
00196 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
00197 
00198 static char defaultcic[64] = "";
00199 static char defaultozz[64] = "";
00200 
00201 static char language[MAX_LANGUAGE] = "";
00202 static char progzone[10]= "";
00203 
00204 static int usedistinctiveringdetection = 0;
00205 
00206 static int numbufs = 4;
00207 
00208 #ifdef ZAPATA_PRI
00209 static struct ast_channel inuse = { "GR-303InUse" };
00210 #ifdef PRI_GETSET_TIMERS
00211 static int pritimers[PRI_MAX_TIMERS];
00212 #endif
00213 static int pridebugfd = -1;
00214 static char pridebugfilename[1024]="";
00215 #endif
00216 
00217 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
00218 static int firstdigittimeout = 16000;
00219 
00220 /*! \brief How long to wait for following digits (FXO logic) */
00221 static int gendigittimeout = 8000;
00222 
00223 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
00224 static int matchdigittimeout = 3000;
00225 
00226 static int usecnt =0;
00227 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
00228 
00229 /*! \brief Protect the interface list (of zt_pvt's) */
00230 AST_MUTEX_DEFINE_STATIC(iflock);
00231 
00232 
00233 static int ifcount = 0;
00234 
00235 #ifdef ZAPATA_PRI
00236 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
00237 #endif
00238 
00239 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00240    when it's doing something critical. */
00241 AST_MUTEX_DEFINE_STATIC(monlock);
00242 
00243 /*! \brief This is the thread for the monitor which checks for input on the channels
00244    which are not currently in use.  */
00245 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00246 
00247 static int restart_monitor(void);
00248 
00249 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);
00250 
00251 static int zt_sendtext(struct ast_channel *c, const char *text);
00252 
00253 /*! \brief Avoid the silly zt_getevent which ignores a bunch of events */
00254 static inline int zt_get_event(int fd)
00255 {
00256    int j;
00257    if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
00258    return j;
00259 }
00260 
00261 /*! \brief Avoid the silly zt_waitevent which ignores a bunch of events */
00262 static inline int zt_wait_event(int fd)
00263 {
00264    int i,j=0;
00265    i = ZT_IOMUX_SIGEVENT;
00266    if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
00267    if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
00268    return j;
00269 }
00270 
00271 /*! Chunk size to read -- we use 20ms chunks to make things happy.  */   
00272 #define READ_SIZE 160
00273 
00274 #define MASK_AVAIL      (1 << 0) /*!< Channel available for PRI use */
00275 #define MASK_INUSE      (1 << 1) /*!< Channel currently in use */
00276 
00277 #define CALLWAITING_SILENT_SAMPLES  ( (300 * 8) / READ_SIZE) /*!< 300 ms */
00278 #define CALLWAITING_REPEAT_SAMPLES  ( (10000 * 8) / READ_SIZE) /*!< 300 ms */
00279 #define CIDCW_EXPIRE_SAMPLES     ( (500 * 8) / READ_SIZE) /*!< 500 ms */
00280 #define MIN_MS_SINCE_FLASH       ( (2000) )  /*!< 2000 ms */
00281 #define DEFAULT_RINGT            ( (8000 * 8) / READ_SIZE)
00282 
00283 struct zt_pvt;
00284 
00285 
00286 #ifdef ZAPATA_R2
00287 static int r2prot = -1;
00288 #endif
00289 
00290 static int ringt_base = DEFAULT_RINGT;
00291 
00292 #ifdef ZAPATA_PRI
00293 
00294 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
00295 #define PRI_CHANNEL(p) ((p) & 0xff)
00296 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
00297 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
00298 
00299 struct zt_pri {
00300    pthread_t master;                /*!< Thread of master */
00301    ast_mutex_t lock;                /*!< Mutex */
00302    char idleext[AST_MAX_EXTENSION];          /*!< Where to idle extra calls */
00303    char idlecontext[AST_MAX_CONTEXT];           /*!< What context to use for idle */
00304    char idledial[AST_MAX_EXTENSION];            /*!< What to dial before dumping */
00305    int minunused;                   /*!< Min # of channels to keep empty */
00306    int minidle;                     /*!< Min # of "idling" calls to keep active */
00307    int nodetype;                    /*!< Node type */
00308    int switchtype;                     /*!< Type of switch to emulate */
00309    int nsf;                   /*!< Network-Specific Facilities */
00310    int dialplan;                    /*!< Dialing plan */
00311    int localdialplan;                  /*!< Local dialing plan */
00312    char internationalprefix[10];             /*!< country access code ('00' for european dialplans) */
00313    char nationalprefix[10];               /*!< area access code ('0' for european dialplans) */
00314    char localprefix[20];                  /*!< area access code + area code ('0'+area code for european dialplans) */
00315    char privateprefix[20];                /*!< for private dialplans */
00316    char unknownprefix[20];                /*!< for unknown dialplans */
00317    int dchannels[NUM_DCHANS];             /*!< What channel are the dchannels on */
00318    int trunkgroup;                     /*!< What our trunkgroup is */
00319    int mastertrunkgroup;                  /*!< What trunk group is our master */
00320    int prilogicalspan;                 /*!< Logical span number within trunk group */
00321    int numchans;                    /*!< Num of channels we represent */
00322    int overlapdial;                 /*!< In overlap dialing mode */
00323    int facilityenable;                 /*!< Enable facility IEs */
00324    struct pri *dchans[NUM_DCHANS];              /*!< Actual d-channels */
00325    int dchanavail[NUM_DCHANS];               /*!< Whether each channel is available */
00326    struct pri *pri;                 /*!< Currently active D-channel */
00327    int debug;
00328    int fds[NUM_DCHANS];                /*!< FD's for d-channels */
00329    int offset;
00330    int span;
00331    int resetting;
00332    int resetpos;
00333    time_t lastreset;                /*!< time when unused channels were last reset */
00334    long resetinterval;                 /*!< Interval (in seconds) for resetting unused channels */
00335    struct zt_pvt *pvts[MAX_CHANNELS];           /*!< Member channel pvt structs */
00336    struct zt_pvt *crvs;                /*!< Member CRV structs */
00337    struct zt_pvt *crvend;                 /*!< Pointer to end of CRV structs */
00338 };
00339 
00340 
00341 static struct zt_pri pris[NUM_SPANS];
00342 
00343 static int pritype = PRI_CPE;
00344 
00345 #if 0
00346 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
00347 #else
00348 #define DEFAULT_PRI_DEBUG 0
00349 #endif
00350 
00351 static inline void pri_rel(struct zt_pri *pri)
00352 {
00353    ast_mutex_unlock(&pri->lock);
00354 }
00355 
00356 static int switchtype = PRI_SWITCH_NI2;
00357 static int nsf = PRI_NSF_NONE;
00358 static int dialplan = PRI_NATIONAL_ISDN + 1;
00359 static int localdialplan = PRI_NATIONAL_ISDN + 1;
00360 
00361 #else
00362 /*! Shut up the compiler */
00363 struct zt_pri;
00364 #endif
00365 
00366 #define SUB_REAL  0        /*!< Active call */
00367 #define SUB_CALLWAIT 1        /*!< Call-Waiting call on hold */
00368 #define SUB_THREEWAY 2        /*!< Three-way call */
00369 
00370 /* Polarity states */
00371 #define POLARITY_IDLE   0
00372 #define POLARITY_REV    1
00373 
00374 
00375 static struct zt_distRings drings;
00376 
00377 struct distRingData {
00378    int ring[3];
00379 };
00380 struct ringContextData {
00381    char contextData[AST_MAX_CONTEXT];
00382 };
00383 struct zt_distRings {
00384    struct distRingData ringnum[3];
00385    struct ringContextData ringContext[3];
00386 };
00387 
00388 static char *subnames[] = {
00389    "Real",
00390    "Callwait",
00391    "Threeway"
00392 };
00393 
00394 struct zt_subchannel {
00395    int zfd;
00396    struct ast_channel *owner;
00397    int chan;
00398    short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
00399    struct ast_frame f;     /*!< One frame for each channel.  How did this ever work before? */
00400    unsigned int needringing:1;
00401    unsigned int needbusy:1;
00402    unsigned int needcongestion:1;
00403    unsigned int needcallerid:1;
00404    unsigned int needanswer:1;
00405    unsigned int needflash:1;
00406    unsigned int linear:1;
00407    unsigned int inthreeway:1;
00408    ZT_CONFINFO curconf;
00409 };
00410 
00411 #define CONF_USER_REAL     (1 << 0)
00412 #define CONF_USER_THIRDCALL   (1 << 1)
00413 
00414 #define MAX_SLAVES   4
00415 
00416 /*! \brief The PRI part of the channel configuration.
00417  * Separated as it is is applied to the span rather than to the channel.
00418  */
00419 struct zt_pri_conf {
00420 #ifdef ZAPATA_PRI
00421    int minunused;
00422    int minidle;
00423    char idleext[AST_MAX_EXTENSION];
00424    char idledial[AST_MAX_EXTENSION];
00425    int overlapdial;
00426    int facilityenable;
00427    char internationalprefix[10];
00428    char nationalprefix[10];
00429    char localprefix[20];
00430    char privateprefix[20];
00431    char unknownprefix[20];
00432    long resetinterval;
00433 #endif
00434 };
00435 
00436 /*! \brief Channel configuration from zapata.conf .
00437  * This struct is used for parsing the [channels] section of zapata.conf.
00438  * Generally there is a field here for every possible configuration item.
00439  *
00440  * The state of fields is saved along the parsing and whenever a 'channel'
00441  * statement is reached, the current zt_chan_conf is used to configure the 
00442  * channel (struct zt_pvt)
00443  *
00444  * @seealso zt_chan_init for the default values.
00445  */
00446 struct zt_chan_conf {
00447    struct zt_pri_conf pri;
00448    char context[AST_MAX_CONTEXT];
00449    char cid_num[AST_MAX_EXTENSION];
00450    char cid_name[AST_MAX_EXTENSION];
00451    char musicclass[MAX_MUSICCLASS];
00452    int transfertobusy;
00453 
00454    int cid_signalling;
00455    int cid_start;
00456    int zaptrcallerid;
00457    int use_callerid;
00458    int signalling;
00459    int outsignalling;
00460    ast_group_t group;
00461    ast_group_t callergroup;
00462    ast_group_t pickupgroup;
00463 
00464    int relaxdtmf;
00465 
00466    int immediate; 
00467 
00468    int stripmsd;
00469 
00470    int callwaiting;
00471 
00472    int callwaitingcallerid;
00473 
00474    int hidecallerid;
00475 
00476    int restrictcid;
00477 
00478    int use_callingpres;
00479 
00480    int callreturn;
00481 
00482    int threewaycalling;
00483 
00484    int transfer;
00485 
00486    int canpark;
00487 
00488    int cancallforward;
00489 
00490    float rxgain;
00491 
00492    float txgain;
00493 
00494    int tonezone;
00495 
00496    int echocancel;
00497 
00498    int echotraining;
00499 
00500    int pulse;
00501 
00502    int echocanbridged;
00503 
00504    int busydetect;
00505 
00506    int busycount;
00507    int busy_tonelength;
00508    int busy_quietlength;
00509 
00510    int callprogress;
00511 
00512    char accountcode[AST_MAX_ACCOUNT_CODE];
00513 
00514    char mailbox[AST_MAX_EXTENSION];
00515 
00516    int amaflags;
00517 
00518    int adsi;
00519 
00520    int numbufs;
00521 
00522    int prewink;
00523    int preflash;
00524    int wink;
00525    int flash;
00526    int start;
00527    int rxwink;
00528    int rxflash;
00529    int debounce;
00530    int priexclusive;
00531 
00532    int answeronpolarityswitch;
00533    int hanguponpolarityswitch;
00534    int polarityonanswerdelay;
00535    int sendcalleridafter;
00536 
00537    int priindication_oob;
00538    int radio;
00539 };
00540 
00541 /** returns a new zt_chan_conf with default values (by-value) */
00542 struct zt_chan_conf zt_chan_conf_default(void) {
00543    struct zt_chan_conf chan_conf = {
00544       .pri = {
00545 #ifdef ZAPATA_PRI
00546          .minunused = 2,
00547          .minidle = 0,
00548          .idleext = "",
00549          .idledial = "",
00550          .overlapdial = 0,
00551          .facilityenable = 0,
00552          .internationalprefix = "",
00553          .nationalprefix = "",
00554          .localprefix = "",
00555          .privateprefix = "",
00556          .unknownprefix = "",
00557          /*!< How often (in seconds) to reset unused channels. Default 1 hour. */
00558          .resetinterval = 3600,  
00559 #endif
00560       },
00561       .context = "default",
00562       .cid_num = "",
00563       .cid_name = "",
00564       .musicclass = "",
00565       .transfertobusy = 1,
00566 
00567       .cid_signalling = CID_SIG_BELL,
00568       .cid_start = CID_START_RING,
00569       .zaptrcallerid = 0,
00570       .use_callerid = 1,
00571       .signalling = -1,
00572       .group = 0,
00573       .callergroup = 0,
00574       .pickupgroup = 0,
00575 
00576       .relaxdtmf = 0,
00577       .immediate = 0,
00578 
00579       .stripmsd = 0,
00580 
00581       .callwaiting = 0,
00582 
00583       .callwaitingcallerid = 0,
00584 
00585       .hidecallerid = 0,
00586 
00587       .restrictcid = 0,
00588 
00589       .use_callingpres = 0,
00590 
00591       .callreturn = 0,
00592 
00593       .threewaycalling = 0,
00594 
00595       .transfer = 0,
00596 
00597       .canpark = 0,
00598 
00599       .cancallforward = 0,
00600 
00601       .rxgain = 0.0,
00602 
00603       .txgain = 0.0,
00604 
00605       .tonezone = -1,
00606 
00607       /*! \brief Boolean: true to use echo cancelling. Default: True. */
00608       .echocancel = 1,
00609 
00610       /*! \brief Integer: Echo training time. True implies 400. */
00611       .echotraining = 0,
00612 
00613       /*! \brief Boolean: Use pulse dialing. Default: false. Right? */
00614       .pulse = 0,
00615       
00616       /*! \brief Boolean: true to use echo cancelling even between zaptel 
00617        * channels. Default: false. */
00618       .echocanbridged = 0,
00619 
00620       /*! \brief Boolean: hangup calls by detecting a busy tone. 
00621        * Default: false. */
00622       .busydetect = 0,
00623 
00624       .busycount = 3,
00625       .busy_tonelength = 0,
00626       .busy_quietlength = 0,
00627 
00628       .callprogress = 0,
00629 
00630       .accountcode = "",
00631 
00632       /*! \brief String. Voicemail box in which to check mail for 
00633        * the channel (mailbox[@context]). Default: none. */
00634       .mailbox = "",
00635       .amaflags = 0,
00636 
00637       .adsi = 0,
00638       .numbufs = 4,
00639 
00640       .prewink = -1,
00641       .preflash = -1,
00642       .wink = -1,
00643       .flash = -1,
00644       .start = -1,
00645       .rxwink = -1,
00646       .rxflash = -1,
00647       .debounce = -1,
00648       .priexclusive = 0,
00649 
00650       /*! \brief Whether we answer on a Polarity Switch event */
00651       .answeronpolarityswitch = 0,
00652 
00653       /*! \brief Whether we hang up on a Polarity Switch event */
00654       .hanguponpolarityswitch = 0,
00655 
00656       /*! \brief How long (ms) to ignore Polarity Switch events after we answer a call */
00657       .polarityonanswerdelay = 600,
00658 
00659       /*! \brief When to send the CallerID signals (rings) */
00660       .sendcalleridafter = DEFAULT_CIDRINGS,
00661 
00662       .priindication_oob = 0,
00663 
00664       /* Add fields above this comment. "radio" will be 
00665        * kept as the one without the comma. for the moment, 
00666        * until we add all fields.
00667        */
00668       .radio = 0
00669    };
00670 
00671    return chan_conf;
00672 }
00673 
00674 static struct zt_pvt {
00675    ast_mutex_t lock;
00676    struct ast_channel *owner;       /*!< Our current active owner (if applicable) */
00677                      /*!< Up to three channels can be associated with this call */
00678       
00679    struct zt_subchannel sub_unused;    /*!< Just a safety precaution */
00680    struct zt_subchannel subs[3];       /*!< Sub-channels */
00681    struct zt_confinfo saveconf;        /*!< Saved conference info */
00682 
00683    struct zt_pvt *slaves[MAX_SLAVES];     /*!< Slave to us (follows our conferencing) */
00684    struct zt_pvt *master;           /*!< Master to us (we follow their conferencing) */
00685    int inconference;          /*!< If our real should be in the conference */
00686    
00687    int sig;             /*!< Signalling style */
00688    int radio;              /*!< radio type */
00689    float rxgain;
00690    float txgain;
00691    int tonezone;              /*!< tone zone for this chan, or -1 for default */
00692    struct zt_pvt *next;          /*!< Next channel in list */
00693    struct zt_pvt *prev;          /*!< Prev channel in list */
00694 
00695    /* flags */
00696    unsigned int adsi:1;
00697    unsigned int answeronpolarityswitch:1;
00698    unsigned int busydetect:1;
00699    unsigned int callreturn:1;
00700    unsigned int callwaiting:1;
00701    unsigned int callwaitingcallerid:1;
00702    unsigned int cancallforward:1;
00703    unsigned int canpark:1;
00704    unsigned int confirmanswer:1;       /*!< Wait for '#' to confirm answer */
00705    unsigned int destroy:1;
00706    unsigned int didtdd:1;           /*!< flag to say its done it once */
00707    unsigned int dialednone:1;
00708    unsigned int dialing:1;
00709    unsigned int digital:1;
00710    unsigned int dnd:1;
00711    unsigned int echobreak:1;
00712    unsigned int echocanbridged:1;
00713    unsigned int echocanon:1;
00714    unsigned int faxhandled:1;       /*!< Has a fax tone already been handled? */
00715    unsigned int firstradio:1;
00716    unsigned int hanguponpolarityswitch:1;
00717    unsigned int hardwaredtmf:1;
00718    unsigned int hidecallerid;
00719    unsigned int ignoredtmf:1;
00720    unsigned int immediate:1;        /*!< Answer before getting digits? */
00721    unsigned int inalarm:1;
00722    unsigned int mate:1;          /*!< flag to say its in MATE mode */
00723    unsigned int outgoing:1;
00724    unsigned int overlapdial:1;
00725    unsigned int permcallwaiting:1;
00726    unsigned int permhidecallerid:1;    /*!< Whether to hide our outgoing caller ID or not */
00727    unsigned int priindication_oob:1;
00728    unsigned int priexclusive:1;
00729    unsigned int pulse:1;
00730    unsigned int pulsedial:1;        /*!< whether a pulse dial phone is detected */
00731    unsigned int restrictcid:1;         /*!< Whether restrict the callerid -> only send ANI */
00732    unsigned int threewaycalling:1;
00733    unsigned int transfer:1;
00734    unsigned int use_callerid:1;        /*!< Whether or not to use caller id on this channel */
00735    unsigned int use_callingpres:1;        /*!< Whether to use the callingpres the calling switch sends */
00736    unsigned int usedistinctiveringdetection:1;
00737    unsigned int zaptrcallerid:1;       /*!< should we use the callerid from incoming call on zap transfer or not */
00738    unsigned int transfertobusy:1;         /*!< allow flash-transfers to busy channels */
00739 #if defined(ZAPATA_PRI)
00740    unsigned int alerting:1;
00741    unsigned int alreadyhungup:1;
00742    unsigned int isidlecall:1;
00743    unsigned int proceeding:1;
00744    unsigned int progress:1;
00745    unsigned int resetting:1;
00746    unsigned int setup_ack:1;
00747 #endif
00748 #if defined(ZAPATA_R2)
00749    unsigned int hasr2call:1;
00750    unsigned int r2blocked:1;
00751    unsigned int sigchecked:1;
00752 #endif
00753 
00754    struct zt_distRings drings;
00755 
00756    char context[AST_MAX_CONTEXT];
00757    char defcontext[AST_MAX_CONTEXT];
00758    char exten[AST_MAX_EXTENSION];
00759    char language[MAX_LANGUAGE];
00760    char musicclass[MAX_MUSICCLASS];
00761 #ifdef PRI_ANI
00762    char cid_ani[AST_MAX_EXTENSION];
00763 #endif
00764    char cid_num[AST_MAX_EXTENSION];
00765    int cid_ton;               /*!< Type Of Number (TON) */
00766    char cid_name[AST_MAX_EXTENSION];
00767    char lastcid_num[AST_MAX_EXTENSION];
00768    char lastcid_name[AST_MAX_EXTENSION];
00769    char *origcid_num;            /*!< malloced original callerid */
00770    char *origcid_name;           /*!< malloced original callerid */
00771    char callwait_num[AST_MAX_EXTENSION];
00772    char callwait_name[AST_MAX_EXTENSION];
00773    char rdnis[AST_MAX_EXTENSION];
00774    char dnid[AST_MAX_EXTENSION];
00775    unsigned int group;
00776    int law;
00777    int confno;             /*!< Our conference */
00778    int confusers;             /*!< Who is using our conference */
00779    int propconfno;               /*!< Propagated conference number */
00780    ast_group_t callgroup;
00781    ast_group_t pickupgroup;
00782    int channel;               /*!< Channel Number or CRV */
00783    int span;               /*!< Span number */
00784    time_t guardtime;          /*!< Must wait this much time before using for new call */
00785    int cid_signalling;           /*!< CID signalling type bell202 or v23 */
00786    int cid_start;             /*!< CID start indicator, polarity or ring */
00787    int callingpres;           /*!< The value of callling presentation that we're going to use when placing a PRI call */
00788    int callwaitingrepeat;           /*!< How many samples to wait before repeating call waiting */
00789    int cidcwexpire;           /*!< When to expire our muting for CID/CW */
00790    unsigned char *cidspill;
00791    int cidpos;
00792    int cidlen;
00793    int ringt;
00794    int ringt_base;
00795    int stripmsd;
00796    int callwaitcas;
00797    int callwaitrings;
00798    int echocancel;
00799    int echotraining;
00800    char echorest[20];
00801    int busycount;
00802    int busy_tonelength;
00803    int busy_quietlength;
00804    int callprogress;
00805    struct timeval flashtime;        /*!< Last flash-hook time */
00806    struct ast_dsp *dsp;
00807    int cref;               /*!< Call reference number */
00808    ZT_DIAL_OPERATION dop;
00809    int whichwink;             /*!< SIG_FEATDMF_TA Which wink are we on? */
00810    char finaldial[64];
00811    char accountcode[AST_MAX_ACCOUNT_CODE];      /*!< Account code */
00812    int amaflags;              /*!< AMA Flags */
00813    struct tdd_state *tdd;           /*!< TDD flag */
00814    char call_forward[AST_MAX_EXTENSION];
00815    char mailbox[AST_MAX_EXTENSION];
00816    char dialdest[256];
00817    int onhooktime;
00818    int msgstate;
00819    int distinctivering;          /*!< Which distinctivering to use */
00820    int cidrings;              /*!< Which ring to deliver CID on */
00821    int dtmfrelax;             /*!< whether to run in relaxed DTMF mode */
00822    int fake_event;
00823    int polarityonanswerdelay;
00824    struct timeval polaritydelaytv;
00825    int sendcalleridafter;
00826 #ifdef ZAPATA_PRI
00827    struct zt_pri *pri;
00828    struct zt_pvt *bearer;
00829    struct zt_pvt *realcall;
00830    q931_call *call;
00831    int prioffset;
00832    int logicalspan;
00833 #endif   
00834 #ifdef ZAPATA_R2
00835    int r2prot;
00836    mfcr2_t *r2;
00837 #endif   
00838    int polarity;
00839    int dsp_features;
00840 
00841 } *iflist = NULL, *ifend = NULL;
00842 
00843 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
00844 static int zt_digit(struct ast_channel *ast, char digit);
00845 static int zt_sendtext(struct ast_channel *c, const char *text);
00846 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
00847 static int zt_hangup(struct ast_channel *ast);
00848 static int zt_answer(struct ast_channel *ast);
00849 struct ast_frame *zt_read(struct ast_channel *ast);
00850 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
00851 struct ast_frame *zt_exception(struct ast_channel *ast);
00852 static int zt_indicate(struct ast_channel *chan, int condition);
00853 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00854 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
00855 
00856 static const struct ast_channel_tech zap_tech = {
00857    .type = type,
00858    .description = tdesc,
00859    .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW,
00860    .requester = zt_request,
00861    .send_digit = zt_digit,
00862    .send_text = zt_sendtext,
00863    .call = zt_call,
00864    .hangup = zt_hangup,
00865    .answer = zt_answer,
00866    .read = zt_read,
00867    .write = zt_write,
00868    .bridge = zt_bridge,
00869    .exception = zt_exception,
00870    .indicate = zt_indicate,
00871    .fixup = zt_fixup,
00872    .setoption = zt_setoption,
00873 };
00874 
00875 #ifdef ZAPATA_PRI
00876 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
00877 #else
00878 #define GET_CHANNEL(p) ((p)->channel)
00879 #endif
00880 
00881 struct zt_pvt *round_robin[32];
00882 
00883 #ifdef ZAPATA_PRI
00884 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
00885 {
00886    int res;
00887    /* Grab the lock first */
00888    do {
00889        res = ast_mutex_trylock(&pri->lock);
00890       if (res) {
00891          ast_mutex_unlock(&pvt->lock);
00892          /* Release the lock and try again */
00893          usleep(1);
00894          ast_mutex_lock(&pvt->lock);
00895       }
00896    } while(res);
00897    /* Then break the poll */
00898    pthread_kill(pri->master, SIGURG);
00899    return 0;
00900 }
00901 #endif
00902 
00903 #define NUM_CADENCE_MAX 25
00904 static int num_cadence = 4;
00905 static int user_has_defined_cadences = 0;
00906 
00907 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
00908    { { 125, 125, 2000, 4000 } },       /*!< Quick chirp followed by normal ring */
00909    { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
00910    { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
00911    { { 1000, 500, 2500, 5000 } },   /*!< Long ring */
00912 };
00913 
00914 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
00915  * is 1, the second pause is 2 and so on.
00916  */
00917 
00918 static int cidrings[NUM_CADENCE_MAX] = {
00919    2,                            /*!< Right after first long ring */
00920    4,                            /*!< Right after long part */
00921    3,                            /*!< After third chirp */
00922    2,                            /*!< Second spell */
00923 };
00924 
00925 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
00926          (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
00927 
00928 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
00929 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
00930 
00931 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
00932 {
00933    int res;
00934    if (p->subs[0].owner == ast)
00935       res = 0;
00936    else if (p->subs[1].owner == ast)
00937       res = 1;
00938    else if (p->subs[2].owner == ast)
00939       res = 2;
00940    else {
00941       res = -1;
00942       if (!nullok)
00943          ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
00944    }
00945    return res;
00946 }
00947 
00948 #ifdef ZAPATA_PRI
00949 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
00950 #else
00951 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
00952 #endif
00953 {
00954    struct ast_frame null = { AST_FRAME_NULL, };
00955 #ifdef ZAPATA_PRI
00956    if (pri)
00957       ast_mutex_unlock(&pri->lock);
00958 #endif         
00959    for (;;) {
00960       if (p->subs[a].owner) {
00961          if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
00962             ast_mutex_unlock(&p->lock);
00963             usleep(1);
00964             ast_mutex_lock(&p->lock);
00965          } else {
00966             ast_queue_frame(p->subs[a].owner, &null);
00967             ast_mutex_unlock(&p->subs[a].owner->lock);
00968             break;
00969          }
00970       } else
00971          break;
00972    }
00973 #ifdef ZAPATA_PRI
00974    if (pri)
00975       ast_mutex_lock(&pri->lock);
00976 #endif         
00977 }
00978 
00979 #ifdef ZAPATA_PRI
00980 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
00981 #else
00982 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
00983 #endif
00984 {
00985    /* We must unlock the PRI to avoid the possibility of a deadlock */
00986 #ifdef ZAPATA_PRI
00987    if (pri)
00988       ast_mutex_unlock(&pri->lock);
00989 #endif      
00990    for (;;) {
00991       if (p->owner) {
00992          if (ast_mutex_trylock(&p->owner->lock)) {
00993             ast_mutex_unlock(&p->lock);
00994             usleep(1);
00995             ast_mutex_lock(&p->lock);
00996          } else {
00997             ast_queue_frame(p->owner, f);
00998             ast_mutex_unlock(&p->owner->lock);
00999             break;
01000          }
01001       } else
01002          break;
01003    }
01004 #ifdef ZAPATA_PRI
01005    if (pri)
01006       ast_mutex_lock(&pri->lock);
01007 #endif      
01008 }
01009 
01010 static int restore_gains(struct zt_pvt *p);
01011 
01012 static void swap_subs(struct zt_pvt *p, int a, int b)
01013 {
01014    int tchan;
01015    int tinthreeway;
01016    struct ast_channel *towner;
01017 
01018    ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
01019 
01020    tchan = p->subs[a].chan;
01021    towner = p->subs[a].owner;
01022    tinthreeway = p->subs[a].inthreeway;
01023 
01024    p->subs[a].chan = p->subs[b].chan;
01025    p->subs[a].owner = p->subs[b].owner;
01026    p->subs[a].inthreeway = p->subs[b].inthreeway;
01027 
01028    p->subs[b].chan = tchan;
01029    p->subs[b].owner = towner;
01030    p->subs[b].inthreeway = tinthreeway;
01031 
01032    if (p->subs[a].owner) 
01033       p->subs[a].owner->fds[0] = p->subs[a].zfd;
01034    if (p->subs[b].owner) 
01035       p->subs[b].owner->fds[0] = p->subs[b].zfd;
01036    wakeup_sub(p, a, NULL);
01037    wakeup_sub(p, b, NULL);
01038 }
01039 
01040 static int zt_open(char *fn)
01041 {
01042    int fd;
01043    int isnum;
01044    int chan = 0;
01045    int bs;
01046    int x;
01047    isnum = 1;
01048    for (x=0;x<strlen(fn);x++) {
01049       if (!isdigit(fn[x])) {
01050          isnum = 0;
01051          break;
01052       }
01053    }
01054    if (isnum) {
01055       chan = atoi(fn);
01056       if (chan < 1) {
01057          ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
01058          return -1;
01059       }
01060       fn = "/dev/zap/channel";
01061    }
01062    fd = open(fn, O_RDWR | O_NONBLOCK);
01063    if (fd < 0) {
01064       ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
01065       return -1;
01066    }
01067    if (chan) {
01068       if (ioctl(fd, ZT_SPECIFY, &chan)) {
01069          x = errno;
01070          close(fd);
01071          errno = x;
01072          ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
01073          return -1;
01074       }
01075    }
01076    bs = READ_SIZE;
01077    if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
01078    return fd;
01079 }
01080 
01081 static void zt_close(int fd)
01082 {
01083    if(fd > 0)
01084       close(fd);
01085 }
01086 
01087 int zt_setlinear(int zfd, int linear)
01088 {
01089    int res;
01090    res = ioctl(zfd, ZT_SETLINEAR, &linear);
01091    if (res)
01092       return res;
01093    return 0;
01094 }
01095 
01096 
01097 int zt_setlaw(int zfd, int law)
01098 {
01099    int res;
01100    res = ioctl(zfd, ZT_SETLAW, &law);
01101    if (res)
01102       return res;
01103    return 0;
01104 }
01105 
01106 static int alloc_sub(struct zt_pvt *p, int x)
01107 {
01108    ZT_BUFFERINFO bi;
01109    int res;
01110    if (p->subs[x].zfd < 0) {
01111       p->subs[x].zfd = zt_open("/dev/zap/pseudo");
01112       if (p->subs[x].zfd > -1) {
01113          res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
01114          if (!res) {
01115             bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
01116             bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
01117             bi.numbufs = numbufs;
01118             res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
01119             if (res < 0) {
01120                ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
01121             }
01122          } else 
01123             ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
01124          if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
01125             ast_log(LOG_WARNING,"Unable to get channel number for pseudo channel on FD %d\n",p->subs[x].zfd);
01126             zt_close(p->subs[x].zfd);
01127             p->subs[x].zfd = -1;
01128             return -1;
01129          }
01130          if (option_debug)
01131             ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
01132          return 0;
01133       } else
01134          ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
01135       return -1;
01136    }
01137    ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
01138    return -1;
01139 }
01140 
01141 static int unalloc_sub(struct zt_pvt *p, int x)
01142 {
01143    if (!x) {
01144       ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
01145       return -1;
01146    }
01147    ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
01148    if (p->subs[x].zfd > -1) {
01149       zt_close(p->subs[x].zfd);
01150    }
01151    p->subs[x].zfd = -1;
01152    p->subs[x].linear = 0;
01153    p->subs[x].chan = 0;
01154    p->subs[x].owner = NULL;
01155    p->subs[x].inthreeway = 0;
01156    p->polarity = POLARITY_IDLE;
01157    memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
01158    return 0;
01159 }
01160 
01161 static int zt_digit(struct ast_channel *ast, char digit)
01162 {
01163    ZT_DIAL_OPERATION zo;
01164    struct zt_pvt *p;
01165    int res = 0;
01166    int index;
01167    p = ast->tech_pvt;
01168    ast_mutex_lock(&p->lock);
01169    index = zt_get_index(ast, p, 0);
01170    if ((index == SUB_REAL) && p->owner) {
01171 #ifdef ZAPATA_PRI
01172       if ((p->sig == SIG_PRI) && (ast->_state == AST_STATE_DIALING) && !p->proceeding) {
01173          if (p->setup_ack) {
01174             if (!pri_grab(p, p->pri)) {
01175                pri_information(p->pri->pri,p->call,digit);
01176                pri_rel(p->pri);
01177             } else
01178                ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
01179          } else if (strlen(p->dialdest) < sizeof(p->dialdest) - 1) {
01180             ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
01181             res = strlen(p->dialdest);
01182             p->dialdest[res++] = digit;
01183             p->dialdest[res] = '\0';
01184          }
01185       } else {
01186 #else
01187       {
01188 #endif
01189          zo.op = ZT_DIAL_OP_APPEND;
01190          zo.dialstr[0] = 'T';
01191          zo.dialstr[1] = digit;
01192          zo.dialstr[2] = 0;
01193          if ((res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
01194             ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
01195          else
01196             p->dialing = 1;
01197       }
01198    }
01199    ast_mutex_unlock(&p->lock);
01200    return res;
01201 }
01202 
01203 static char *events[] = {
01204       "No event",
01205       "On hook",
01206       "Ring/Answered",
01207       "Wink/Flash",
01208       "Alarm",
01209       "No more alarm",
01210       "HDLC Abort",
01211       "HDLC Overrun",
01212       "HDLC Bad FCS",
01213       "Dial Complete",
01214       "Ringer On",
01215       "Ringer Off",
01216       "Hook Transition Complete",
01217       "Bits Changed",
01218       "Pulse Start",
01219       "Timer Expired",
01220       "Timer Ping",
01221       "Polarity Reversal",
01222       "Ring Begin",
01223 };
01224 
01225 static struct {
01226    int alarm;
01227    char *name;
01228 } alarms[] = {
01229    { ZT_ALARM_RED, "Red Alarm" },
01230    { ZT_ALARM_YELLOW, "Yellow Alarm" },
01231    { ZT_ALARM_BLUE, "Blue Alarm" },
01232    { ZT_ALARM_RECOVER, "Recovering" },
01233    { ZT_ALARM_LOOPBACK, "Loopback" },
01234    { ZT_ALARM_NOTOPEN, "Not Open" },
01235    { ZT_ALARM_NONE, "None" },
01236 };
01237 
01238 static char *alarm2str(int alarm)
01239 {
01240    int x;
01241    for (x=0;x<sizeof(alarms) / sizeof(alarms[0]); x++) {
01242       if (alarms[x].alarm & alarm)
01243          return alarms[x].name;
01244    }
01245    return alarm ? "Unknown Alarm" : "No Alarm";
01246 }
01247 
01248 static char *event2str(int event)
01249 {
01250         static char buf[256];
01251         if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
01252                 return events[event];
01253         sprintf(buf, "Event %d", event); /* safe */
01254         return buf;
01255 }
01256 
01257 #ifdef ZAPATA_PRI
01258 static char *dialplan2str(int dialplan)
01259 {
01260    if (dialplan == -1) {
01261       return("Dynamically set dialplan in ISDN");
01262    }
01263    return(pri_plan2str(dialplan));
01264 }
01265 #endif
01266 
01267 #ifdef ZAPATA_R2
01268 static int str2r2prot(char *swtype)
01269 {
01270     if (!strcasecmp(swtype, "ar"))
01271         return MFCR2_PROT_ARGENTINA;
01272     /*endif*/
01273     if (!strcasecmp(swtype, "cn"))
01274         return MFCR2_PROT_CHINA;
01275     /*endif*/
01276     if (!strcasecmp(swtype, "kr"))
01277         return MFCR2_PROT_KOREA;
01278     /*endif*/
01279     return -1;
01280 }
01281 #endif
01282 
01283 static char *zap_sig2str(int sig)
01284 {
01285    static char buf[256];
01286    switch(sig) {
01287    case SIG_EM:
01288       return "E & M Immediate";
01289    case SIG_EMWINK:
01290       return "E & M Wink";
01291    case SIG_EM_E1:
01292       return "E & M E1";
01293    case SIG_FEATD:
01294       return "Feature Group D (DTMF)";
01295    case SIG_FEATDMF:
01296       return "Feature Group D (MF)";
01297    case SIG_FEATDMF_TA:
01298       return "Feature Groud D (MF) Tandem Access";
01299    case SIG_FEATB:
01300       return "Feature Group B (MF)";
01301    case SIG_E911:
01302       return "E911 (MF)";
01303    case SIG_FXSLS:
01304       return "FXS Loopstart";
01305    case SIG_FXSGS:
01306       return "FXS Groundstart";
01307    case SIG_FXSKS:
01308       return "FXS Kewlstart";
01309    case SIG_FXOLS:
01310       return "FXO Loopstart";
01311    case SIG_FXOGS:
01312       return "FXO Groundstart";
01313    case SIG_FXOKS:
01314       return "FXO Kewlstart";
01315    case SIG_PRI:
01316       return "PRI Signalling";
01317    case SIG_R2:
01318       return "R2 Signalling";
01319    case SIG_SF:
01320       return "SF (Tone) Signalling Immediate";
01321    case SIG_SFWINK:
01322       return "SF (Tone) Signalling Wink";
01323    case SIG_SF_FEATD:
01324       return "SF (Tone) Signalling with Feature Group D (DTMF)";
01325    case SIG_SF_FEATDMF:
01326       return "SF (Tone) Signalling with Feature Group D (MF)";
01327    case SIG_SF_FEATB:
01328       return "SF (Tone) Signalling with Feature Group B (MF)";
01329    case SIG_GR303FXOKS:
01330       return "GR-303 Signalling with FXOKS";
01331    case SIG_GR303FXSKS:
01332       return "GR-303 Signalling with FXSKS";
01333    case 0:
01334       return "Pseudo Signalling";
01335    default:
01336       snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
01337       return buf;
01338    }
01339 }
01340 
01341 #define sig2str zap_sig2str
01342 
01343 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
01344 {
01345    /* If the conference already exists, and we're already in it
01346       don't bother doing anything */
01347    ZT_CONFINFO zi;
01348    
01349    memset(&zi, 0, sizeof(zi));
01350    zi.chan = 0;
01351 
01352    if (slavechannel > 0) {
01353       /* If we have only one slave, do a digital mon */
01354       zi.confmode = ZT_CONF_DIGITALMON;
01355       zi.confno = slavechannel;
01356    } else {
01357       if (!index) {
01358          /* Real-side and pseudo-side both participate in conference */
01359          zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
01360                         ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
01361       } else
01362          zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
01363       zi.confno = p->confno;
01364    }
01365    if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
01366       return 0;
01367    if (c->zfd < 0)
01368       return 0;
01369    if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
01370       ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
01371       return -1;
01372    }
01373    if (slavechannel < 1) {
01374       p->confno = zi.confno;
01375    }
01376    memcpy(&c->curconf, &zi, sizeof(c->curconf));
01377    ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
01378    return 0;
01379 }
01380 
01381 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
01382 {
01383    /* If they're listening to our channel, they're ours */  
01384    if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
01385       return 1;
01386    /* If they're a talker on our (allocated) conference, they're ours */
01387    if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
01388       return 1;
01389    return 0;
01390 }
01391 
01392 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
01393 {
01394    ZT_CONFINFO zi;
01395    if (/* Can't delete if there's no zfd */
01396       (c->zfd < 0) ||
01397       /* Don't delete from the conference if it's not our conference */
01398       !isourconf(p, c)
01399       /* Don't delete if we don't think it's conferenced at all (implied) */
01400       ) return 0;
01401    memset(&zi, 0, sizeof(zi));
01402    zi.chan = 0;
01403    zi.confno = 0;
01404    zi.confmode = 0;
01405    if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
01406       ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
01407       return -1;
01408    }
01409    ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
01410    memcpy(&c->curconf, &zi, sizeof(c->curconf));
01411    return 0;
01412 }
01413 
01414 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
01415 {
01416    int x;
01417    int useslavenative;
01418    struct zt_pvt *slave = NULL;
01419    /* Start out optimistic */
01420    useslavenative = 1;
01421    /* Update conference state in a stateless fashion */
01422    for (x=0;x<3;x++) {
01423       /* Any three-way calling makes slave native mode *definitely* out
01424          of the question */
01425       if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
01426          useslavenative = 0;
01427    }
01428    /* If we don't have any 3-way calls, check to see if we have
01429       precisely one slave */
01430    if (useslavenative) {
01431       for (x=0;x<MAX_SLAVES;x++) {
01432          if (p->slaves[x]) {
01433             if (slave) {
01434                /* Whoops already have a slave!  No 
01435                   slave native and stop right away */
01436                slave = NULL;
01437                useslavenative = 0;
01438                break;
01439             } else {
01440                /* We have one slave so far */
01441                slave = p->slaves[x];
01442             }
01443          }
01444       }
01445    }
01446    /* If no slave, slave native definitely out */
01447    if (!slave)
01448       useslavenative = 0;
01449    else if (slave->law != p->law) {
01450       useslavenative = 0;
01451       slave = NULL;
01452    }
01453    if (out)
01454       *out = slave;
01455    return useslavenative;
01456 }
01457 
01458 static int reset_conf(struct zt_pvt *p)
01459 {
01460    ZT_CONFINFO zi;
01461    memset(&zi, 0, sizeof(zi));
01462    p->confno = -1;
01463    memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
01464    if (p->subs[SUB_REAL].zfd > -1) {
01465       if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
01466          ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
01467    }
01468    return 0;
01469 }
01470 
01471 static int update_conf(struct zt_pvt *p)
01472 {
01473    int needconf = 0;
01474    int x;
01475    int useslavenative;
01476    struct zt_pvt *slave = NULL;
01477 
01478    useslavenative = isslavenative(p, &slave);
01479    /* Start with the obvious, general stuff */
01480    for (x=0;x<3;x++) {
01481       /* Look for three way calls */
01482       if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
01483          conf_add(p, &p->subs[x], x, 0);
01484          needconf++;
01485       } else {
01486          conf_del(p, &p->subs[x], x);
01487       }
01488    }
01489    /* If we have a slave, add him to our conference now. or DAX
01490       if this is slave native */
01491    for (x=0;x<MAX_SLAVES;x++) {
01492       if (p->slaves[x]) {
01493          if (useslavenative)
01494             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
01495          else {
01496             conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
01497             needconf++;
01498          }
01499       }
01500    }
01501    /* If we're supposed to be in there, do so now */
01502    if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
01503       if (useslavenative)
01504          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
01505       else {
01506          conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
01507          needconf++;
01508       }
01509    }
01510    /* If we have a master, add ourselves to his conference */
01511    if (p->master) {
01512       if (isslavenative(p->master, NULL)) {
01513          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
01514       } else {
01515          conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
01516       }
01517    }
01518    if (!needconf) {
01519       /* Nobody is left (or should be left) in our conference.  
01520          Kill it.  */
01521       p->confno = -1;
01522    }
01523    ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
01524    return 0;
01525 }
01526 
01527 static void zt_enable_ec(struct zt_pvt *p)
01528 {
01529    int x;
01530    int res;
01531    if (!p)
01532       return;
01533    if (p->echocanon) {
01534       ast_log(LOG_DEBUG, "Echo cancellation already on\n");
01535       return;
01536    }
01537    if (p->digital) {
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) {
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          ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
01555       }
01556    } else
01557       ast_log(LOG_DEBUG, "No echo cancellation requested\n");
01558 }
01559 
01560 static void zt_train_ec(struct zt_pvt *p)
01561 {
01562    int x;
01563    int res;
01564    if (p && p->echocancel && p->echotraining) {
01565       x = p->echotraining;
01566       res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
01567       if (res) 
01568          ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
01569       else {
01570          ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
01571       }
01572    } else
01573       ast_log(LOG_DEBUG, "No echo training requested\n");
01574 }
01575 
01576 static void zt_disable_ec(struct zt_pvt *p)
01577 {
01578    int x;
01579    int res;
01580    if (p->echocancel) {
01581       x = 0;
01582       res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
01583       if (res) 
01584          ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
01585       else
01586          ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
01587    }
01588    p->echocanon = 0;
01589 }
01590 
01591 static void fill_txgain(struct zt_gains *g, float gain, int law)
01592 {
01593    int j;
01594    int k;
01595    float linear_gain = pow(10.0, gain / 20.0);
01596 
01597    switch (law) {
01598    case ZT_LAW_ALAW:
01599       for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
01600          if (gain) {
01601             k = (int) (((float) AST_ALAW(j)) * linear_gain);
01602             if (k > 32767) k = 32767;
01603             if (k < -32767) k = -32767;
01604             g->txgain[j] = AST_LIN2A(k);
01605          } else {
01606             g->txgain[j] = j;
01607          }
01608       }
01609       break;
01610    case ZT_LAW_MULAW:
01611       for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
01612          if (gain) {
01613             k = (int) (((float) AST_MULAW(j)) * linear_gain);
01614             if (k > 32767) k = 32767;
01615             if (k < -32767) k = -32767;
01616             g->txgain[j] = AST_LIN2MU(k);
01617          } else {
01618             g->txgain[j] = j;
01619          }
01620       }
01621       break;
01622    }
01623 }
01624 
01625 static void fill_rxgain(struct zt_gains *g, float gain, int law)
01626 {
01627    int j;
01628    int k;
01629    float linear_gain = pow(10.0, gain / 20.0);
01630 
01631    switch (law) {
01632    case ZT_LAW_ALAW:
01633       for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
01634          if (gain) {
01635             k = (int) (((float) AST_ALAW(j)) * linear_gain);
01636             if (k > 32767) k = 32767;
01637             if (k < -32767) k = -32767;
01638             g->rxgain[j] = AST_LIN2A(k);
01639          } else {
01640             g->rxgain[j] = j;
01641          }
01642       }
01643       break;
01644    case ZT_LAW_MULAW:
01645       for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
01646          if (gain) {
01647             k = (int) (((float) AST_MULAW(j)) * linear_gain);
01648             if (k > 32767) k = 32767;
01649             if (k < -32767) k = -32767;
01650             g->rxgain[j] = AST_LIN2MU(k);
01651          } else {
01652             g->rxgain[j] = j;
01653          }
01654       }
01655       break;
01656    }
01657 }
01658 
01659 int set_actual_txgain(int fd, int chan, float gain, int law)
01660 {
01661    struct zt_gains g;
01662    int res;
01663 
01664    memset(&g, 0, sizeof(g));
01665    g.chan = chan;
01666    res = ioctl(fd, ZT_GETGAINS, &g);
01667    if (res) {
01668       ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
01669       return res;
01670    }
01671 
01672    fill_txgain(&g, gain, law);
01673 
01674    return ioctl(fd, ZT_SETGAINS, &g);
01675 }
01676 
01677 int set_actual_rxgain(int fd, int chan, float gain, int law)
01678 {
01679    struct zt_gains g;
01680    int res;
01681 
01682    memset(&g, 0, sizeof(g));
01683    g.chan = chan;
01684    res = ioctl(fd, ZT_GETGAINS, &g);
01685    if (res) {
01686       ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
01687       return res;
01688    }
01689 
01690    fill_rxgain(&g, gain, law);
01691 
01692    return ioctl(fd, ZT_SETGAINS, &g);
01693 }
01694 
01695 int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
01696 {
01697    return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
01698 }
01699 
01700 static int bump_gains(struct zt_pvt *p)
01701 {
01702    int res;
01703 
01704    /* Bump receive gain by 5.0db */
01705    res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + 5.0, p->txgain, p->law);
01706    if (res) {
01707       ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
01708       return -1;
01709    }
01710 
01711    return 0;
01712 }
01713 
01714 static int restore_gains(struct zt_pvt *p)
01715 {
01716    int res;
01717 
01718    res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
01719    if (res) {
01720       ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
01721       return -1;
01722    }
01723 
01724    return 0;
01725 }
01726 
01727 static inline int zt_set_hook(int fd, int hs)
01728 {
01729    int x, res;
01730 
01731    x = hs;
01732    res = ioctl(fd, ZT_HOOK, &x);
01733 
01734    if (res < 0) {
01735       if (errno == EINPROGRESS)
01736          return 0;
01737       ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
01738    }
01739 
01740    return res;
01741 }
01742 
01743 static inline int zt_confmute(struct zt_pvt *p, int muted)
01744 {
01745    int x, y, res;
01746    x = muted;
01747    if (p->sig == SIG_PRI) {
01748       y = 1;
01749       res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
01750       if (res)
01751          ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
01752    }
01753    res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
01754    if (res < 0) 
01755       ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
01756    return res;
01757 }
01758 
01759 static int save_conference(struct zt_pvt *p)
01760 {
01761    struct zt_confinfo c;
01762    int res;
01763    if (p->saveconf.confmode) {
01764       ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
01765       return -1;
01766    }
01767    p->saveconf.chan = 0;
01768    res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
01769    if (res) {
01770       ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
01771       p->saveconf.confmode = 0;
01772       return -1;
01773    }
01774    c.chan = 0;
01775    c.confno = 0;
01776    c.confmode = ZT_CONF_NORMAL;
01777    res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
01778    if (res) {
01779       ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
01780       return -1;
01781    }
01782    if (option_debug)
01783       ast_log(LOG_DEBUG, "Disabled conferencing\n");
01784    return 0;
01785 }
01786 
01787 static int restore_conference(struct zt_pvt *p)
01788 {
01789    int res;
01790    if (p->saveconf.confmode) {
01791       res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
01792       p->saveconf.confmode = 0;
01793       if (res) {
01794          ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
01795          return -1;
01796       }
01797    }
01798    if (option_debug)
01799       ast_log(LOG_DEBUG, "Restored conferencing\n");
01800    return 0;
01801 }
01802 
01803 static int send_callerid(struct zt_pvt *p);
01804 
01805 int send_cwcidspill(struct zt_pvt *p)
01806 {
01807    p->callwaitcas = 0;
01808    p->cidcwexpire = 0;
01809    p->cidspill = malloc(MAX_CALLERID_SIZE);
01810    if (p->cidspill) {
01811       memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
01812       p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
01813       /* Make sure we account for the end */
01814       p->cidlen += READ_SIZE * 4;
01815       p->cidpos = 0;
01816       send_callerid(p);
01817       if (option_verbose > 2)
01818          ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
01819    } else return -1;
01820    return 0;
01821 }
01822 
01823 static int has_voicemail(struct zt_pvt *p)
01824 {
01825 
01826    return ast_app_has_voicemail(p->mailbox, NULL);
01827 }
01828 
01829 static int send_callerid(struct zt_pvt *p)
01830 {
01831    /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
01832    int res;
01833    /* Take out of linear mode if necessary */
01834    if (p->subs[SUB_REAL].linear) {
01835       p->subs[SUB_REAL].linear = 0;
01836       zt_setlinear(p->subs[SUB_REAL].zfd, 0);
01837    }
01838    while(p->cidpos < p->cidlen) {
01839       res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
01840       if (res < 0) {
01841          if (errno == EAGAIN)
01842             return 0;
01843          else {
01844             ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
01845             return -1;
01846          }
01847       }
01848       if (!res)
01849          return 0;
01850       p->cidpos += res;
01851    }
01852    free(p->cidspill);
01853    p->cidspill = NULL;
01854    if (p->callwaitcas) {
01855       /* Wait for CID/CW to expire */
01856       p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
01857    } else
01858       restore_conference(p);
01859    return 0;
01860 }
01861 
01862 static int zt_callwait(struct ast_channel *ast)
01863 {
01864    struct zt_pvt *p = ast->tech_pvt;
01865    p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
01866    if (p->cidspill) {
01867       ast_log(LOG_WARNING, "Spill already exists?!?\n");
01868       free(p->cidspill);
01869    }
01870    p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
01871    if (p->cidspill) {
01872       save_conference(p);
01873       /* Silence */
01874       memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
01875       if (!p->callwaitrings && p->callwaitingcallerid) {
01876          ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
01877          p->callwaitcas = 1;
01878          p->cidlen = 2400 + 680 + READ_SIZE * 4;
01879       } else {
01880          ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
01881          p->callwaitcas = 0;
01882          p->cidlen = 2400 + READ_SIZE * 4;
01883       }
01884       p->cidpos = 0;
01885       send_callerid(p);
01886    } else {
01887       ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
01888       return -1;
01889    }
01890    return 0;
01891 }
01892 
01893 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
01894 {
01895    struct zt_pvt *p = ast->tech_pvt;
01896    int x, res, index;
01897    char *c, *n, *l;
01898 #ifdef ZAPATA_PRI
01899    char *s=NULL;
01900 #endif
01901    char dest[256]; /* must be same length as p->dialdest */
01902    ast_mutex_lock(&p->lock);
01903    ast_copy_string(dest, rdest, sizeof(dest));
01904    ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
01905    if ((ast->_state == AST_STATE_BUSY)) {
01906       p->subs[SUB_REAL].needbusy = 1;
01907       ast_mutex_unlock(&p->lock);
01908       return 0;
01909    }
01910    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
01911       ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
01912       ast_mutex_unlock(&p->lock);
01913       return -1;
01914    }
01915    p->dialednone = 0;
01916    if (p->radio)  /* if a radio channel, up immediately */
01917    {
01918       /* Special pseudo -- automatically up */
01919       ast_setstate(ast, AST_STATE_UP); 
01920       ast_mutex_unlock(&p->lock);
01921       return 0;
01922    }
01923    x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
01924    res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
01925    if (res)
01926       ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
01927    p->outgoing = 1;
01928 
01929    set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
01930 
01931    switch(p->sig) {
01932    case SIG_FXOLS:
01933    case SIG_FXOGS:
01934    case SIG_FXOKS:
01935       if (p->owner == ast) {
01936          /* Normal ring, on hook */
01937          
01938          /* Don't send audio while on hook, until the call is answered */
01939          p->dialing = 1;
01940          if (p->use_callerid) {
01941             /* Generate the Caller-ID spill if desired */
01942             if (p->cidspill) {
01943                ast_log(LOG_WARNING, "cidspill already exists??\n");
01944                free(p->cidspill);
01945             }
01946             p->cidspill = malloc(MAX_CALLERID_SIZE);
01947             p->callwaitcas = 0;
01948             if (p->cidspill) {
01949                p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
01950                p->cidpos = 0;
01951                send_callerid(p);
01952             } else
01953                ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
01954          }
01955          /* Choose proper cadence */
01956          if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
01957             if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
01958                ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
01959             p->cidrings = cidrings[p->distinctivering - 1];
01960          } else {
01961             if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
01962                ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
01963             p->cidrings = p->sendcalleridafter;
01964          }
01965 
01966 
01967          /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
01968          c = strchr(dest, '/');
01969          if (c)
01970             c++;
01971          if (c && (strlen(c) < p->stripmsd)) {
01972             ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
01973             c = NULL;
01974          }
01975          if (c) {
01976             p->dop.op = ZT_DIAL_OP_REPLACE;
01977             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
01978             ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
01979          } else {
01980             p->dop.dialstr[0] = '\0';
01981          }
01982          x = ZT_RING;
01983          if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
01984             ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
01985             ast_mutex_unlock(&p->lock);
01986             return -1;
01987          }
01988          p->dialing = 1;
01989       } else {
01990          /* Call waiting call */
01991          p->callwaitrings = 0;
01992          if (ast->cid.cid_num)
01993             ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
01994          else
01995             p->callwait_num[0] = '\0';
01996          if (ast->cid.cid_name)
01997             ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
01998          else
01999             p->callwait_name[0] = '\0';
02000          /* Call waiting tone instead */
02001          if (zt_callwait(ast)) {
02002             ast_mutex_unlock(&p->lock);
02003             return -1;
02004          }
02005          /* Make ring-back */
02006          if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
02007             ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
02008             
02009       }
02010       n = ast->cid.cid_name;
02011       l = ast->cid.cid_num;
02012       if (l)
02013          ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
02014       else
02015          p->lastcid_num[0] = '\0';
02016       if (n)
02017          ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
02018       else
02019          p->lastcid_name[0] = '\0';
02020       ast_setstate(ast, AST_STATE_RINGING);
02021       index = zt_get_index(ast, p, 0);
02022       if (index > -1) {
02023          p->subs[index].needringing = 1;
02024       }
02025       break;
02026    case SIG_FXSLS:
02027    case SIG_FXSGS:
02028    case SIG_FXSKS:
02029    case SIG_EMWINK:
02030    case SIG_EM:
02031    case SIG_EM_E1:
02032    case SIG_FEATD:
02033    case SIG_FEATDMF:
02034    case SIG_E911:
02035    case SIG_FEATB:
02036    case SIG_SFWINK:
02037    case SIG_SF:
02038    case SIG_SF_FEATD:
02039    case SIG_SF_FEATDMF:
02040    case SIG_FEATDMF_TA:
02041    case SIG_SF_FEATB:
02042       c = strchr(dest, '/');
02043       if (c)
02044          c++;
02045       else
02046          c = "";
02047       if (strlen(c) < p->stripmsd) {
02048          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
02049          ast_mutex_unlock(&p->lock);
02050          return -1;
02051       }
02052 #ifdef ZAPATA_PRI
02053       /* Start the trunk, if not GR-303 */
02054       if (!p->pri) {
02055 #endif
02056          x = ZT_START;
02057          res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
02058          if (res < 0) {
02059             if (errno != EINPROGRESS) {
02060                ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
02061                ast_mutex_unlock(&p->lock);
02062                return -1;
02063             }
02064          }
02065 #ifdef ZAPATA_PRI
02066       }
02067 #endif
02068       ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
02069       p->dop.op = ZT_DIAL_OP_REPLACE;
02070 
02071       c += p->stripmsd;
02072 
02073       switch (p->sig) {
02074       case SIG_FEATD:
02075          l = ast->cid.cid_num;
02076          if (l) 
02077             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
02078          else
02079             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
02080          break;
02081       case SIG_FEATDMF:
02082          l = ast->cid.cid_num;
02083          if (l) 
02084             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
02085          else
02086             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
02087          break;
02088       case SIG_FEATDMF_TA:
02089       {
02090          char *cic = NULL, *ozz = NULL;
02091 
02092          /* If you have to go through a Tandem Access point you need to use this */
02093          ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
02094          if (!ozz)
02095             ozz = defaultozz;
02096          cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
02097          if (!cic)
02098             cic = defaultcic;
02099          if (!ozz || !cic) {
02100             ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
02101             ast_mutex_unlock(&p->lock);
02102             return -1;
02103          }
02104          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
02105          snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
02106          p->whichwink = 0;
02107       }
02108          break;
02109       case SIG_E911:
02110          ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
02111          break;
02112       case SIG_FEATB:
02113          snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
02114          break;
02115       default:
02116          if (p->pulse)
02117             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
02118          else
02119             snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
02120          break;
02121       }
02122 
02123       if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
02124          memset(p->echorest, 'w', sizeof(p->echorest) - 1);
02125          strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
02126          p->echorest[sizeof(p->echorest) - 1] = '\0';
02127          p->echobreak = 1;
02128          p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
02129       } else
02130          p->echobreak = 0;
02131       if (!res) {
02132          if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
02133             x = ZT_ONHOOK;
02134             ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
02135             ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
02136             ast_mutex_unlock(&p->lock);
02137             return -1;
02138          }
02139       } else
02140          ast_log(LOG_DEBUG, "Deferring dialing...\n");
02141       p->dialing = 1;
02142       if (ast_strlen_zero(c))
02143          p->dialednone = 1;
02144       ast_setstate(ast, AST_STATE_DIALING);
02145       break;
02146    case 0:
02147       /* Special pseudo -- automatically up*/
02148       ast_setstate(ast, AST_STATE_UP);
02149       break;      
02150    case SIG_PRI:
02151       /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
02152       p->dialdest[0] = '\0';
02153       break;
02154    default:
02155       ast_log(LOG_DEBUG, "not yet implemented\n");
02156       ast_mutex_unlock(&p->lock);
02157       return -1;
02158    }
02159 #ifdef ZAPATA_PRI
02160    if (p->pri) {
02161       struct pri_sr *sr;
02162 #ifdef SUPPORT_USERUSER
02163       char *useruser;
02164 #endif
02165       int pridialplan;
02166       int dp_strip;
02167       int prilocaldialplan;
02168       int ldp_strip;
02169       int exclusive;
02170 
02171       c = strchr(dest, '/');
02172       if (c)
02173          c++;
02174       else
02175          c = dest;
02176       if (!p->hidecallerid) {
02177          l = ast->cid.cid_num;
02178          n = ast->cid.cid_name;
02179       } else {
02180          l = NULL;
02181          n = NULL;
02182       }
02183       if (strlen(c) < p->stripmsd) {
02184          ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
02185          ast_mutex_unlock(&p->lock);
02186          return -1;
02187       }
02188       if (p->sig != SIG_FXSKS) {
02189          p->dop.op = ZT_DIAL_OP_REPLACE;
02190          s = strchr(c + p->stripmsd, 'w');
02191          if (s) {
02192             if (strlen(s) > 1)
02193                snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
02194             else
02195                p->dop.dialstr[0] = '\0';
02196             *s = '\0';
02197          } else {
02198             p->dop.dialstr[0] = '\0';
02199          }
02200       }
02201       if (pri_grab(p, p->pri)) {
02202          ast_log(LOG_WARNING, "Failed to grab PRI!\n");
02203          ast_mutex_unlock(&p->lock);
02204          return -1;
02205       }
02206       if (!(p->call = pri_new_call(p->pri->pri))) {
02207          ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
02208          pri_rel(p->pri);
02209          ast_mutex_unlock(&p->lock);
02210          return -1;
02211       }
02212       if (!(sr = pri_sr_new())) {
02213          ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
02214          pri_rel(p->pri);
02215          ast_mutex_unlock(&p->lock);
02216       }
02217       if (p->bearer || (p->sig == SIG_FXSKS)) {
02218          if (p->bearer) {
02219             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);
02220             p->bearer->call = p->call;
02221          } else
02222             ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
02223          pri_set_crv(p->pri->pri, p->call, p->channel, 0);
02224       }
02225       p->digital = IS_DIGITAL(ast->transfercapability);
02226       /* Add support for exclusive override */
02227       if (p->priexclusive)
02228          exclusive = 1;
02229       else {
02230       /* otherwise, traditional behavior */
02231          if (p->pri->nodetype == PRI_NETWORK)
02232             exclusive = 0;
02233          else
02234             exclusive = 1;
02235       }
02236       
02237       pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
02238       pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
02239                (p->digital ? -1 : 
02240                   ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
02241       if (p->pri->facilityenable)
02242          pri_facility_enable(p->pri->pri);
02243 
02244       if (option_verbose > 2)
02245          ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
02246       dp_strip = 0;
02247       pridialplan = p->pri->dialplan - 1;
02248       if (pridialplan == -2) { /* compute dynamically */
02249          if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
02250             dp_strip = strlen(p->pri->internationalprefix);
02251             pridialplan = PRI_INTERNATIONAL_ISDN;
02252          } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
02253             dp_strip = strlen(p->pri->nationalprefix);
02254             pridialplan = PRI_NATIONAL_ISDN;
02255          } else {
02256             pridialplan = PRI_LOCAL_ISDN;
02257          }
02258       }
02259       pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan,  s ? 1 : 0);
02260 
02261       ldp_strip = 0;
02262       prilocaldialplan = p->pri->localdialplan - 1;
02263       if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
02264          if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
02265             ldp_strip = strlen(p->pri->internationalprefix);
02266             prilocaldialplan = PRI_INTERNATIONAL_ISDN;
02267          } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
02268             ldp_strip = strlen(p->pri->nationalprefix);
02269             prilocaldialplan = PRI_NATIONAL_ISDN;
02270          } else {
02271             prilocaldialplan = PRI_LOCAL_ISDN;
02272          }
02273       }
02274       pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
02275               p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
02276       pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
02277 
02278 #ifdef SUPPORT_USERUSER
02279       /* User-user info */
02280       useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
02281 
02282       if (useruser)
02283          pri_sr_set_useruser(sr, useruser);
02284 #endif
02285 
02286       if (pri_setup(p->pri->pri, p->call,  sr)) {
02287          ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
02288                   c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
02289          pri_rel(p->pri);
02290          ast_mutex_unlock(&p->lock);
02291          pri_sr_free(sr);
02292          return -1;
02293       }
02294       pri_sr_free(sr);
02295       ast_setstate(ast, AST_STATE_DIALING);
02296       pri_rel(p->pri);
02297    }
02298 #endif      
02299    ast_mutex_unlock(&p->lock);
02300    return 0;
02301 }
02302 
02303 static void destroy_zt_pvt(struct zt_pvt **pvt)
02304 {
02305    struct zt_pvt *p = *pvt;
02306    /* Remove channel from the list */
02307    if(p->prev)
02308       p->prev->next = p->next;
02309    if(p->next)
02310       p->next->prev = p->prev;
02311    ast_mutex_destroy(&p->lock);
02312    free(p);
02313    *pvt = NULL;
02314 }
02315 
02316 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
02317 {
02318    int owned = 0;
02319    int i = 0;
02320 
02321    if (!now) {
02322       if (cur->owner) {
02323          owned = 1;
02324       }
02325 
02326       for (i = 0; i < 3; i++) {
02327          if (cur->subs[i].owner) {
02328             owned = 1;
02329          }
02330       }
02331       if (!owned) {
02332          if (prev) {
02333             prev->next = cur->next;
02334             if (prev->next)
02335                prev->next->prev = prev;
02336             else
02337                ifend = prev;
02338          } else {
02339             iflist = cur->next;
02340             if (iflist)
02341                iflist->prev = NULL;
02342             else
02343                ifend = NULL;
02344          }
02345          if (cur->subs[SUB_REAL].zfd > -1) {
02346             zt_close(cur->subs[SUB_REAL].zfd);
02347          }
02348          destroy_zt_pvt(&cur);
02349       }
02350    } else {
02351       if (prev) {
02352          prev->next = cur->next;
02353          if (prev->next)
02354             prev->next->prev = prev;
02355          else
02356             ifend = prev;
02357       } else {
02358          iflist = cur->next;
02359          if (iflist)
02360             iflist->prev = NULL;
02361          else
02362             ifend = NULL;
02363       }
02364       if (cur->subs[SUB_REAL].zfd > -1) {
02365          zt_close(cur->subs[SUB_REAL].zfd);
02366       }
02367       destroy_zt_pvt(&cur);
02368    }
02369    return 0;
02370 }
02371 
02372 #ifdef ZAPATA_PRI
02373 int pri_is_up(struct zt_pri *pri)
02374 {
02375    int x;
02376    for (x=0;x<NUM_DCHANS;x++) {
02377       if (pri->dchanavail[x] == DCHAN_AVAILABLE)
02378          return 1;
02379    }
02380    return 0;
02381 }
02382 
02383 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
02384 {
02385    bearer->owner = &inuse;
02386    bearer->realcall = crv;
02387    crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
02388    if (crv->subs[SUB_REAL].owner)
02389       crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
02390    crv->bearer = bearer;
02391    crv->call = bearer->call;
02392    crv->pri = pri;
02393    return 0;
02394 }
02395 
02396 static char *pri_order(int level)
02397 {
02398    switch(level) {
02399    case 0:
02400       return "Primary";
02401    case 1:
02402       return "Secondary";
02403    case 2:
02404       return "Tertiary";
02405    case 3:
02406       return "Quaternary";
02407    default:
02408       return "<Unknown>";
02409    }     
02410 }
02411 
02412 /* Returns fd of the active dchan */
02413 int pri_active_dchan_fd(struct zt_pri *pri)
02414 {
02415    int x = -1;
02416 
02417    for (x = 0; x < NUM_DCHANS; x++) {
02418       if ((pri->dchans[x] == pri->pri))
02419          break;
02420    }
02421 
02422    return pri->fds[x];
02423 }
02424 
02425 int pri_find_dchan(struct zt_pri *pri)
02426 {
02427    int oldslot = -1;
02428    struct pri *old;
02429    int newslot = -1;
02430    int x;
02431    old = pri->pri;
02432    for(x=0;x<NUM_DCHANS;x++) {
02433       if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
02434          newslot = x;
02435       if (pri->dchans[x] == old) {
02436          oldslot = x;
02437       }
02438    }
02439    if (newslot < 0) {
02440       newslot = 0;
02441       ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
02442          pri->dchannels[newslot]);
02443    }
02444    if (old && (oldslot != newslot))
02445       ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
02446          pri->dchannels[oldslot], pri->dchannels[newslot]);
02447    pri->pri = pri->dchans[newslot];
02448    return 0;
02449 }
02450 #endif
02451 
02452 static int zt_hangup(struct ast_channel *ast)
02453 {
02454    int res;
02455    int index,x, law;
02456    /*static int restore_gains(struct zt_pvt *p);*/
02457    struct zt_pvt *p = ast->tech_pvt;
02458    struct zt_pvt *tmp = NULL;
02459    struct zt_pvt *prev = NULL;
02460    ZT_PARAMS par;
02461 
02462    if (option_debug)
02463       ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
02464    if (!ast->tech_pvt) {
02465       ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
02466       return 0;
02467    }
02468    
02469    ast_mutex_lock(&p->lock);
02470    
02471    index = zt_get_index(ast, p, 1);
02472 
02473    if (p->sig == SIG_PRI) {
02474       x = 1;
02475       ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
02476    }
02477 
02478    x = 0;
02479    zt_confmute(p, 0);
02480    restore_gains(p);
02481    if (p->origcid_num) {
02482       ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
02483       free(p->origcid_num);
02484       p->origcid_num = NULL;
02485    }  
02486    if (p->origcid_name) {
02487       ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
02488       free(p->origcid_name);
02489       p->origcid_name = NULL;
02490    }  
02491    if (p->dsp)
02492       ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
02493    if (p->exten)
02494       p->exten[0] = '\0';
02495 
02496    ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
02497       p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
02498    p->ignoredtmf = 0;
02499    
02500    if (index > -1) {
02501       /* Real channel, do some fixup */
02502       p->subs[index].owner = NULL;
02503       p->subs[index].needanswer = 0;
02504       p->subs[index].needflash = 0;
02505       p->subs[index].needringing = 0;
02506       p->subs[index].needbusy = 0;
02507       p->subs[index].needcongestion = 0;
02508       p->subs[index].linear = 0;
02509       p->subs[index].needcallerid = 0;
02510       p->polarity = POLARITY_IDLE;
02511       zt_setlinear(p->subs[index].zfd, 0);
02512       if (index == SUB_REAL) {
02513          if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
02514             ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
02515             if (p->subs[SUB_CALLWAIT].inthreeway) {
02516                /* We had flipped over to answer a callwait and now it's gone */
02517                ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
02518                /* Move to the call-wait, but un-own us until they flip back. */
02519                swap_subs(p, SUB_CALLWAIT, SUB_REAL);
02520                unalloc_sub(p, SUB_CALLWAIT);
02521                p->owner = NULL;
02522             } else {
02523                /* The three way hung up, but we still have a call wait */
02524                ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
02525                swap_subs(p, SUB_THREEWAY, SUB_REAL);
02526                unalloc_sub(p, SUB_THREEWAY);
02527                if (p->subs[SUB_REAL].inthreeway) {
02528                   /* This was part of a three way call.  Immediately make way for
02529                      another call */
02530                   ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
02531                   p->owner = p->subs[SUB_REAL].owner;
02532                } else {
02533                   /* This call hasn't been completed yet...  Set owner to NULL */
02534                   ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
02535                   p->owner = NULL;
02536                }
02537                p->subs[SUB_REAL].inthreeway = 0;
02538             }
02539          } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
02540             /* Move to the call-wait and switch back to them. */
02541             swap_subs(p, SUB_CALLWAIT, SUB_REAL);
02542             unalloc_sub(p, SUB_CALLWAIT);
02543             p->owner = p->subs[SUB_REAL].owner;
02544             if (p->owner->_state != AST_STATE_UP)
02545                p->subs[SUB_REAL].needanswer = 1;
02546             if (ast_bridged_channel(p->subs[SUB_REAL].owner))
02547                ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
02548          } else if (p->subs[SUB_THREEWAY].zfd > -1) {
02549             swap_subs(p, SUB_THREEWAY, SUB_REAL);
02550             unalloc_sub(p, SUB_THREEWAY);
02551             if (p->subs[SUB_REAL].inthreeway) {
02552                /* This was part of a three way call.  Immediately make way for
02553                   another call */
02554                ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
02555                p->owner = p->subs[SUB_REAL].owner;
02556             } else {
02557                /* This call hasn't been completed yet...  Set owner to NULL */
02558                ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
02559                p->owner = NULL;
02560             }
02561             p->subs[SUB_REAL].inthreeway = 0;
02562          }
02563       } else if (index == SUB_CALLWAIT) {
02564          /* Ditch the holding callwait call, and immediately make it availabe */
02565          if (p->subs[SUB_CALLWAIT].inthreeway) {
02566             /* This is actually part of a three way, placed on hold.  Place the third part
02567                on music on hold now */
02568             if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
02569                ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
02570             p->subs[SUB_THREEWAY].inthreeway = 0;
02571             /* Make it the call wait now */
02572             swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
02573             unalloc_sub(p, SUB_THREEWAY);
02574          } else
02575             unalloc_sub(p, SUB_CALLWAIT);
02576       } else if (index == SUB_THREEWAY) {
02577          if (p->subs[SUB_CALLWAIT].inthreeway) {
02578             /* The other party of the three way call is currently in a call-wait state.
02579                Start music on hold for them, and take the main guy out of the third call */
02580             if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
02581                ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
02582             p->subs[SUB_CALLWAIT].inthreeway = 0;
02583          }
02584          p->subs[SUB_REAL].inthreeway = 0;
02585          /* If this was part of a three way call index, let us make
02586             another three way call */
02587          unalloc_sub(p, SUB_THREEWAY);
02588       } else {
02589          /* This wasn't any sort of call, but how are we an index? */
02590          ast_log(LOG_WARNING, "Index found but not any type of call?\n");
02591       }
02592    }
02593 
02594 
02595    if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
02596       p->owner = NULL;
02597       p->ringt = 0;
02598       p->distinctivering = 0;
02599       p->confirmanswer = 0;
02600       p->cidrings = 1;
02601       p->outgoing = 0;
02602       p->digital = 0;
02603       p->faxhandled = 0;
02604       p->pulsedial = 0;
02605       p->onhooktime = time(NULL);
02606 #ifdef ZAPATA_PRI
02607       p->proceeding = 0;
02608       p->progress = 0;
02609       p->alerting = 0;
02610       p->setup_ack = 0;
02611 #endif      
02612       if (p->dsp) {
02613          ast_dsp_free(p->dsp);
02614          p->dsp = NULL;
02615       }
02616 
02617       law = ZT_LAW_DEFAULT;
02618       res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
02619       if (res < 0) 
02620          ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
02621       /* Perform low level hangup if no owner left */
02622 #ifdef ZAPATA_PRI
02623       if (p->pri) {
02624 #ifdef SUPPORT_USERUSER
02625          char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
02626 #endif
02627 
02628          /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
02629          if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
02630             if (!pri_grab(p, p->pri)) {
02631                if (p->alreadyhungup) {
02632                   ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
02633 
02634 #ifdef SUPPORT_USERUSER
02635                   pri_call_set_useruser(p->call, useruser);
02636 #endif
02637 
02638                   pri_hangup(p->pri->pri, p->call, -1);
02639                   p->call = NULL;
02640                   if (p->bearer) 
02641                      p->bearer->call = NULL;
02642                } else {
02643                   char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
02644                   int icause = ast->hangupcause ? ast->hangupcause : -1;
02645                   ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
02646 
02647 #ifdef SUPPORT_USERUSER
02648                   pri_call_set_useruser(p->call, useruser);
02649 #endif
02650 
02651                   p->alreadyhungup = 1;
02652                   if (p->bearer)
02653                      p->bearer->alreadyhungup = 1;
02654                   if (cause) {
02655                      if (atoi(cause))
02656                         icause = atoi(cause);
02657                   }
02658                   pri_hangup(p->pri->pri, p->call, icause);
02659                }
02660                if (res < 0) 
02661                   ast_log(LOG_WARNING, "pri_disconnect failed\n");
02662                pri_rel(p->pri);        
02663             } else {
02664                ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
02665                res = -1;
02666             }
02667          } else {
02668             if (p->bearer)
02669                ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
02670             p->call = NULL;
02671             res = 0;
02672          }
02673       }
02674 #endif
02675 #ifdef ZAPATA_R2
02676       if (p->sig == SIG_R2) {
02677          if (p->hasr2call) {
02678             mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
02679             p->hasr2call = 0;
02680             res = 0;
02681          } else
02682             res = 0;
02683 
02684       }
02685 #endif
02686       if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
02687          res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
02688       if (res < 0) {
02689          ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
02690       }
02691       switch(p->sig) {
02692       case SIG_FXOGS:
02693       case SIG_FXOLS:
02694       case SIG_FXOKS:
02695          res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
02696          if (!res) {
02697 #if 0
02698             ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
02699 #endif
02700             /* If they're off hook, try playing congestion */
02701             if ((par.rxisoffhook) && (!p->radio))
02702                tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
02703             else
02704                tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
02705          }
02706          break;
02707       case SIG_FXSGS:
02708       case SIG_FXSLS:
02709       case SIG_FXSKS:
02710          /* Make sure we're not made available for at least two seconds assuming
02711             we were actually used for an inbound or outbound call. */
02712          if (ast->_state != AST_STATE_RESERVED) {
02713             time(&p->guardtime);
02714             p->guardtime += 2;
02715          }
02716          break;
02717       default:
02718          tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
02719       }
02720       if (p->cidspill)
02721          free(p->cidspill);
02722       if (p->sig)
02723          zt_disable_ec(p);
02724       x = 0;
02725       ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
02726       ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
02727       p->didtdd = 0;
02728       p->cidspill = NULL;
02729       p->callwaitcas = 0;
02730       p->callwaiting = p->permcallwaiting;
02731       p->hidecallerid = p->permhidecallerid;
02732       p->dialing = 0;
02733       p->rdnis[0] = '\0';
02734       update_conf(p);
02735       reset_conf(p);
02736       /* Restore data mode */
02737       if (p->sig == SIG_PRI) {
02738          x = 0;
02739          ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
02740       }
02741 #ifdef ZAPATA_PRI
02742       if (p->bearer) {
02743          ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
02744          /* Free up the bearer channel as well, and
02745             don't use its file descriptor anymore */
02746          update_conf(p->bearer);
02747          reset_conf(p->bearer);
02748          p->bearer->owner = NULL;
02749          p->bearer->realcall = NULL;
02750          p->bearer = NULL;
02751          p->subs[SUB_REAL].zfd = -1;
02752          p->pri = NULL;
02753       }
02754 #endif
02755       restart_monitor();
02756    }
02757 
02758 
02759    p->callwaitingrepeat = 0;
02760    p->cidcwexpire = 0;
02761    ast->tech_pvt = NULL;
02762    ast_mutex_unlock(&p->lock);
02763    ast_mutex_lock(&usecnt_lock);
02764    usecnt--;
02765    if (usecnt < 0) 
02766       ast_log(LOG_WARNING, "Usecnt < 0???\n");
02767    ast_mutex_unlock(&usecnt_lock);
02768    ast_update_use_count();
02769    if (option_verbose > 2) 
02770       ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
02771 
02772    ast_mutex_lock(&iflock);
02773    tmp = iflist;
02774    prev = NULL;
02775    if (p->destroy) {
02776       while (tmp) {
02777          if (tmp == p) {
02778             destroy_channel(prev, tmp, 0);
02779             break;
02780          } else {
02781             prev = tmp;
02782             tmp = tmp->next;
02783          }
02784       }
02785    }
02786    ast_mutex_unlock(&iflock);
02787    return 0;
02788 }
02789 
02790 static int zt_answer(struct ast_channel *ast)
02791 {
02792    struct zt_pvt *p = ast->tech_pvt;
02793    int res=0;
02794    int index;
02795    int oldstate = ast->_state;
02796    ast_setstate(ast, AST_STATE_UP);
02797    ast_mutex_lock(&p->lock);
02798    index = zt_get_index(ast, p, 0);
02799    if (index < 0)
02800       index = SUB_REAL;
02801    /* nothing to do if a radio channel */
02802    if (p->radio) {
02803       ast_mutex_unlock(&p->lock);
02804       return 0;
02805    }
02806    switch(p->sig) {
02807    case SIG_FXSLS:
02808    case SIG_FXSGS:
02809    case SIG_FXSKS:
02810       p->ringt = 0;
02811       /* Fall through */
02812    case SIG_EM:
02813    case SIG_EM_E1:
02814    case SIG_EMWINK:
02815    case SIG_FEATD:
02816    case SIG_FEATDMF:
02817    case SIG_E911:
02818    case SIG_FEATB:
02819    case SIG_SF:
02820    case SIG_SFWINK:
02821    case SIG_SF_FEATD:
02822    case SIG_SF_FEATDMF:
02823    case SIG_SF_FEATB:
02824    case SIG_FXOLS:
02825    case SIG_FXOGS:
02826    case SIG_FXOKS:
02827       /* Pick up the line */
02828       ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
02829       if(p->hanguponpolarityswitch) {
02830          gettimeofday(&p->polaritydelaytv, NULL);
02831       }
02832       res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
02833       tone_zone_play_tone(p->subs[index].zfd, -1);
02834       p->dialing = 0;
02835       if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
02836          if (oldstate == AST_STATE_RINGING) {
02837             ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
02838             tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
02839             swap_subs(p, SUB_THREEWAY, SUB_REAL);
02840             p->owner = p->subs[SUB_REAL].owner;
02841          }
02842       }
02843       if (p->sig & __ZT_SIG_FXS) {
02844          zt_enable_ec(p);
02845          zt_train_ec(p);
02846       }
02847       break;
02848 #ifdef ZAPATA_PRI
02849    case SIG_PRI:
02850       /* Send a pri acknowledge */
02851       if (!pri_grab(p, p->pri)) {
02852          p->proceeding = 1;
02853          res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
02854          pri_rel(p->pri);
02855       } else {
02856          ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
02857          res= -1;
02858       }
02859       break;
02860 #endif
02861 #ifdef ZAPATA_R2
02862    case SIG_R2:
02863       res = mfcr2_AnswerCall(p->r2, NULL);
02864       if (res)
02865          ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
02866       break;
02867 #endif         
02868    case 0:
02869       ast_mutex_unlock(&p->lock);
02870       return 0;
02871    default:
02872       ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
02873       res = -1;
02874    }
02875    ast_mutex_unlock(&p->lock);
02876    return res;
02877 }
02878 
02879 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
02880 {
02881    char *cp;
02882    signed char *scp;
02883    int x;
02884    int index;
02885    struct zt_pvt *p = chan->tech_pvt;
02886 
02887    /* all supported options require data */
02888    if (!data || (datalen < 1)) {
02889       errno = EINVAL;
02890       return -1;
02891    }
02892 
02893    switch(option) {
02894    case AST_OPTION_TXGAIN:
02895       scp = (signed char *) data;
02896       index = zt_get_index(chan, p, 0);
02897       if (index < 0) {
02898          ast_log(LOG_WARNING, "No index in TXGAIN?\n");
02899          return -1;
02900       }
02901       ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
02902       return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
02903    case AST_OPTION_RXGAIN:
02904       scp = (signed char *) data;
02905       index = zt_get_index(chan, p, 0);
02906       if (index < 0) {
02907          ast_log(LOG_WARNING, "No index in RXGAIN?\n");
02908          return -1;
02909       }
02910       ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
02911       return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
02912    case AST_OPTION_TONE_VERIFY:
02913       if (!p->dsp)
02914          break;
02915       cp = (char *) data;
02916       switch (*cp) {
02917       case 1:
02918          ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
02919          ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
02920          break;
02921       case 2:
02922          ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
02923          ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
02924          break;
02925       default:
02926          ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
02927          ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
02928          break;
02929       }
02930       break;
02931    case AST_OPTION_TDD:
02932       /* turn on or off TDD */
02933       cp = (char *) data;
02934       p->mate = 0;
02935       if (!*cp) { /* turn it off */
02936          ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
02937          if (p->tdd) tdd_free(p->tdd);
02938          p->tdd = 0;
02939          break;
02940       }
02941       ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
02942          (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
02943       zt_disable_ec(p);
02944       /* otherwise, turn it on */
02945       if (!p->didtdd) { /* if havent done it yet */
02946          unsigned char mybuf[41000],*buf;
02947          int size,res,fd,len;
02948          struct pollfd fds[1];
02949 
02950          buf = mybuf;
02951          memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
02952          ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
02953          len = 40000;
02954          index = zt_get_index(chan, p, 0);
02955          if (index < 0) {
02956             ast_log(LOG_WARNING, "No index in TDD?\n");
02957             return -1;
02958          }
02959          fd = p->subs[index].zfd;
02960          while(len) {
02961             if (ast_check_hangup(chan)) return -1;
02962             size = len;
02963             if (size > READ_SIZE)
02964                size = READ_SIZE;
02965             fds[0].fd = fd;
02966             fds[0].events = POLLPRI | POLLOUT;
02967             fds[0].revents = 0;
02968             res = poll(fds, 1, -1);
02969             if (!res) {
02970                ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
02971                continue;
02972             }
02973             /* if got exception */
02974             if (fds[0].revents & POLLPRI) return -1;
02975             if (!(fds[0].revents & POLLOUT)) {
02976                ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
02977                continue;
02978             }
02979             res = write(fd, buf, size);
02980             if (res != size) {
02981                if (res == -1) return -1;
02982                ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
02983                break;
02984             }
02985             len -= size;
02986             buf += size;
02987          }
02988          p->didtdd = 1; /* set to have done it now */    
02989       }
02990       if (*cp == 2) { /* Mate mode */
02991          if (p->tdd) tdd_free(p->tdd);
02992          p->tdd = 0;
02993          p->mate = 1;
02994          break;
02995       }     
02996       if (!p->tdd) { /* if we dont have one yet */
02997          p->tdd = tdd_new(); /* allocate one */
02998       }     
02999       break;
03000    case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
03001       if (!p->dsp)
03002          break;
03003       cp = (char *) data;
03004       ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
03005          *cp ? "ON" : "OFF", (int) *cp, chan->name);
03006       ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
03007       break;
03008    case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
03009       cp = (char *) data;
03010       if (!*cp) {    
03011          ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
03012          x = 0;
03013          zt_disable_ec(p);
03014       } else {    
03015          ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
03016          x = 1;
03017       }
03018       if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
03019          ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
03020       break;
03021    }
03022    errno = 0;
03023 
03024    return 0;
03025 }
03026 
03027 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
03028 {
03029    /* Unlink a specific slave or all slaves/masters from a given master */
03030    int x;
03031    int hasslaves;
03032    if (!master)
03033       return;
03034    if (needlock) {
03035       ast_mutex_lock(&master->lock);
03036       if (slave) {
03037          while(ast_mutex_trylock(&slave->lock)) {
03038             ast_mutex_unlock(&master->lock);
03039             usleep(1);
03040             ast_mutex_lock(&master->lock);
03041          }
03042       }
03043    }
03044    hasslaves = 0;
03045    for (x=0;x<MAX_SLAVES;x++) {
03046       if (master->slaves[x]) {
03047          if (!slave || (master->slaves[x] == slave)) {
03048             /* Take slave out of the conference */
03049             ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
03050             conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
03051             conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
03052             master->slaves[x]->master = NULL;
03053             master->slaves[x] = NULL;
03054          } else
03055             hasslaves = 1;
03056       }
03057       if (!hasslaves)
03058          master->inconference = 0;
03059    }
03060    if (!slave) {
03061       if (master->master) {
03062          /* Take master out of the conference */
03063          conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
03064          conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
03065          hasslaves = 0;
03066          for (x=0;x<MAX_SLAVES;x++) {
03067             if (master->master->slaves[x] == master)
03068                master->master->slaves[x] = NULL;
03069             else if (master->master->slaves[x])
03070                hasslaves = 1;
03071          }
03072          if (!hasslaves)
03073             master->master->inconference = 0;
03074       }
03075       master->master = NULL;
03076    }
03077    update_conf(master);
03078    if (needlock) {
03079       if (slave)
03080          ast_mutex_unlock(&slave->lock);
03081       ast_mutex_unlock(&master->lock);
03082    }
03083 }
03084 
03085 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
03086    int x;
03087    if (!slave || !master) {
03088       ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
03089       return;
03090    }
03091    for (x=0;x<MAX_SLAVES;x++) {
03092       if (!master->slaves[x]) {
03093          master->slaves[x] = slave;
03094          break;
03095       }
03096    }
03097    if (x >= MAX_SLAVES) {
03098       ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
03099       master->slaves[MAX_SLAVES - 1] = slave;
03100    }
03101    if (slave->master) 
03102       ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
03103    slave->master = master;
03104    
03105    ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
03106 }
03107 
03108 static void disable_dtmf_detect(struct zt_pvt *p)
03109 {
03110 #ifdef ZT_TONEDETECT
03111    int val;
03112 #endif
03113 
03114    p->ignoredtmf = 1;
03115 
03116 #ifdef ZT_TONEDETECT
03117    val = 0;
03118    ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
03119 #endif      
03120    if (!p->hardwaredtmf && p->dsp) {
03121       p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
03122       ast_dsp_set_features(p->dsp, p->dsp_features);
03123    }
03124 }
03125 
03126 static void enable_dtmf_detect(struct zt_pvt *p)
03127 {
03128 #ifdef ZT_TONEDETECT
03129    int val;
03130 #endif
03131 
03132    if (p->channel == CHAN_PSEUDO)
03133       return;
03134 
03135    p->ignoredtmf = 0;
03136 
03137 #ifdef ZT_TONEDETECT
03138    val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
03139    ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
03140 #endif      
03141    if (!p->hardwaredtmf && p->dsp) {
03142       p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
03143       ast_dsp_set_features(p->dsp, p->dsp_features);
03144    }
03145 }
03146 
03147 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)
03148 {
03149    struct ast_channel *who;
03150    struct zt_pvt *p0, *p1, *op0, *op1;
03151    struct zt_pvt *master = NULL, *slave = NULL;
03152    struct ast_frame *f;
03153    int inconf = 0;
03154    int nothingok = 1;
03155    int ofd0, ofd1;
03156    int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
03157    int os0 = -1, os1 = -1;
03158    int priority = 0;
03159    struct ast_channel *oc0, *oc1;
03160    enum ast_bridge_result res;
03161 
03162 #ifdef PRI_2BCT
03163    int triedtopribridge = 0;
03164    q931_call *q931c0 = NULL, *q931c1 = NULL;
03165 #endif
03166 
03167    /* For now, don't attempt to native bridge if either channel needs DTMF detection.
03168       There is code below to handle it properly until DTMF is actually seen,
03169       but due to currently unresolved issues it's ignored...
03170    */
03171 
03172    if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
03173       return AST_BRIDGE_FAILED_NOWARN;
03174 
03175    ast_mutex_lock(&c0->lock);
03176    ast_mutex_lock(&c1->lock);
03177 
03178    p0 = c0->tech_pvt;
03179    p1 = c1->tech_pvt;
03180    /* cant do pseudo-channels here */
03181    if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
03182       ast_mutex_unlock(&c0->lock);
03183       ast_mutex_unlock(&c1->lock);
03184       return AST_BRIDGE_FAILED_NOWARN;
03185    }
03186 
03187    oi0 = zt_get_index(c0, p0, 0);
03188    oi1 = zt_get_index(c1, p1, 0);
03189    if ((oi0 < 0) || (oi1 < 0)) {
03190       ast_mutex_unlock(&c0->lock);
03191       ast_mutex_unlock(&c1->lock);
03192       return AST_BRIDGE_FAILED;
03193    }
03194 
03195    op0 = p0 = c0->tech_pvt;
03196    op1 = p1 = c1->tech_pvt;
03197    ofd0 = c0->fds[0];
03198    ofd1 = c1->fds[0];
03199    oc0 = p0->owner;
03200    oc1 = p1->owner;
03201 
03202    if (ast_mutex_trylock(&p0->lock)) {
03203       /* Don't block, due to potential for deadlock */
03204       ast_mutex_unlock(&c0->lock);
03205       ast_mutex_unlock(&c1->lock);
03206       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
03207       return AST_BRIDGE_RETRY;
03208    }
03209    if (ast_mutex_trylock(&p1->lock)) {
03210       /* Don't block, due to potential for deadlock */
03211       ast_mutex_unlock(&p0->lock);
03212       ast_mutex_unlock(&c0->lock);
03213       ast_mutex_unlock(&c1->lock);
03214       ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
03215       return AST_BRIDGE_RETRY;
03216    }
03217 
03218    if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
03219       if (p0->owner && p1->owner) {
03220          /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
03221          if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
03222             master = p0;
03223             slave = p1;
03224             inconf = 1;
03225          } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
03226             master = p1;
03227             slave = p0;
03228             inconf = 1;
03229          } else {
03230             ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
03231             ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
03232                p0->channel,
03233                oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
03234                p0->subs[SUB_REAL].inthreeway, p0->channel,
03235                oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
03236                p1->subs[SUB_REAL].inthreeway);
03237          }
03238          nothingok = 0;
03239       }
03240    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
03241       if (p1->subs[SUB_THREEWAY].inthreeway) {
03242          master = p1;
03243          slave = p0;
03244          nothingok = 0;
03245       }
03246    } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
03247       if (p0->subs[SUB_THREEWAY].inthreeway) {
03248          master = p0;
03249          slave = p1;
03250          nothingok = 0;
03251       }
03252    } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
03253       /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
03254          don't put us in anything */
03255       if (p1->subs[SUB_CALLWAIT].inthreeway) {
03256          master = p1;
03257          slave = p0;
03258          nothingok = 0;
03259       }
03260    } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
03261       /* Same as previous */
03262       if (p0->subs[SUB_CALLWAIT].inthreeway) {
03263          master = p0;
03264          slave = p1;
03265          nothingok = 0;
03266       }
03267    }
03268    ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
03269       master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
03270    if (master && slave) {
03271       /* Stop any tones, or play ringtone as appropriate.  If they're bridged
03272          in an active threeway call with a channel that is ringing, we should
03273          indicate ringing. */
03274       if ((oi1 == SUB_THREEWAY) && 
03275           p1->subs[SUB_THREEWAY].inthreeway && 
03276           p1->subs[SUB_REAL].owner && 
03277           p1->subs[SUB_REAL].inthreeway && 
03278           (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
03279          ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
03280          tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
03281          os1 = p1->subs[SUB_REAL].owner->_state;
03282       } else {
03283          ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
03284          tone_zone_play_tone(p0->subs[oi0].zfd, -1);
03285       }
03286       if ((oi0 == SUB_THREEWAY) && 
03287           p0->subs[SUB_THREEWAY].inthreeway && 
03288           p0->subs[SUB_REAL].owner && 
03289           p0->subs[SUB_REAL].inthreeway && 
03290           (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
03291          ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
03292          tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
03293          os0 = p0->subs[SUB_REAL].owner->_state;
03294       } else {
03295          ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
03296          tone_zone_play_tone(p1->subs[oi0].zfd, -1);
03297       }
03298       if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
03299          if (!p0->echocanbridged || !p1->echocanbridged) {
03300             /* Disable echo cancellation if appropriate */
03301             zt_disable_ec(p0);
03302             zt_disable_ec(p1);
03303          }
03304       }
03305       zt_link(slave, master);
03306       master->inconference = inconf;
03307    } else if (!nothingok)
03308       ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
03309 
03310    update_conf(p0);
03311    update_conf(p1);
03312    t0 = p0->subs[SUB_REAL].inthreeway;
03313    t1 = p1->subs[SUB_REAL].inthreeway;
03314 
03315    ast_mutex_unlock(&p0->lock);
03316    ast_mutex_unlock(&p1->lock);
03317 
03318    ast_mutex_unlock(&c0->lock);
03319    ast_mutex_unlock(&c1->lock);
03320 
03321    /* Native bridge failed */
03322    if ((!master || !slave) && !nothingok) {
03323       zt_enable_ec(p0);
03324       zt_enable_ec(p1);
03325       return AST_BRIDGE_FAILED;
03326    }
03327    
03328    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
03329       disable_dtmf_detect(op0);
03330 
03331    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
03332       disable_dtmf_detect(op1);
03333 
03334    for (;;) {
03335       struct ast_channel *c0_priority[2] = {c0, c1};
03336       struct ast_channel *c1_priority[2] = {c1, c0};
03337 
03338       /* Here's our main loop...  Start by locking things, looking for private parts, 
03339          and then balking if anything is wrong */
03340       ast_mutex_lock(&c0->lock);
03341       ast_mutex_lock(&c1->lock);
03342       p0 = c0->tech_pvt;
03343       p1 = c1->tech_pvt;
03344 
03345       if (op0 == p0)
03346          i0 = zt_get_index(c0, p0, 1);
03347       if (op1 == p1)
03348          i1 = zt_get_index(c1, p1, 1);
03349       ast_mutex_unlock(&c0->lock);
03350       ast_mutex_unlock(&c1->lock);
03351 
03352       if (!timeoutms || 
03353           (op0 != p0) ||
03354           (op1 != p1) || 
03355           (ofd0 != c0->fds[0]) || 
03356           (ofd1 != c1->fds[0]) ||
03357           (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) || 
03358           (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) || 
03359           (oc0 != p0->owner) || 
03360           (oc1 != p1->owner) ||
03361           (t0 != p0->subs[SUB_REAL].inthreeway) ||
03362           (t1 != p1->subs[SUB_REAL].inthreeway) ||
03363           (oi0 != i0) ||
03364           (oi1 != i1)) {
03365          ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
03366             op0->channel, oi0, op1->channel, oi1);
03367          res = AST_BRIDGE_RETRY;
03368          goto return_from_bridge;
03369       }
03370 
03371 #ifdef PRI_2BCT
03372       q931c0 = p0->call;
03373       q931c1 = p1->call;
03374       if (p0->transfer && p1->transfer 
03375           && q931c0 && q931c1 
03376           && !triedtopribridge) {
03377          pri_channel_bridge(q931c0, q931c1);
03378          triedtopribridge = 1;
03379       }
03380 #endif
03381 
03382       who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
03383       if (!who) {
03384          ast_log(LOG_DEBUG, "Ooh, empty read...\n");
03385          continue;
03386       }
03387       f = ast_read(who);
03388       if (!f || (f->frametype == AST_FRAME_CONTROL)) {
03389          *fo = f;
03390          *rc = who;
03391          res = AST_BRIDGE_COMPLETE;
03392          goto return_from_bridge;
03393       }
03394       if (f->frametype == AST_FRAME_DTMF) {
03395          if ((who == c0) && p0->pulsedial) {
03396             ast_write(c1, f);
03397          } else if ((who == c1) && p1->pulsedial) {
03398             ast_write(c0, f);
03399          } else {
03400             *fo = f;
03401             *rc = who;
03402             res = AST_BRIDGE_COMPLETE;
03403             goto return_from_bridge;
03404          }
03405       }
03406       ast_frfree(f);
03407       
03408       /* Swap who gets priority */
03409       priority = !priority;
03410    }
03411 
03412 return_from_bridge:
03413    if (op0 == p0)
03414       zt_enable_ec(p0);
03415 
03416    if (op1 == p1)
03417       zt_enable_ec(p1);
03418 
03419    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
03420       enable_dtmf_detect(op0);
03421 
03422    if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
03423       enable_dtmf_detect(op1);
03424 
03425    zt_unlink(slave, master, 1);
03426 
03427    return res;
03428 }
03429 
03430 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
03431 {
03432    struct zt_pvt *p = newchan->tech_pvt;
03433    int x;
03434    ast_mutex_lock(&p->lock);
03435    ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
03436    if (p->owner == oldchan) {
03437       p->owner = newchan;
03438    }
03439    for (x=0;x<3;x++)
03440       if (p->subs[x].owner == oldchan) {
03441          if (!x)
03442             zt_unlink(NULL, p, 0);
03443          p->subs[x].owner = newchan;
03444       }
03445    if (newchan->_state == AST_STATE_RINGING) 
03446       zt_indicate(newchan, AST_CONTROL_RINGING);
03447    update_conf(p);
03448    ast_mutex_unlock(&p->lock);
03449    return 0;
03450 }
03451 
03452 static int zt_ring_phone(struct zt_pvt *p)
03453 {
03454    int x;
03455    int res;
03456    /* Make sure our transmit state is on hook */
03457    x = 0;
03458    x = ZT_ONHOOK;
03459    res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
03460    do {
03461       x = ZT_RING;
03462       res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
03463       if (res) {
03464          switch(errno) {
03465          case EBUSY:
03466          case EINTR:
03467             /* Wait just in case */
03468             usleep(10000);
03469             continue;
03470          case EINPROGRESS:
03471             res = 0;
03472             break;
03473          default:
03474             ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
03475             res = 0;
03476          }
03477       }
03478    } while (res);
03479    return res;
03480 }
03481 
03482 static void *ss_thread(void *data);
03483 
03484 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
03485 
03486 static int attempt_transfer(struct zt_pvt *p)
03487 {
03488    /* In order to transfer, we need at least one of the channels to
03489       actually be in a call bridge.  We can't conference two applications
03490       together (but then, why would we want to?) */
03491    if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
03492       /* The three-way person we're about to transfer to could still be in MOH, so
03493          stop if now if appropriate */
03494       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
03495          ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
03496       if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
03497          ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
03498       }
03499       if (p->subs[SUB_REAL].owner->cdr) {
03500          /* Move CDR from second channel to current one */
03501          p->subs[SUB_THREEWAY].owner->cdr =
03502             ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
03503          p->subs[SUB_REAL].owner->cdr = NULL;
03504       }
03505       if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
03506          /* Move CDR from second channel's bridge to current one */
03507          p->subs[SUB_THREEWAY].owner->cdr =
03508             ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
03509          ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
03510       }
03511        if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
03512          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
03513                ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
03514          return -1;
03515       }
03516       /* Orphan the channel after releasing the lock */
03517       ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03518       unalloc_sub(p, SUB_THREEWAY);
03519    } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
03520       if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
03521          ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
03522       }
03523       ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
03524       if (p->subs[SUB_THREEWAY].owner->cdr) {
03525          /* Move CDR from second channel to current one */
03526          p->subs[SUB_REAL].owner->cdr = 
03527             ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
03528          p->subs[SUB_THREEWAY].owner->cdr = NULL;
03529       }
03530       if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
03531          /* Move CDR from second channel's bridge to current one */
03532          p->subs[SUB_REAL].owner->cdr = 
03533             ast_cdr_append(p->subs[SUB_REAL].owner->cdr, ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr);
03534          ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr = NULL;
03535       }
03536       if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
03537          ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
03538                ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
03539          return -1;
03540       }
03541       /* Three-way is now the REAL */
03542       swap_subs(p, SUB_THREEWAY, SUB_REAL);
03543       ast_mutex_unlock(&p->subs[SUB_REAL].owner->lock);
03544       unalloc_sub(p, SUB_THREEWAY);
03545       /* Tell the caller not to hangup */
03546       return 1;
03547    } else {
03548       ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
03549                p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
03550       p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
03551       return -1;
03552    }
03553    return 0;
03554 }
03555 
03556 #ifdef ZAPATA_R2
03557 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
03558 {
03559    struct ast_frame *f;
03560    f = &p->subs[index].f;
03561    if (!p->r2) {
03562       ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
03563       return NULL;
03564    }
03565    switch(e->e) {
03566    case MFCR2_EVENT_BLOCKED:
03567       if (option_verbose > 2)
03568          ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
03569       break;
03570    case MFCR2_EVENT_UNBLOCKED:
03571       if (option_verbose > 2)
03572          ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
03573       break;
03574    case MFCR2_EVENT_CONFIG_ERR:
03575       if (option_verbose > 2)
03576          ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
03577       break;
03578    case MFCR2_EVENT_RING:
03579       if (option_verbose > 2)
03580          ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
03581       break;
03582    case MFCR2_EVENT_HANGUP:
03583       if (option_verbose > 2)
03584          ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
03585       break;
03586    case MFCR2_EVENT_RINGING:
03587       if (option_verbose > 2)
03588          ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
03589       break;
03590    case MFCR2_EVENT_ANSWER:
03591       if (option_verbose > 2)
03592          ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
03593       break;
03594    case MFCR2_EVENT_HANGUP_ACK:
03595       if (option_verbose > 2)
03596          ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
03597       break;
03598    case MFCR2_EVENT_IDLE:
03599       if (option_verbose > 2)
03600          ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
03601       break;
03602    default:
03603       ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
03604       break;
03605    }
03606    return f;
03607 }
03608 
03609 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
03610 {
03611    int x;
03612    int res;
03613    mfcr2_event_t *e;
03614    res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
03615    if (res) {
03616       ast_log(LOG_WARNING, "Unable to check received bits\n");
03617       return NULL;
03618    }
03619    if (!p->r2) {
03620       ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
03621       return NULL;
03622    }
03623    e = mfcr2_cas_signaling_event(p->r2, x);
03624    return e;
03625 }
03626 #endif
03627 
03628 static int check_for_conference(struct zt_pvt *p)
03629 {
03630    ZT_CONFINFO ci;
03631    /* Fine if we already have a master, etc */
03632    if (p->master || (p->confno > -1))
03633       return 0;
03634    memset(&ci, 0, sizeof(ci));
03635    if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
03636       ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
03637       return 0;
03638    }
03639    /* If we have no master and don't have a confno, then 
03640       if we're in a conference, it's probably a MeetMe room or
03641       some such, so don't let us 3-way out! */
03642    if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
03643       if (option_verbose > 2) 
03644          ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
03645       return 1;
03646    }
03647    return 0;
03648 }
03649 
03650 static int get_alarms(struct zt_pvt *p)
03651 {
03652    int res;
03653    ZT_SPANINFO zi;
03654    memset(&zi, 0, sizeof(zi));
03655    zi.spanno = p->span;
03656    res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
03657    if (res < 0) {
03658       ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
03659       return 0;
03660    }
03661    return zi.alarms;
03662 }
03663 
03664 static void zt_handle_dtmfup(struct ast_channel *ast, int index, struct ast_frame **dest)
03665 {
03666    struct zt_pvt *p = ast->tech_pvt;
03667    struct ast_frame *f = *dest;
03668 
03669    ast_log(LOG_DEBUG, "DTMF digit: %c on %s\n", f->subclass, ast->name);
03670    if (p->confirmanswer) {
03671       ast_log(LOG_DEBUG, "Confirm answer on %s!\n", ast->name);
03672       /* Upon receiving a DTMF digit, consider this an answer confirmation instead
03673          of a DTMF digit */
03674       p->subs[index].f.frametype = AST_FRAME_CONTROL;
03675       p->subs[index].f.subclass = AST_CONTROL_ANSWER;
03676       *dest = &p->subs[index].f;
03677       /* Reset confirmanswer so DTMF's will behave properly for the duration of the call */
03678       p->confirmanswer = 0;
03679    } else if (p->callwaitcas) {
03680       if ((f->subclass == 'A') || (f->subclass == 'D')) {
03681          ast_log(LOG_DEBUG, "Got some DTMF, but it's for the CAS\n");
03682          if (p->cidspill)
03683             free(p->cidspill);
03684          send_cwcidspill(p);
03685       }
03686       if ((f->subclass != 'm') && (f->subclass != 'u')) 
03687          p->callwaitcas = 0;
03688       p->subs[index].f.frametype = AST_FRAME_NULL;
03689       p->subs[index].f.subclass = 0;
03690       *dest = &p->subs[index].f;
03691    } else if (f->subclass == 'f') {
03692       /* Fax tone -- Handle and return NULL */
03693       if ((p->callprogress & 0x6) && !p->faxhandled) {
03694          p->faxhandled++;
03695          if (strcmp(ast->exten, "fax")) {
03696             const char *target_context = ast_strlen_zero(ast->macrocontext) ? ast->context : ast->macrocontext;
03697 
03698             if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
03699                if (option_verbose > 2)
03700                   ast_verbose(VERBOSE_PREFIX_3 "Redirecting %s to fax extension\n", ast->name);
03701                /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
03702                pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
03703                if (ast_async_goto(ast, target_context, "fax", 1))
03704                   ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
03705             } else
03706                ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
03707          } else
03708             ast_log(LOG_DEBUG, "Already in a fax extension, not redirecting\n");
03709       } else
03710             ast_log(LOG_DEBUG, "Fax already handled\n");
03711       zt_confmute(p, 0);
03712       p->subs[index].f.frametype = AST_FRAME_NULL;
03713       p->subs[index].f.subclass = 0;
03714       *dest = &p->subs[index].f;
03715    } else if (f->subclass == 'm') {
03716       /* Confmute request */
03717       zt_confmute(p, 1);
03718       p->subs[index].f.frametype = AST_FRAME_NULL;
03719       p->subs[index].f.subclass = 0;
03720       *dest = &p->subs[index].f;    
03721    } else if (f->subclass == 'u') {
03722       /* Unmute */
03723       zt_confmute(p, 0);
03724       p->subs[index].f.frametype = AST_FRAME_NULL;
03725       p->subs[index].f.subclass = 0;
03726       *dest = &p->subs[index].f;    
03727    } else
03728       zt_confmute(p, 0);
03729 }
03730          
03731 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
03732 {
03733    int res,x;
03734    int index;
03735    char *c;
03736    struct zt_pvt *p = ast->tech_pvt;
03737    pthread_t threadid;
03738    pthread_attr_t attr;
03739    struct ast_channel *chan;
03740    struct ast_frame *f;
03741 
03742    index = zt_get_index(ast, p, 0);
03743    p->subs[index].f.frametype = AST_FRAME_NULL;
03744    p->subs[index].f.datalen = 0;
03745    p->subs[index].f.samples = 0;
03746    p->subs[index].f.mallocd = 0;
03747    p->subs[index].f.offset = 0;
03748    p->subs[index].f.src = "zt_handle_event";
03749    p->subs[index].f.data = NULL;
03750    f = &p->subs[index].f;
03751 
03752    if (index < 0)
03753       return &p->subs[index].f;
03754    if (p->fake_event) {
03755       res = p->fake_event;
03756       p->fake_event = 0;
03757    } else
03758       res = zt_get_event(p->subs[index].zfd);
03759 
03760    ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
03761 
03762    if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFUP)) {
03763       if (res & ZT_EVENT_PULSEDIGIT)
03764          p->pulsedial = 1;
03765       else
03766          p->pulsedial = 0;
03767 
03768       ast_log(LOG_DEBUG, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
03769 #ifdef ZAPATA_PRI
03770       if (!p->proceeding && p->sig == SIG_PRI && p->pri && p->pri->overlapdial) {
03771          p->subs[index].f.frametype = AST_FRAME_NULL;
03772          p->subs[index].f.subclass = 0;
03773       } else {
03774 #endif
03775          p->subs[index].f.frametype = AST_FRAME_DTMF;
03776          p->subs[index].f.subclass = res & 0xff;
03777 #ifdef ZAPATA_PRI
03778       }
03779 #endif
03780       zt_handle_dtmfup(ast, index, &f);
03781       return f;
03782    }
03783 
03784    if (res & ZT_EVENT_DTMFDOWN) {
03785       ast_log(LOG_DEBUG, "DTMF Down '%c'\n", res & 0xff);
03786       p->subs[index].f.frametype = AST_FRAME_NULL;
03787       p->subs[index].f.subclass = 0;
03788       zt_confmute(p, 1);
03789       /* Mute conference, return null frame */
03790       return &p->subs[index].f;
03791    }
03792 
03793    switch(res) {
03794       case ZT_EVENT_BITSCHANGED:
03795          if (p->sig == SIG_R2) {
03796 #ifdef ZAPATA_R2
03797             struct ast_frame  *f = &p->subs[index].f;
03798             mfcr2_event_t *e;
03799             e = r2_get_event_bits(p);
03800             if (e)
03801                f = handle_r2_event(p, e, index);
03802             return f;
03803 #else          
03804             break;
03805 #endif
03806          }
03807          ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
03808       case ZT_EVENT_PULSE_START:
03809          /* Stop tone if there's a pulse start and the PBX isn't started */
03810          if (!ast->pbx)
03811             tone_zone_play_tone(p->subs[index].zfd, -1);
03812          break;   
03813       case ZT_EVENT_DIALCOMPLETE:
03814          if (p->inalarm) break;
03815          if (p->radio) break;
03816          if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
03817             ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
03818             return NULL;
03819          }
03820          if (!x) { /* if not still dialing in driver */
03821             zt_enable_ec(p);
03822             if (p->echobreak) {
03823                zt_train_ec(p);
03824                ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
03825                p->dop.op = ZT_DIAL_OP_REPLACE;
03826                res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
03827                p->echobreak = 0;
03828             } else {
03829                p->dialing = 0;
03830                if (p->sig == SIG_E911) {
03831                   /* if thru with dialing after offhook */
03832                   if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
03833                      ast_setstate(ast, AST_STATE_UP);
03834                      p->subs[index].f.frametype = AST_FRAME_CONTROL;
03835                      p->subs[index].f.subclass = AST_CONTROL_ANSWER;
03836                      break;
03837                   } else { /* if to state wait for offhook to dial rest */
03838                      /* we now wait for off hook */
03839                      ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
03840                   }
03841                }
03842                if (ast->_state == AST_STATE_DIALING) {
03843                   if ((p->callprogress & 1) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
03844                      ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
03845                   } else if (p->confirmanswer || (!p->dialednone && ((p->sig == SIG_EM) || (p->sig == SIG_EM_E1) ||  (p->sig == SIG_EMWINK) || (p->sig == SIG_FEATD) || (p->sig == SIG_FEATDMF) || (p->sig == SIG_E911) || (p->sig == SIG_FEATB) || (p->sig == SIG_SF) || (p->sig == SIG_SFWINK) || (p->sig == SIG_SF_FEATD) || (p->sig == SIG_SF_FEATDMF) || (p->sig == SIG_SF_FEATB)))) {
03846                      ast_setstate(ast, AST_STATE_RINGING);
03847                   } else if (!p->answeronpolarityswitch) {
03848                      ast_setstate(ast, AST_STATE_UP);
03849                      p->subs[index].f.frametype = AST_FRAME_CONTROL;
03850                      p->subs[index].f.subclass = AST_CONTROL_ANSWER;
03851                   }
03852                }
03853             }
03854          }
03855          break;
03856       case ZT_EVENT_ALARM:
03857 #ifdef ZAPATA_PRI
03858          if (p->call) {
03859             if (p->pri && p->pri->pri) {
03860                if (!pri_grab(p, p->pri)) {
03861                   pri_hangup(p->pri->pri, p->call, -1);
03862                   pri_destroycall(p->pri->pri, p->call);
03863                   p->call = NULL;
03864                   pri_rel(p->pri);
03865                } else
03866                   ast_log(LOG_WARNING, "Failed to grab PRI!\n");
03867             } else
03868                ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
03869          }
03870          if (p->owner)
03871             p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
03872          if (p->bearer)
03873             p->bearer->inalarm = 1;
03874          else
03875 #endif
03876          p->inalarm = 1;
03877          res = get_alarms(p);
03878          ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
03879          manager_event(EVENT_FLAG_SYSTEM, "Alarm",
03880                         "Alarm: %s\r\n"
03881                         "Channel: %d\r\n",
03882                         alarm2str(res), p->channel);
03883          /* fall through intentionally */
03884       case ZT_EVENT_ONHOOK:
03885          if (p->radio)
03886          {
03887             p->subs[index].f.frametype = AST_FRAME_CONTROL;
03888             p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
03889             break;
03890          }
03891          switch(p->sig) {
03892          case SIG_FXOLS:
03893          case SIG_FXOGS:
03894          case SIG_FXOKS:
03895             p->onhooktime = time(NULL);
03896             p->msgstate = -1;
03897             /* Check for some special conditions regarding call waiting */
03898             if (index == SUB_REAL) {
03899                /* The normal line was hung up */
03900                if (p->subs[SUB_CALLWAIT].owner) {
03901                   /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
03902                   swap_subs(p, SUB_CALLWAIT, SUB_REAL);
03903                   if (option_verbose > 2) 
03904                      ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
03905                   unalloc_sub(p, SUB_CALLWAIT); 
03906 #if 0
03907                   p->subs[index].needanswer = 0;
03908                   p->subs[index].needringing = 0;
03909 #endif                  
03910                   p->callwaitingrepeat = 0;
03911                   p->cidcwexpire = 0;
03912                   p->owner = NULL;
03913                   /* Don't start streaming audio yet if the incoming call isn't up yet */
03914                   if (p->subs[SUB_REAL].owner->_state != AST_STATE_UP)
03915                      p->dialing = 1;
03916                   zt_ring_phone(p);
03917                } else if (p->subs[SUB_THREEWAY].owner) {
03918                   unsigned int mssinceflash;
03919                   /* Here we have to retain the lock on both the main channel, the 3-way channel, and
03920                      the private structure -- not especially easy or clean */
03921                   while(p->subs[SUB_THREEWAY].owner && ast_mutex_trylock(&p->subs[SUB_THREEWAY].owner->lock)) {
03922                      /* Yuck, didn't get the lock on the 3-way, gotta release everything and re-grab! */
03923                      ast_mutex_unlock(&p->lock);
03924                      ast_mutex_unlock(&ast->lock);
03925                      usleep(1);
03926                      /* We can grab ast and p in that order, without worry.  We should make sure
03927                         nothing seriously bad has happened though like some sort of bizarre double
03928                         masquerade! */
03929                      ast_mutex_lock(&ast->lock);
03930                      ast_mutex_lock(&p->lock);
03931                      if (p->owner != ast) {
03932                         ast_log(LOG_WARNING, "This isn't good...\n");
03933                         return NULL;
03934                      }
03935                   }
03936                   if (!p->subs[SUB_THREEWAY].owner) {
03937                      ast_log(LOG_NOTICE, "Whoa, threeway disappeared kinda randomly.\n");
03938                      return NULL;
03939                   }
03940                   mssinceflash = ast_tvdiff_ms(ast_tvnow(), p->flashtime);
03941                   ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
03942                   if (mssinceflash < MIN_MS_SINCE_FLASH) {
03943                      /* It hasn't been long enough since the last flashook.  This is probably a bounce on 
03944                         hanging up.  Hangup both channels now */
03945                      if (p->subs[SUB_THREEWAY].owner)
03946                         ast_queue_hangup(p->subs[SUB_THREEWAY].owner);
03947                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
03948                      ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
03949                      ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03950                   } else if ((ast->pbx) || (ast->_state == AST_STATE_UP)) {
03951                      if (p->transfer) {
03952                         /* In any case this isn't a threeway call anymore */
03953                         p->subs[SUB_REAL].inthreeway = 0;
03954                         p->subs[SUB_THREEWAY].inthreeway = 0;
03955                         /* Only attempt transfer if the phone is ringing; why transfer to busy tone eh? */
03956                         if (!p->transfertobusy && ast->_state == AST_STATE_BUSY) {
03957                            ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03958                            /* Swap subs and dis-own channel */
03959                            swap_subs(p, SUB_THREEWAY, SUB_REAL);
03960                            p->owner = NULL;
03961                            /* Ring the phone */
03962                            zt_ring_phone(p);
03963                         } else {
03964                            if ((res = attempt_transfer(p)) < 0) {
03965                               p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
03966                               if (p->subs[SUB_THREEWAY].owner)
03967                                  ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03968                            } else if (res) {
03969                               /* Don't actually hang up at this point */
03970                               if (p->subs[SUB_THREEWAY].owner)
03971                                  ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03972                               break;
03973                            }
03974                         }
03975                      } else {
03976                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
03977                         if (p->subs[SUB_THREEWAY].owner)
03978                            ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03979                      }
03980                   } else {
03981                      ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
03982                      /* Swap subs and dis-own channel */
03983                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
03984                      p->owner = NULL;
03985                      /* Ring the phone */
03986                      zt_ring_phone(p);
03987                   }
03988                }
03989             } else {
03990                ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
03991             }
03992             /* Fall through */
03993          default:
03994             zt_disable_ec(p);
03995             return NULL;
03996          }
03997          break;
03998       case ZT_EVENT_RINGOFFHOOK:
03999          if (p->inalarm) break;
04000          if (p->radio)
04001          {
04002             p->subs[index].f.frametype = AST_FRAME_CONTROL;
04003             p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
04004             break;
04005          }
04006          /* for E911, its supposed to wait for offhook then dial
04007             the second half of the dial string */
04008          if ((p->sig == SIG_E911) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
04009             c = strchr(p->dialdest, '/');
04010             if (c)
04011                c++;
04012             else
04013                c = p->dialdest;
04014             if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
04015             else ast_copy_string(p->dop.dialstr,"M*2#", sizeof(p->dop.dialstr));
04016             if (strlen(p->dop.dialstr) > 4) {
04017                memset(p->echorest, 'w', sizeof(p->echorest) - 1);
04018                strcpy(p->echorest + (p->echotraining / 401) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
04019                p->echorest[sizeof(p->echorest) - 1] = '\0';
04020                p->echobreak = 1;
04021                p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
04022             } else
04023                p->echobreak = 0;
04024             if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
04025                x = ZT_ONHOOK;
04026                ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
04027                ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
04028                return NULL;
04029                }
04030             p->dialing = 1;
04031             return &p->subs[index].f;
04032          }
04033          switch(p->sig) {
04034          case SIG_FXOLS:
04035          case SIG_FXOGS:
04036          case SIG_FXOKS:
04037             switch(ast->_state) {
04038             case AST_STATE_RINGING:
04039                zt_enable_ec(p);
04040                zt_train_ec(p);
04041                p->subs[index].f.frametype = AST_FRAME_CONTROL;
04042                p->subs[index].f.subclass = AST_CONTROL_ANSWER;
04043                /* Make sure it stops ringing */
04044                zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
04045                ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
04046                if (p->cidspill) {
04047                   /* Cancel any running CallerID spill */
04048                   free(p->cidspill);
04049                   p->cidspill = NULL;
04050                }
04051                p->dialing = 0;
04052                p->callwaitcas = 0;
04053                if (p->confirmanswer) {
04054                   /* Ignore answer if "confirm answer" is enabled */
04055                   p->subs[index].f.frametype = AST_FRAME_NULL;
04056                   p->subs[index].f.subclass = 0;
04057                } else if (!ast_strlen_zero(p->dop.dialstr)) {
04058                   /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
04059                   res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
04060                   if (res < 0) {
04061                      ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
04062                      p->dop.dialstr[0] = '\0';
04063                      return NULL;
04064                   } else {
04065                      ast_log(LOG_DEBUG, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
04066                      p->subs[index].f.frametype = AST_FRAME_NULL;
04067                      p->subs[index].f.subclass = 0;
04068                      p->dialing = 1;
04069                   }
04070                   p->dop.dialstr[0] = '\0';
04071                   ast_setstate(ast, AST_STATE_DIALING);
04072                } else
04073                   ast_setstate(ast, AST_STATE_UP);
04074                return &p->subs[index].f;
04075             case AST_STATE_DOWN:
04076                ast_setstate(ast, AST_STATE_RING);
04077                ast->rings = 1;
04078                p->subs[index].f.frametype = AST_FRAME_CONTROL;
04079                p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
04080                ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
04081                return &p->subs[index].f;
04082             case AST_STATE_UP:
04083                /* Make sure it stops ringing */
04084                zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
04085                /* Okay -- probably call waiting*/
04086                if (ast_bridged_channel(p->owner))
04087                      ast_moh_stop(ast_bridged_channel(p->owner));
04088                break;
04089             case AST_STATE_RESERVED:
04090                /* Start up dialtone */
04091                if (has_voicemail(p))
04092                   res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_STUTTER);
04093                else
04094                   res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALTONE);
04095                break;
04096             default:
04097                ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
04098             }
04099             break;
04100          case SIG_FXSLS:
04101          case SIG_FXSGS:
04102          case SIG_FXSKS:
04103             if (ast->_state == AST_STATE_RING) {
04104                p->ringt = p->ringt_base;
04105             }
04106 
04107             /* If we get a ring then we cannot be in 
04108              * reversed polarity. So we reset to idle */
04109             ast_log(LOG_DEBUG, "Setting IDLE polarity due "
04110                "to ring. Old polarity was %d\n", 
04111                p->polarity);
04112             p->polarity = POLARITY_IDLE;
04113 
04114             /* Fall through */
04115          case SIG_EM:
04116          case SIG_EM_E1:
04117          case SIG_EMWINK:
04118          case SIG_FEATD:
04119          case SIG_FEATDMF:
04120          case SIG_FEATDMF_TA:
04121          case SIG_E911:
04122          case SIG_FEATB:
04123          case SIG_SF:
04124          case SIG_SFWINK:
04125          case SIG_SF_FEATD:
04126          case SIG_SF_FEATDMF:
04127          case SIG_SF_FEATB:
04128             if (ast->_state == AST_STATE_PRERING)
04129                ast_setstate(ast, AST_STATE_RING);
04130             if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
04131                if (option_debug)
04132                   ast_log(LOG_DEBUG, "Ring detected\n");
04133                p->subs[index].f.frametype = AST_FRAME_CONTROL;
04134                p->subs[index].f.subclass = AST_CONTROL_RING;
04135             } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
04136                if (option_debug)
04137                   ast_log(LOG_DEBUG, "Line answered\n");
04138                if (p->confirmanswer) {
04139                   p->subs[index].f.frametype = AST_FRAME_NULL;
04140                   p->subs[index].f.subclass = 0;
04141                } else {
04142                   p->subs[index].f.frametype = AST_FRAME_CONTROL;
04143                   p->subs[index].f.subclass = AST_CONTROL_ANSWER;
04144                   ast_setstate(ast, AST_STATE_UP);
04145                }
04146             } else if (ast->_state != AST_STATE_RING)
04147                ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
04148             break;
04149          default:
04150             ast_log(LOG_WARNING, "Don't know how to handle ring/off hook for signalling %d\n", p->sig);
04151          }
04152          break;
04153 #ifdef ZT_EVENT_RINGBEGIN
04154       case ZT_EVENT_RINGBEGIN:
04155          switch(p->sig) {
04156          case SIG_FXSLS:
04157          case SIG_FXSGS:
04158          case SIG_FXSKS:
04159             if (ast->_state == AST_STATE_RING) {
04160                p->ringt = p->ringt_base;
04161             }
04162             break;
04163          }
04164          break;
04165 #endif         
04166       case ZT_EVENT_RINGEROFF:
04167          if (p->inalarm) break;
04168          if (p->radio) break;
04169          ast->rings++;
04170          if ((ast->rings > p->cidrings) && (p->cidspill)) {
04171             ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
04172             free(p->cidspill);
04173             p->cidspill = NULL;
04174             p->callwaitcas = 0;
04175          }
04176          p->subs[index].f.frametype = AST_FRAME_CONTROL;
04177          p->subs[index].f.subclass = AST_CONTROL_RINGING;
04178          break;
04179       case ZT_EVENT_RINGERON:
04180          break;
04181       case ZT_EVENT_NOALARM:
04182          p->inalarm = 0;
04183 #ifdef ZAPATA_PRI
04184          /* Extremely unlikely but just in case */
04185          if (p->bearer)
04186             p->bearer->inalarm = 0;
04187 #endif            
04188          ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
04189          manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
04190                         "Channel: %d\r\n", p->channel);
04191          break;
04192       case ZT_EVENT_WINKFLASH:
04193          if (p->inalarm) break;
04194          if (p->radio) break;
04195          /* Remember last time we got a flash-hook */
04196          gettimeofday(&p->flashtime, NULL);
04197          switch(p->sig) {
04198          case SIG_FXOLS:
04199          case SIG_FXOGS:
04200          case SIG_FXOKS:
04201             ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
04202                index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
04203             p->callwaitcas = 0;
04204 
04205             if (index != SUB_REAL) {
04206                ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
04207                goto winkflashdone;
04208             }
04209             
04210             if (p->subs[SUB_CALLWAIT].owner) {
04211                /* Swap to call-wait */
04212                swap_subs(p, SUB_REAL, SUB_CALLWAIT);
04213                tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
04214                p->owner = p->subs[SUB_REAL].owner;
04215                ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
04216                if (p->owner->_state == AST_STATE_RINGING) {
04217                   ast_setstate(p->owner, AST_STATE_UP);
04218                   p->subs[SUB_REAL].needanswer = 1;
04219                }
04220                p->callwaitingrepeat = 0;
04221                p->cidcwexpire = 0;
04222                /* Start music on hold if appropriate */
04223                if (!p->subs[SUB_CALLWAIT].inthreeway && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
04224                   ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
04225                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
04226                   ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
04227             } else if (!p->subs[SUB_THREEWAY].owner) {
04228                char cid_num[256];
04229                char cid_name[256];
04230 
04231                if (!p->threewaycalling) {
04232                   /* Just send a flash if no 3-way calling */
04233                   p->subs[SUB_REAL].needflash = 1;
04234                   goto winkflashdone;
04235                } else if (!check_for_conference(p)) {
04236                   if (p->zaptrcallerid && p->owner) {
04237                      if (p->owner->cid.cid_num)
04238                         ast_copy_string(cid_num, p->owner->cid.cid_num, sizeof(cid_num));
04239                      if (p->owner->cid.cid_name)
04240                         ast_copy_string(cid_name, p->owner->cid.cid_name, sizeof(cid_name));
04241                   }
04242                   /* XXX This section needs much more error checking!!! XXX */
04243                   /* Start a 3-way call if feasible */
04244                   if (!((ast->pbx) ||
04245                         (ast->_state == AST_STATE_UP) ||
04246                         (ast->_state == AST_STATE_RING))) {
04247                      ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
04248                         goto winkflashdone;
04249                   }
04250                   if (alloc_sub(p, SUB_THREEWAY)) {
04251                      ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
04252                      goto winkflashdone;
04253                   }
04254                   /* Make new channel */
04255                   chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
04256                   if (p->zaptrcallerid) {
04257                      if (!p->origcid_num)
04258                         p->origcid_num = strdup(p->cid_num);
04259                      if (!p->origcid_name)
04260                         p->origcid_name = strdup(p->cid_name);
04261                      ast_copy_string(p->cid_num, cid_num, sizeof(p->cid_num));
04262                      ast_copy_string(p->cid_name, cid_name, sizeof(p->cid_name));
04263                   }
04264                   /* Swap things around between the three-way and real call */
04265                   swap_subs(p, SUB_THREEWAY, SUB_REAL);
04266                   /* Disable echo canceller for better dialing */
04267                   zt_disable_ec(p);
04268                   res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
04269                   if (res)
04270                      ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
04271                   p->owner = chan;
04272                   pthread_attr_init(&attr);
04273                   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
04274                   if (!chan) {
04275                      ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
04276                   } else if (ast_pthread_create(&threadid, &attr, ss_thread, chan)) {
04277                      ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
04278                      res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
04279                      zt_enable_ec(p);
04280                      ast_hangup(chan);
04281                   } else {
04282                      if (option_verbose > 2) 
04283                         ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
04284                      /* Start music on hold if appropriate */
04285                      if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
04286                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
04287                   }
04288                   pthread_attr_destroy(&attr);
04289                }
04290             } else {
04291                /* Already have a 3 way call */
04292                if (p->subs[SUB_THREEWAY].inthreeway) {
04293                   /* Call is already up, drop the last person */
04294                   if (option_debug)
04295                      ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
04296                   /* If the primary call isn't answered yet, use it */
04297                   if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
04298                      /* Swap back -- we're dropping the real 3-way that isn't finished yet*/
04299                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
04300                      p->owner = p->subs[SUB_REAL].owner;
04301                   }
04302                   /* Drop the last call and stop the conference */
04303                   if (option_verbose > 2)
04304                      ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
04305                   p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
04306                   p->subs[SUB_REAL].inthreeway = 0;
04307                   p->subs[SUB_THREEWAY].inthreeway = 0;
04308                } else {
04309                   /* Lets see what we're up to */
04310                   if (((ast->pbx) || (ast->_state == AST_STATE_UP)) && 
04311                       (p->transfertobusy || (ast->_state != AST_STATE_BUSY))) {
04312                      int otherindex = SUB_THREEWAY;
04313 
04314                      if (option_verbose > 2)
04315                         ast_verbose(VERBOSE_PREFIX_3 "Building conference on call on %s and %s\n", p->subs[SUB_THREEWAY].owner->name, p->subs[SUB_REAL].owner->name);
04316                      /* Put them in the threeway, and flip */
04317                      p->subs[SUB_THREEWAY].inthreeway = 1;
04318                      p->subs[SUB_REAL].inthreeway = 1;
04319                      if (ast->_state == AST_STATE_UP) {
04320                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
04321                         otherindex = SUB_REAL;
04322                      }
04323                      if (p->subs[otherindex].owner && ast_bridged_channel(p->subs[otherindex].owner))
04324                         ast_moh_stop(ast_bridged_channel(p->subs[otherindex].owner));
04325                      p->owner = p->subs[SUB_REAL].owner;
04326                      if (ast->_state == AST_STATE_RINGING) {
04327                         ast_log(LOG_DEBUG, "Enabling ringtone on real and threeway\n");
04328                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
04329                         res = tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
04330                      }
04331                   } else {
04332                      if (option_verbose > 2)
04333                         ast_verbose(VERBOSE_PREFIX_3 "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
04334                      swap_subs(p, SUB_THREEWAY, SUB_REAL);
04335                      p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
04336                      p->owner = p->subs[SUB_REAL].owner;
04337                      if (p->subs[SUB_REAL].owner && ast_bridged_channel(p->subs[SUB_REAL].owner))
04338                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
04339                      zt_enable_ec(p);
04340                   }
04341                      
04342                }
04343             }
04344          winkflashdone:              
04345             update_conf(p);
04346             break;
04347          case SIG_EM:
04348          case SIG_EM_E1:
04349          case SIG_EMWINK:
04350          case SIG_FEATD:
04351          case SIG_SF:
04352          case SIG_SFWINK:
04353          case SIG_SF_FEATD:
04354          case SIG_FXSLS:
04355          case SIG_FXSGS:
04356             if (p->dialing)
04357                ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
04358             else
04359                ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
04360             break;
04361          case SIG_FEATDMF_TA:
04362             switch (p->whichwink) {
04363             case 0:
04364                ast_log(LOG_DEBUG, "ANI2 set to '%d' and ANI is '%s'\n", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
04365                snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%d%s#", p->owner->cid.cid_ani2, p->owner->cid.cid_ani);
04366                break;
04367             case 1:
04368                ast_copy_string(p->dop.dialstr, p->finaldial, sizeof(p->dop.dialstr));
04369                break;
04370             case 2:
04371                ast_log(LOG_WARNING, "Received unexpected wink on channel of type SIG_FEATDMF_TA\n");
04372                return NULL;
04373             }
04374             p->whichwink++;
04375             /* Fall through */
04376          case SIG_FEATDMF:
04377          case SIG_E911:
04378          case SIG_FEATB:
04379          case SIG_SF_FEATDMF:
04380          case SIG_SF_FEATB:
04381             /* FGD MF *Must* wait for wink */
04382             if (!ast_strlen_zero(p->dop.dialstr))
04383                res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
04384             else if (res < 0) {
04385                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
04386                p->dop.dialstr[0] = '\0';
04387                return NULL;
04388             } else 
04389                ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
04390             p->dop.dialstr[0] = '\0';
04391             break;
04392          default:
04393             ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
04394          }
04395          break;
04396       case ZT_EVENT_HOOKCOMPLETE:
04397          if (p->inalarm) break;
04398          if (p->radio) break;
04399          switch(p->sig) {
04400          case SIG_FXSLS:  /* only interesting for FXS */
04401          case SIG_FXSGS:
04402          case SIG_FXSKS:
04403          case SIG_EM:
04404          case SIG_EM_E1:
04405          case SIG_EMWINK:
04406          case SIG_FEATD:
04407          case SIG_SF:
04408          case SIG_SFWINK:
04409          case SIG_SF_FEATD:
04410             if (!ast_strlen_zero(p->dop.dialstr)) 
04411                res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
04412             else if (res < 0) {
04413                ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
04414                p->dop.dialstr[0] = '\0';
04415                return NULL;
04416             } else 
04417                ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
04418             p->dop.dialstr[0] = '\0';
04419             p->dop.op = ZT_DIAL_OP_REPLACE;
04420             break;
04421          case SIG_FEATDMF:
04422          case SIG_E911:
04423          case SIG_FEATB:
04424          case SIG_SF_FEATDMF:
04425          case SIG_SF_FEATB:
04426             ast_log(LOG_DEBUG, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
04427             break;
04428          default:
04429             break;
04430          }
04431          break;
04432       case ZT_EVENT_POLARITY:
04433                         /*
04434                          * If we get a Polarity Switch event, check to see
04435                          * if we should change the polarity state and
04436                          * mark the channel as UP or if this is an indication
04437                          * of remote end disconnect.
04438                          */
04439                         if (p->polarity == POLARITY_IDLE) {
04440                                 p->polarity = POLARITY_REV;
04441                                 if (p->answeronpolarityswitch &&
04442                                     ((ast->_state == AST_STATE_DIALING) ||
04443                                      (ast->_state == AST_STATE_RINGING))) {
04444                                         ast_log(LOG_DEBUG, "Answering on polarity switch!\n");
04445                                         ast_setstate(p->owner, AST_STATE_UP);
04446                if(p->hanguponpolarityswitch) {
04447                   gettimeofday(&p->polaritydelaytv, NULL);
04448                }
04449                break;
04450                                 } else
04451                                         ast_log(LOG_DEBUG, "Ignore switch to REVERSED Polarity on channel %d, state %d\n", p->channel, ast->_state);
04452          } 
04453          /* Removed else statement from here as it was preventing hangups from ever happening*/
04454          /* Added AST_STATE_RING in if statement below to deal with calling party hangups that take place when ringing */
04455          if(p->hanguponpolarityswitch &&
04456             (p->polarityonanswerdelay > 0) &&
04457                 (p->polarity == POLARITY_REV) &&
04458             ((ast->_state == AST_STATE_UP) || (ast->_state == AST_STATE_RING)) ) {
04459                                 /* Added log_debug information below to provide a better indication of what is going on */
04460             ast_log(LOG_DEBUG, "Polarity Reversal event occured - DEBUG 1: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
04461          
04462             if(ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) > p->polarityonanswerdelay) {
04463                ast_log(LOG_DEBUG, "Polarity Reversal detected and now Hanging up on channel %d\n", p->channel);
04464                ast_softhangup(p->owner, AST_SOFTHANGUP_EXPLICIT);
04465                p->polarity = POLARITY_IDLE;
04466             } else {
04467                ast_log(LOG_DEBUG, "Polarity Reversal detected but NOT hanging up (too close to answer event) on channel %d, state %d\n", p->channel, ast->_state);
04468             }
04469          } else {
04470             p->polarity = POLARITY_IDLE;
04471             ast_log(LOG_DEBUG, "Ignoring Polarity switch to IDLE on channel %d, state %d\n", p->channel, ast->_state);
04472          }
04473                         /* Added more log_debug information below to provide a better indication of what is going on */
04474          ast_log(LOG_DEBUG, "Polarity Reversal event occured - DEBUG 2: channel %d, state %d, pol= %d, aonp= %d, honp= %d, pdelay= %d, tv= %d\n", p->channel, ast->_state, p->polarity, p->answeronpolarityswitch, p->hanguponpolarityswitch, p->polarityonanswerdelay, ast_tvdiff_ms(ast_tvnow(), p->polaritydelaytv) );
04475          break;
04476       default:
04477          ast_log(LOG_DEBUG, "Dunno what to do with event %d on channel %d\n", res, p->channel);
04478    }
04479    return &p->subs[index].f;
04480 }
04481 
04482 static struct ast_frame *__zt_exception(struct ast_channel *ast)
04483 {
04484    struct zt_pvt *p = ast->tech_pvt;
04485    int res;
04486    int usedindex=-1;
04487    int index;
04488    struct ast_frame *f;
04489 
04490 
04491    index = zt_get_index(ast, p, 1);
04492    
04493    p->subs[index].f.frametype = AST_FRAME_NULL;
04494    p->subs[index].f.datalen = 0;
04495    p->subs[index].f.samples = 0;
04496    p->subs[index].f.mallocd = 0;
04497    p->subs[index].f.offset = 0;
04498    p->subs[index].f.subclass = 0;
04499    p->subs[index].f.delivery = ast_tv(0,0);
04500    p->subs[index].f.src = "zt_exception";
04501    p->subs[index].f.data = NULL;
04502    
04503    
04504    if ((!p->owner) && (!p->radio)) {
04505       /* If nobody owns us, absorb the event appropriately, otherwise
04506          we loop indefinitely.  This occurs when, during call waiting, the
04507          other end hangs up our channel so that it no longer exists, but we
04508          have neither FLASH'd nor ONHOOK'd to signify our desire to
04509          change to the other channel. */
04510       if (p->fake_event) {
04511          res = p->fake_event;
04512          p->fake_event = 0;
04513       } else
04514          res = zt_get_event(p->subs[SUB_REAL].zfd);
04515       /* Switch to real if there is one and this isn't something really silly... */
04516       if ((res != ZT_EVENT_RINGEROFF) && (res != ZT_EVENT_RINGERON) &&
04517          (res != ZT_EVENT_HOOKCOMPLETE)) {
04518          ast_log(LOG_DEBUG, "Restoring owner of channel %d on event %d\n", p->channel, res);
04519          p->owner = p->subs[SUB_REAL].owner;
04520          if (p->owner && ast_bridged_channel(p->owner))
04521             ast_moh_stop(ast_bridged_channel(p->owner));
04522       }
04523       switch(res) {
04524       case ZT_EVENT_ONHOOK:
04525          zt_disable_ec(p);
04526          if (p->owner) {
04527             if (option_verbose > 2) 
04528                ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has call, ringing phone\n", p->owner->name);
04529             zt_ring_phone(p);
04530             p->callwaitingrepeat = 0;
04531             p->cidcwexpire = 0;
04532          } else
04533             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
04534          update_conf(p);
04535          break;
04536       case ZT_EVENT_RINGOFFHOOK:
04537          zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
04538          if (p->owner && (p->owner->_state == AST_STATE_RINGING)) {
04539             p->subs[SUB_REAL].needanswer = 1;
04540             p->dialing = 0;
04541          }
04542          break;
04543       case ZT_EVENT_HOOKCOMPLETE:
04544       case ZT_EVENT_RINGERON:
04545       case ZT_EVENT_RINGEROFF:
04546          /* Do nothing */
04547          break;
04548       case ZT_EVENT_WINKFLASH:
04549          gettimeofday(&p->flashtime, NULL);
04550          if (p->owner) {
04551             if (option_verbose > 2) 
04552                ast_verbose(VERBOSE_PREFIX_3 "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
04553             if (p->owner->_state != AST_STATE_UP) {
04554                /* Answer if necessary */
04555                usedindex = zt_get_index(p->owner, p, 0);
04556                if (usedindex > -1) {
04557                   p->subs[usedindex].needanswer = 1;
04558                }
04559                ast_setstate(p->owner, AST_STATE_UP);
04560             }
04561             p->callwaitingrepeat = 0;
04562             p->cidcwexpire = 0;
04563             if (ast_bridged_channel(p->owner))
04564                ast_moh_stop(ast_bridged_channel(p->owner));
04565          } else
04566             ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
04567          update_conf(p);
04568          break;
04569       default:
04570          ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
04571       }
04572       f = &p->subs[index].f;
04573       return f;
04574    }
04575    if (!p->radio) ast_log(LOG_DEBUG, "Exception on %d, channel %d\n", ast->fds[0],p->channel);
04576    /* If it's not us, return NULL immediately */
04577    if (ast != p->owner) {
04578       ast_log(LOG_WARNING, "We're %s, not %s\n", ast->name, p->owner->name);
04579       f = &p->subs[index].f;
04580       return f;
04581    }
04582    f = zt_handle_event(ast);
04583    return f;
04584 }
04585 
04586 struct ast_frame *zt_exception(struct ast_channel *ast)
04587 {
04588    struct zt_pvt *p = ast->tech_pvt;
04589    struct ast_frame *f;
04590    ast_mutex_lock(&p->lock);
04591    f = __zt_exception(ast);
04592    ast_mutex_unlock(&p->lock);
04593    return f;
04594 }
04595 
04596 struct ast_frame  *zt_read(struct ast_channel *ast)
04597 {
04598    struct zt_pvt *p = ast->tech_pvt;
04599    int res;
04600    int index;
04601    void *readbuf;
04602    struct ast_frame *f;
04603    
04604 
04605    ast_mutex_lock(&p->lock);
04606    
04607    index = zt_get_index(ast, p, 0);
04608    
04609    /* Hang up if we don't really exist */
04610    if (index < 0) {
04611       ast_log(LOG_WARNING, "We dont exist?\n");
04612       ast_mutex_unlock(&p->lock);
04613       return NULL;
04614    }
04615    
04616    if (p->radio && p->inalarm) return NULL;
04617 
04618    p->subs[index].f.frametype = AST_FRAME_NULL;
04619    p->subs[index].f.datalen = 0;
04620    p->subs[index].f.samples = 0;
04621    p->subs[index].f.mallocd = 0;
04622    p->subs[index].f.offset = 0;
04623    p->subs[index].f.subclass = 0;
04624    p->subs[index].f.delivery = ast_tv(0,0);
04625    p->subs[index].f.src = "zt_read";
04626    p->subs[index].f.data = NULL;
04627    
04628    /* make sure it sends initial key state as first frame */
04629    if (p->radio && (!p->firstradio))
04630    {
04631       ZT_PARAMS ps;
04632 
04633       ps.channo = p->channel;
04634       if (ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps) < 0) {
04635          ast_mutex_unlock(&p->lock);
04636          return NULL;
04637       }
04638       p->firstradio = 1;
04639       p->subs[index].f.frametype = AST_FRAME_CONTROL;
04640       if (ps.rxisoffhook)
04641       {
04642          p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
04643       }
04644       else
04645       {
04646          p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
04647       }
04648       ast_mutex_unlock(&p->lock);
04649       return &p->subs[index].f;
04650    }
04651    if (p->ringt == 1) {
04652       ast_mutex_unlock(&p->lock);
04653       return NULL;
04654    }
04655    else if (p->ringt > 0) 
04656       p->ringt--;
04657 
04658    if (p->subs[index].needringing) {
04659       /* Send ringing frame if requested */
04660       p->subs[index].needringing = 0;
04661       p->subs[index].f.frametype = AST_FRAME_CONTROL;
04662       p->subs[index].f.subclass = AST_CONTROL_RINGING;
04663       ast_setstate(ast, AST_STATE_RINGING);
04664       ast_mutex_unlock(&p->lock);
04665       return &p->subs[index].f;
04666    }
04667 
04668    if (p->subs[index].needbusy) {
04669       /* Send busy frame if requested */
04670       p->subs[index].needbusy = 0;
04671       p->subs[index].f.frametype = AST_FRAME_CONTROL;
04672       p->subs[index].f.subclass = AST_CONTROL_BUSY;
04673       ast_mutex_unlock(&p->lock);
04674       return &p->subs[index].f;
04675    }
04676 
04677    if (p->subs[index].needcongestion) {
04678       /* Send congestion frame if requested */
04679       p->subs[index].needcongestion = 0;
04680       p->subs[index].f.frametype = AST_FRAME_CONTROL;
04681       p->subs[index].f.subclass = AST_CONTROL_CONGESTION;
04682       ast_mutex_unlock(&p->lock);
04683       return &p->subs[index].f;
04684    }
04685 
04686    if (p->subs[index].needcallerid) {
04687       ast_set_callerid(ast, !ast_strlen_zero(p->lastcid_num) ? p->lastcid_num : NULL, 
04688                      !ast_strlen_zero(p->lastcid_name) ? p->lastcid_name : NULL,
04689                      !ast_strlen_zero(p->lastcid_num) ? p->lastcid_num : NULL
04690                      );
04691       p->subs[index].needcallerid = 0;
04692    }
04693    
04694    if (p->subs[index].needanswer) {
04695       /* Send answer frame if requested */
04696       p->subs[index].needanswer = 0;
04697       p->subs[index].f.frametype = AST_FRAME_CONTROL;
04698       p->subs[index].f.subclass = AST_CONTROL_ANSWER;
04699       ast_mutex_unlock(&p->lock);
04700       return &p->subs[index].f;
04701    }  
04702    
04703    if (p->subs[index].needflash) {
04704       /* Send answer frame if requested */
04705       p->subs[index].needflash = 0;
04706       p->subs[index].f.frametype = AST_FRAME_CONTROL;
04707       p->subs[index].f.subclass = AST_CONTROL_FLASH;
04708       ast_mutex_unlock(&p->lock);
04709       return &p->subs[index].f;
04710    }  
04711    
04712    if (ast->rawreadformat == AST_FORMAT_SLINEAR) {
04713       if (!p->subs[index].linear) {
04714          p->subs[index].linear = 1;
04715          res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
04716          if (res) 
04717             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to linear mode.\n", p->channel, index);
04718       }
04719    } else if ((ast->rawreadformat == AST_FORMAT_ULAW) ||
04720          (ast->rawreadformat == AST_FORMAT_ALAW)) {
04721       if (p->subs[index].linear) {
04722          p->subs[index].linear = 0;
04723          res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
04724          if (res) 
04725             ast_log(LOG_WARNING, "Unable to set channel %d (index %d) to companded mode.\n", p->channel, index);
04726       }
04727    } else {
04728       ast_log(LOG_WARNING, "Don't know how to read frames in format %s\n", ast_getformatname(ast->rawreadformat));
04729       ast_mutex_unlock(&p->lock);
04730       return NULL;
04731    }
04732    readbuf = ((unsigned char *)p->subs[index].buffer) + AST_FRIENDLY_OFFSET;
04733    CHECK_BLOCKING(ast);
04734    res = read(p->subs[index].zfd, readbuf, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
04735    ast_clear_flag(ast, AST_FLAG_BLOCKING);
04736    /* Check for hangup */
04737    if (res < 0) {
04738       f = NULL;
04739       if (res == -1)  {
04740          if (errno == EAGAIN) {
04741             /* Return "NULL" frame if there is nobody there */
04742             ast_mutex_unlock(&p->lock);
04743             return &p->subs[index].f;
04744          } else if (errno == ELAST) {
04745             f = __zt_exception(ast);
04746          } else
04747             ast_log(LOG_WARNING, "zt_rec: %s\n", strerror(errno));
04748       }
04749       ast_mutex_unlock(&p->lock);
04750       return f;
04751    }
04752    if (res != (p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE)) {
04753       ast_log(LOG_DEBUG, "Short read (%d/%d), must be an event...\n", res, p->subs[index].linear ? READ_SIZE * 2 : READ_SIZE);
04754       f = __zt_exception(ast);
04755       ast_mutex_unlock(&p->lock);
04756       return f;
04757    }
04758    if (p->tdd) { /* if in TDD mode, see if we receive that */
04759       int c;
04760 
04761       c = tdd_feed(p->tdd,readbuf,READ_SIZE);
04762       if (c < 0) {
04763          ast_log(LOG_DEBUG,"tdd_feed failed\n");
04764          ast_mutex_unlock(&p->lock);
04765          return NULL;
04766       }
04767       if (c) { /* if a char to return */
04768          p->subs[index].f.subclass = 0;
04769          p->subs[index].f.frametype = AST_FRAME_TEXT;
04770          p->subs[index].f.mallocd = 0;
04771          p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
04772          p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET;
04773          p->subs[index].f.datalen = 1;
04774          *((char *) p->subs[index].f.data) = c;
04775          ast_mutex_unlock(&p->lock);
04776          return &p->subs[index].f;
04777       }
04778    }
04779    if (p->callwaitingrepeat)
04780       p->callwaitingrepeat--;
04781    if (p->cidcwexpire)
04782       p->cidcwexpire--;
04783    /* Repeat callwaiting */
04784    if (p->callwaitingrepeat == 1) {
04785       p->callwaitrings++;
04786       zt_callwait(ast);
04787    }
04788    /* Expire CID/CW */
04789    if (p->cidcwexpire == 1) {
04790       if (option_verbose > 2)
04791          ast_verbose(VERBOSE_PREFIX_3 "CPE does not support Call Waiting Caller*ID.\n");
04792       restore_conference(p);
04793    }
04794    if (p->subs[index].linear) {
04795       p->subs[index].f.datalen = READ_SIZE * 2;
04796    } else 
04797       p->subs[index].f.datalen = READ_SIZE;
04798 
04799    /* Handle CallerID Transmission */
04800    if ((p->owner == ast) && p->cidspill &&((ast->_state == AST_STATE_UP) || (ast->rings == p->cidrings))) {
04801       send_callerid(p);
04802    }
04803 
04804    p->subs[index].f.frametype = AST_FRAME_VOICE;
04805    p->subs[index].f.subclass = ast->rawreadformat;
04806    p->subs[index].f.samples = READ_SIZE;
04807    p->subs[index].f.mallocd = 0;
04808    p->subs[index].f.offset = AST_FRIENDLY_OFFSET;
04809    p->subs[index].f.data = p->subs[index].buffer + AST_FRIENDLY_OFFSET/2;
04810 #if 0
04811    ast_log(LOG_DEBUG, "Read %d of voice on %s\n", p->subs[index].f.datalen, ast->name);
04812 #endif   
04813    if (p->dialing || /* Transmitting something */
04814       (index && (ast->_state != AST_STATE_UP)) || /* Three-way or callwait that isn't up */
04815       ((index == SUB_CALLWAIT) && !p->subs[SUB_CALLWAIT].inthreeway) /* Inactive and non-confed call-wait */
04816       ) {
04817       /* Whoops, we're still dialing, or in a state where we shouldn't transmit....
04818          don't send anything */
04819       p->subs[index].f.frametype = AST_FRAME_NULL;
04820       p->subs[index].f.subclass = 0;
04821       p->subs[index].f.samples = 0;
04822       p->subs[index].f.mallocd = 0;
04823       p->subs[index].f.offset = 0;
04824       p->subs[index].f.data = NULL;
04825       p->subs[index].f.datalen= 0;
04826    }
04827    if (p->dsp && (!p->ignoredtmf || p->callwaitcas || p->busydetect  || p->callprogress) && !index) {
04828       /* Perform busy detection. etc on the zap line */
04829       f = ast_dsp_process(ast, p->dsp, &p->subs[index].f);
04830       if (f) {
04831          if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_BUSY)) {
04832             if ((ast->_state == AST_STATE_UP) && !p->outgoing) {
04833                /* Treat this as a "hangup" instead of a "busy" on the assumption that
04834                   a busy  */
04835                f = NULL;
04836             }
04837          } else if (f->frametype == AST_FRAME_DTMF) {
04838 #ifdef ZAPATA_PRI
04839             if (!p->proceeding && p->sig==SIG_PRI && p->pri && p->pri->overlapdial) {
04840                /* Don't accept in-band DTMF when in overlap dial mode */
04841                f->frametype = AST_FRAME_NULL;
04842                f->subclass = 0;
04843             }
04844 #endif            
04845             /* DSP clears us of being pulse */
04846             p->pulsedial = 0;
04847          }
04848       }
04849    } else 
04850       f = &p->subs[index].f; 
04851    if (f && (f->frametype == AST_FRAME_DTMF))
04852       zt_handle_dtmfup(ast, index, &f);
04853 
04854    /* If we have a fake_event, trigger exception to handle it */
04855    if (p->fake_event)
04856       ast_set_flag(ast, AST_FLAG_EXCEPTION);
04857 
04858    ast_mutex_unlock(&p->lock);
04859    return f;
04860 }
04861 
04862 static int my_zt_write(struct zt_pvt *p, unsigned char *buf, int len, int index, int linear)
04863 {
04864    int sent=0;
04865    int size;
04866    int res;
04867    int fd;
04868    fd = p->subs[index].zfd;
04869    while(len) {
04870       size = len;
04871       if (size > (linear ? READ_SIZE * 2 : READ_SIZE))
04872          size = (linear ? READ_SIZE * 2 : READ_SIZE);
04873       res = write(fd, buf, size);
04874       if (res != size) {
04875          if (option_debug)
04876             ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
04877          return sent;
04878       }
04879       len -= size;
04880       buf += size;
04881    }
04882    return sent;
04883 }
04884 
04885 static int zt_write(struct ast_channel *ast, struct ast_frame *frame)
04886 {
04887    struct zt_pvt *p = ast->tech_pvt;
04888    int res;
04889    unsigned char outbuf[4096];
04890    int index;
04891    index = zt_get_index(ast, p, 0);
04892    if (index < 0) {
04893       ast_log(LOG_WARNING, "%s doesn't really exist?\n", ast->name);
04894       return -1;
04895    }
04896 
04897 #if 0
04898 #ifdef ZAPATA_PRI
04899    ast_mutex_lock(&p->lock);
04900    if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
04901       if (p->pri->pri) {      
04902          if (!pri_grab(p, p->pri)) {
04903                pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
04904                pri_rel(p->pri);
04905          } else
04906                ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
04907       }
04908       p->proceeding=1;
04909    }
04910    ast_mutex_unlock(&p->lock);
04911 #endif
04912 #endif
04913    /* Write a frame of (presumably voice) data */
04914    if (frame->frametype != AST_FRAME_VOICE) {
04915       if (frame->frametype != AST_FRAME_IMAGE)
04916          ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
04917       return 0;
04918    }
04919    if ((frame->subclass != AST_FORMAT_SLINEAR) && 
04920        (frame->subclass != AST_FORMAT_ULAW) &&
04921        (frame->subclass != AST_FORMAT_ALAW)) {
04922       ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
04923       return -1;
04924    }
04925    if (p->dialing) {
04926       if (option_debug)
04927          ast_log(LOG_DEBUG, "Dropping frame since I'm still dialing on %s...\n",ast->name);
04928       return 0;
04929    }
04930    if (!p->owner) {
04931       if (option_debug)
04932          ast_log(LOG_DEBUG, "Dropping frame since there is no active owner on %s...\n",ast->name);
04933       return 0;
04934    }
04935    if (p->cidspill) {
04936       if (option_debug)
04937          ast_log(LOG_DEBUG, "Dropping frame since I've still got a callerid spill\n");
04938       return 0;
04939    }
04940    /* Return if it's not valid data */
04941    if (!frame->data || !frame->datalen)
04942       return 0;
04943    if (frame->datalen > sizeof(outbuf) * 2) {
04944       ast_log(LOG_WARNING, "Frame too large\n");
04945       return 0;
04946    }
04947 
04948    if (frame->subclass == AST_FORMAT_SLINEAR) {
04949       if (!p->subs[index].linear) {
04950          p->subs[index].linear = 1;
04951          res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
04952          if (res)
04953             ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
04954       }
04955       res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 1);
04956    } else {
04957       /* x-law already */
04958       if (p->subs[index].linear) {
04959          p->subs[index].linear = 0;
04960          res = zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
04961          if (res)
04962             ast_log(LOG_WARNING, "Unable to set companded mode on channel %d\n", p->channel);
04963       }
04964       res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, index, 0);
04965    }
04966    if (res < 0) {
04967       ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
04968       return -1;
04969    } 
04970    return 0;
04971 }
04972 
04973 static int zt_indicate(struct ast_channel *chan, int condition)
04974 {
04975    struct zt_pvt *p = chan->tech_pvt;
04976    int res=-1;
04977    int index;
04978    int func = ZT_FLASH;
04979    ast_mutex_lock(&p->lock);
04980    index = zt_get_index(chan, p, 0);
04981    ast_log(LOG_DEBUG, "Requested indication %d on channel %s\n", condition, chan->name);
04982    if (index == SUB_REAL) {
04983       switch(condition) {
04984       case AST_CONTROL_BUSY:
04985 #ifdef ZAPATA_PRI
04986          if (p->priindication_oob && p->sig == SIG_PRI) {
04987             chan->hangupcause = AST_CAUSE_USER_BUSY;
04988             chan->_softhangup |= AST_SOFTHANGUP_DEV;
04989             res = 0;
04990          } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
04991             if (p->pri->pri) {      
04992                if (!pri_grab(p, p->pri)) {
04993                   pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
04994                   pri_rel(p->pri);
04995                }
04996                else
04997                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
04998             }
04999             p->progress = 1;
05000             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
05001          } else
05002 #endif
05003             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_BUSY);
05004          break;
05005       case AST_CONTROL_RINGING:
05006 #ifdef ZAPATA_PRI
05007          if ((!p->alerting) && p->sig==SIG_PRI && p->pri && !p->outgoing && (chan->_state != AST_STATE_UP)) {
05008             if (p->pri->pri) {      
05009                if (!pri_grab(p, p->pri)) {
05010                   pri_acknowledge(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
05011                   pri_rel(p->pri);
05012                }
05013                else
05014                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
05015             }
05016             p->alerting = 1;
05017          }
05018 #endif
05019          res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_RINGTONE);
05020          if (chan->_state != AST_STATE_UP && chan->_state != AST_STATE_RING) {
05021             if ((p->sig != SIG_FXSKS) &&
05022                 (p->sig != SIG_FXSLS) &&
05023                 (p->sig != SIG_FXSGS))
05024                ast_setstate(chan, AST_STATE_RINGING);
05025          }
05026          break;
05027       case AST_CONTROL_PROCEEDING:
05028          ast_log(LOG_DEBUG,"Received AST_CONTROL_PROCEEDING on %s\n",chan->name);
05029 #ifdef ZAPATA_PRI
05030          if (!p->proceeding && p->sig==SIG_PRI && p->pri && !p->outgoing) {
05031             if (p->pri->pri) {      
05032                if (!pri_grab(p, p->pri)) {
05033                   pri_proceeding(p->pri->pri,p->call, PVT_TO_CHANNEL(p), !p->digital);
05034                   pri_rel(p->pri);
05035                }
05036                else
05037                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
05038             }
05039             p->proceeding = 1;
05040          }
05041 #endif
05042          /* don't continue in ast_indicate */
05043          res = 0;
05044          break;
05045       case AST_CONTROL_PROGRESS:
05046          ast_log(LOG_DEBUG,"Received AST_CONTROL_PROGRESS on %s\n",chan->name);
05047 #ifdef ZAPATA_PRI
05048          p->digital = 0;   /* Digital-only calls isn't allows any inband progress messages */
05049          if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
05050             if (p->pri->pri) {      
05051                if (!pri_grab(p, p->pri)) {
05052                   pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
05053                   pri_rel(p->pri);
05054                }
05055                else
05056                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
05057             }
05058             p->progress = 1;
05059          }
05060 #endif
05061          /* don't continue in ast_indicate */
05062          res = 0;
05063          break;
05064       case AST_CONTROL_CONGESTION:
05065          chan->hangupcause = AST_CAUSE_CONGESTION;
05066 #ifdef ZAPATA_PRI
05067          if (p->priindication_oob && p->sig == SIG_PRI) {
05068             chan->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
05069             chan->_softhangup |= AST_SOFTHANGUP_DEV;
05070             res = 0;
05071          } else if (!p->progress && p->sig==SIG_PRI && p->pri && !p->outgoing) {
05072             if (p->pri) {     
05073                if (!pri_grab(p, p->pri)) {
05074                   pri_progress(p->pri->pri,p->call, PVT_TO_CHANNEL(p), 1);
05075                   pri_rel(p->pri);
05076                } else
05077                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
05078             }
05079             p->progress = 1;
05080             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05081          } else
05082 #endif
05083             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05084          break;
05085 #ifdef ZAPATA_PRI
05086       case AST_CONTROL_HOLD:
05087          if (p->pri) {
05088             if (!pri_grab(p, p->pri)) {
05089                res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_HOLD);
05090                pri_rel(p->pri);
05091             } else
05092                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);       
05093          }
05094          break;
05095       case AST_CONTROL_UNHOLD:
05096          if (p->pri) {
05097             if (!pri_grab(p, p->pri)) {
05098                res = pri_notify(p->pri->pri, p->call, p->prioffset, PRI_NOTIFY_REMOTE_RETRIEVAL);
05099                pri_rel(p->pri);
05100             } else
05101                   ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);       
05102          }
05103          break;
05104 #endif
05105       case AST_CONTROL_RADIO_KEY:
05106          if (p->radio) 
05107              res =  zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
05108          res = 0;
05109          break;
05110       case AST_CONTROL_RADIO_UNKEY:
05111          if (p->radio)
05112              res =  zt_set_hook(p->subs[index].zfd, ZT_RINGOFF);
05113          res = 0;
05114          break;
05115       case AST_CONTROL_FLASH:
05116          /* flash hookswitch */
05117          if (ISTRUNK(p) && (p->sig != SIG_PRI)) {
05118             /* Clear out the dial buffer */
05119             p->dop.dialstr[0] = '\0';
05120             if ((ioctl(p->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
05121                ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n", 
05122                   chan->name, strerror(errno));
05123             } else
05124                res = 0;
05125          } else
05126             res = 0;
05127          break;
05128       case -1:
05129          res = tone_zone_play_tone(p->subs[index].zfd, -1);
05130          break;
05131       }
05132    } else
05133       res = 0;
05134    ast_mutex_unlock(&p->lock);
05135    return res;
05136 }
05137 
05138 static struct ast_channel *zt_new(struct zt_pvt *i, int state, int startpbx, int index, int law, int transfercapability)
05139 {
05140    struct ast_channel *tmp;
05141    int deflaw;
05142    int res;
05143    int x,y;
05144    int features;
05145    ZT_PARAMS ps;
05146    if (i->subs[index].owner) {
05147       ast_log(LOG_WARNING, "Channel %d already has a %s call\n", i->channel,subnames[index]);
05148       return NULL;
05149    }
05150    tmp = ast_channel_alloc(0);
05151    if (tmp) {
05152       tmp->tech = &zap_tech;
05153       ps.channo = i->channel;
05154       res = ioctl(i->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &ps);
05155       if (res) {
05156          ast_log(LOG_WARNING, "Unable to get parameters, assuming MULAW\n");
05157          ps.curlaw = ZT_LAW_MULAW;
05158       }
05159       if (ps.curlaw == ZT_LAW_ALAW)
05160          deflaw = AST_FORMAT_ALAW;
05161       else
05162          deflaw = AST_FORMAT_ULAW;
05163       if (law) {
05164          if (law == ZT_LAW_ALAW)
05165             deflaw = AST_FORMAT_ALAW;
05166          else
05167             deflaw = AST_FORMAT_ULAW;
05168       }
05169       y = 1;
05170       do {
05171 #ifdef ZAPATA_PRI
05172          if (i->bearer || (i->pri && (i->sig == SIG_FXSKS)))
05173             snprintf(tmp->name, sizeof(tmp->name), "Zap/%d:%d-%d", i->pri->trunkgroup, i->channel, y);
05174          else
05175 #endif
05176          if (i->channel == CHAN_PSEUDO)
05177             snprintf(tmp->name, sizeof(tmp->name), "Zap/pseudo-%d", rand());
05178          else  
05179             snprintf(tmp->name, sizeof(tmp->name), "Zap/%d-%d", i->channel, y);
05180          for (x=0;x<3;x++) {
05181             if ((index != x) && i->subs[x].owner && !strcasecmp(tmp->name, i->subs[x].owner->name))
05182                break;
05183          }
05184          y++;
05185       } while (x < 3);
05186       tmp->type = type;
05187       tmp->fds[0] = i->subs[index].zfd;
05188       tmp->nativeformats = AST_FORMAT_SLINEAR | deflaw;
05189       /* Start out assuming ulaw since it's smaller :) */
05190       tmp->rawreadformat = deflaw;
05191       tmp->readformat = deflaw;
05192       tmp->rawwriteformat = deflaw;
05193       tmp->writeformat = deflaw;
05194       i->subs[index].linear = 0;
05195       zt_setlinear(i->subs[index].zfd, i->subs[index].linear);
05196       features = 0;
05197       if (index == SUB_REAL) {
05198          if (i->busydetect && CANBUSYDETECT(i)) {
05199             features |= DSP_FEATURE_BUSY_DETECT;
05200          }
05201          if ((i->callprogress & 1) && CANPROGRESSDETECT(i)) {
05202             features |= DSP_FEATURE_CALL_PROGRESS;
05203          }
05204          if ((!i->outgoing && (i->callprogress & 4)) || 
05205              (i->outgoing && (i->callprogress & 2))) {
05206             features |= DSP_FEATURE_FAX_DETECT;
05207          }
05208 #ifdef ZT_TONEDETECT
05209          x = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
05210          if (ioctl(i->subs[index].zfd, ZT_TONEDETECT, &x)) {
05211 #endif      
05212             i->hardwaredtmf = 0;
05213             features |= DSP_FEATURE_DTMF_DETECT;
05214 #ifdef ZT_TONEDETECT
05215          } else if (NEED_MFDETECT(i)) {
05216             i->hardwaredtmf = 1;
05217             features |= DSP_FEATURE_DTMF_DETECT;
05218          }
05219 #endif
05220       }
05221       if (features) {
05222          if (i->dsp) {
05223             ast_log(LOG_DEBUG, "Already have a dsp on %s?\n", tmp->name);
05224          } else {
05225             if (i->channel != CHAN_PSEUDO)
05226                i->dsp = ast_dsp_new();
05227             else
05228                i->dsp = NULL;
05229             if (i->dsp) {
05230                i->dsp_features = features & ~DSP_PROGRESS_TALK;
05231 #ifdef ZAPATA_PRI
05232                /* We cannot do progress detection until receives PROGRESS message */
05233                if (i->outgoing && (i->sig == SIG_PRI)) {
05234                   /* Remember requested DSP features, don't treat
05235                      talking as ANSWER */
05236                   features = 0;
05237                }
05238 #endif
05239                ast_dsp_set_features(i->dsp, features);
05240                ast_dsp_digitmode(i->dsp, DSP_DIGITMODE_DTMF | i->dtmfrelax);
05241                if (!ast_strlen_zero(progzone))
05242                   ast_dsp_set_call_progress_zone(i->dsp, progzone);
05243                if (i->busydetect && CANBUSYDETECT(i)) {
05244                   ast_dsp_set_busy_count(i->dsp, i->busycount);
05245                   ast_dsp_set_busy_pattern(i->dsp, i->busy_tonelength, i->busy_quietlength);
05246                }
05247             }
05248          }
05249       }
05250       
05251       if (state == AST_STATE_RING)
05252          tmp->rings = 1;
05253       tmp->tech_pvt = i;
05254       if ((i->sig == SIG_FXOKS) || (i->sig == SIG_FXOGS) || (i->sig == SIG_FXOLS)) {
05255          /* Only FXO signalled stuff can be picked up */
05256          tmp->callgroup = i->callgroup;
05257          tmp->pickupgroup = i->pickupgroup;
05258       }
05259       if (!ast_strlen_zero(i->language))
05260          ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
05261       if (!ast_strlen_zero(i->musicclass))
05262          ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
05263       if (!i->owner)
05264          i->owner = tmp;
05265       if (!ast_strlen_zero(i->accountcode))
05266          ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
05267       if (i->amaflags)
05268          tmp->amaflags = i->amaflags;
05269       i->subs[index].owner = tmp;
05270       ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05271       /* Copy call forward info */
05272       ast_copy_string(tmp->call_forward, i->call_forward, sizeof(tmp->call_forward));
05273       /* If we've been told "no ADSI" then enforce it */
05274       if (!i->adsi)
05275          tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05276       if (!ast_strlen_zero(i->exten))
05277          ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05278       if (!ast_strlen_zero(i->rdnis))
05279          tmp->cid.cid_rdnis = strdup(i->rdnis);
05280       if (!ast_strlen_zero(i->dnid))
05281          tmp->cid.cid_dnid = strdup(i->dnid);
05282 
05283 #ifdef PRI_ANI
05284       if (!ast_strlen_zero(i->cid_num))
05285          tmp->cid.cid_num = strdup(i->cid_num);
05286       if (!ast_strlen_zero(i->cid_name))
05287          tmp->cid.cid_name = strdup(i->cid_name);
05288       if (!ast_strlen_zero(i->cid_ani))
05289          tmp->cid.cid_ani = strdup(i->cid_ani);
05290       else if (!ast_strlen_zero(i->cid_num)) 
05291          tmp->cid.cid_ani = strdup(i->cid_num);
05292 #else
05293       if (!ast_strlen_zero(i->cid_num)) {
05294          tmp->cid.cid_num = strdup(i->cid_num);
05295          tmp->cid.cid_ani = strdup(i->cid_num);
05296       }
05297       if (!ast_strlen_zero(i->cid_name))
05298          tmp->cid.cid_name = strdup(i->cid_name);
05299 #endif
05300       tmp->cid.cid_pres = i->callingpres;
05301       tmp->cid.cid_ton = i->cid_ton;
05302 #ifdef ZAPATA_PRI
05303       tmp->transfercapability = transfercapability;
05304       pbx_builtin_setvar_helper(tmp, "TRANSFERCAPABILITY", ast_transfercapability2str(transfercapability));
05305       if (transfercapability & PRI_TRANS_CAP_DIGITAL) {
05306          i->digital = 1;
05307       }
05308       /* Assume calls are not idle calls unless we're told differently */
05309       i->isidlecall = 0;
05310       i->alreadyhungup = 0;
05311 #endif
05312       /* clear the fake event in case we posted one before we had ast_channel */
05313       i->fake_event = 0;
05314       /* Assure there is no confmute on this channel */
05315       zt_confmute(i, 0);
05316       ast_setstate(tmp, state);
05317       ast_mutex_lock(&usecnt_lock);
05318       usecnt++;
05319       ast_mutex_unlock(&usecnt_lock);
05320       ast_update_use_count();
05321       if (startpbx) {
05322          if (ast_pbx_start(tmp)) {
05323             ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05324             ast_hangup(tmp);
05325             tmp = NULL;
05326          }
05327       }
05328    } else
05329       ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
05330    return tmp;
05331 }
05332 
05333 
05334 static int my_getsigstr(struct ast_channel *chan, char *str, const char *term, int ms)
05335 {
05336    char c;
05337 
05338    *str = 0; /* start with empty output buffer */
05339    for (;;)
05340    {
05341       /* Wait for the first digit (up to specified ms). */
05342       c = ast_waitfordigit(chan, ms);
05343       /* if timeout, hangup or error, return as such */
05344       if (c < 1)
05345          return c;
05346       *str++ = c;
05347       *str = 0;
05348       if (strchr(term, c))
05349          return 1;
05350    }
05351 }
05352 
05353 static int zt_wink(struct zt_pvt *p, int index)
05354 {
05355    int j;
05356    zt_set_hook(p->subs[index].zfd, ZT_WINK);
05357    for(;;)
05358    {
05359          /* set bits of interest */
05360       j = ZT_IOMUX_SIGEVENT;
05361           /* wait for some happening */
05362       if (ioctl(p->subs[index].zfd,ZT_IOMUX,&j) == -1) return(-1);
05363          /* exit loop if we have it */
05364       if (j & ZT_IOMUX_SIGEVENT) break;
05365    }
05366      /* get the event info */
05367    if (ioctl(p->subs[index].zfd,ZT_GETEVENT,&j) == -1) return(-1);
05368    return 0;
05369 }
05370 
05371 static void *ss_thread(void *data)
05372 {
05373    struct ast_channel *chan = data;
05374    struct zt_pvt *p = chan->tech_pvt;
05375    char exten[AST_MAX_EXTENSION]="";
05376    char exten2[AST_MAX_EXTENSION]="";
05377    unsigned char buf[256];
05378    char dtmfcid[300];
05379    char dtmfbuf[300];
05380    struct callerid_state *cs;
05381    char *name=NULL, *number=NULL;
05382    int distMatches;
05383    int curRingData[3];
05384    int receivedRingT;
05385    int counter1;
05386    int counter;
05387    int samples = 0;
05388 
05389    int flags;
05390    int i;
05391    int timeout;
05392    int getforward=0;
05393    char *s1, *s2;
05394    int len = 0;
05395    int res;
05396    int index;
05397 
05398    /* in the bizarre case where the channel has become a zombie before we
05399       even get started here, abort safely
05400    */
05401    if (!p) {
05402       ast_log(LOG_WARNING, "Channel became a zombie before simple switch could be started (%s)\n", chan->name);
05403       ast_hangup(chan);
05404       return NULL;
05405    }
05406 
05407    if (option_verbose > 2) 
05408       ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s'\n", chan->name);
05409    index = zt_get_index(chan, p, 1);
05410    if (index < 0) {
05411       ast_log(LOG_WARNING, "Huh?\n");
05412       ast_hangup(chan);
05413       return NULL;
05414    }
05415    if (p->dsp)
05416       ast_dsp_digitreset(p->dsp);
05417    switch(p->sig) {
05418 #ifdef ZAPATA_PRI
05419    case SIG_PRI:
05420       /* Now loop looking for an extension */
05421       ast_copy_string(exten, p->exten, sizeof(exten));
05422       len = strlen(exten);
05423       res = 0;
05424       while((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
05425          if (len && !ast_ignore_pattern(chan->context, exten))
05426             tone_zone_play_tone(p->subs[index].zfd, -1);
05427          else
05428             tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
05429          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num))
05430             timeout = matchdigittimeout;
05431          else
05432             timeout = gendigittimeout;
05433          res = ast_waitfordigit(chan, timeout);
05434          if (res < 0) {
05435             ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
05436             ast_hangup(chan);
05437             return NULL;
05438          } else if (res) {
05439             exten[len++] = res;
05440             exten[len] = '\0';
05441          } else
05442             break;
05443       }
05444       /* if no extension was received ('unspecified') on overlap call, use the 's' extension */
05445       if (ast_strlen_zero(exten)) {
05446          if (option_verbose > 2)
05447             ast_verbose(VERBOSE_PREFIX_3 "Going to extension s|1 because of empty extension received on overlap call\n");
05448          exten[0] = 's';
05449          exten[1] = '\0';
05450       }
05451       tone_zone_play_tone(p->subs[index].zfd, -1);
05452       if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num)) {
05453          /* Start the real PBX */
05454          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
05455          if (p->dsp) ast_dsp_digitreset(p->dsp);
05456          zt_enable_ec(p);
05457          ast_setstate(chan, AST_STATE_RING);
05458          res = ast_pbx_run(chan);
05459          if (res) {
05460             ast_log(LOG_WARNING, "PBX exited non-zero!\n");
05461          }
05462       } else {
05463          ast_log(LOG_DEBUG, "No such possible extension '%s' in context '%s'\n", exten, chan->context);
05464          chan->hangupcause = AST_CAUSE_UNALLOCATED;
05465          ast_hangup(chan);
05466          p->exten[0] = '\0';
05467          /* Since we send release complete here, we won't get one */
05468          p->call = NULL;
05469       }
05470       return NULL;
05471       break;
05472 #endif
05473    case SIG_FEATD:
05474    case SIG_FEATDMF:
05475    case SIG_E911:
05476    case SIG_FEATB:
05477    case SIG_EMWINK:
05478    case SIG_SF_FEATD:
05479    case SIG_SF_FEATDMF:
05480    case SIG_SF_FEATB:
05481    case SIG_SFWINK:
05482       if (zt_wink(p, index))  
05483          return NULL;
05484       /* Fall through */
05485    case SIG_EM:
05486    case SIG_EM_E1:
05487    case SIG_SF:
05488       res = tone_zone_play_tone(p->subs[index].zfd, -1);
05489       if (p->dsp)
05490          ast_dsp_digitreset(p->dsp);
05491       /* set digit mode appropriately */
05492       if (p->dsp) {
05493          if (NEED_MFDETECT(p))
05494             ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MF | p->dtmfrelax); 
05495          else 
05496             ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
05497       }
05498       memset(dtmfbuf, 0, sizeof(dtmfbuf));
05499       /* Wait for the first digit only if immediate=no */
05500       if (!p->immediate)
05501          /* Wait for the first digit (up to 5 seconds). */
05502          res = ast_waitfordigit(chan, 5000);
05503       else res = 0;
05504       if (res > 0) {
05505          /* save first char */
05506          dtmfbuf[0] = res;
05507          switch(p->sig) {
05508          case SIG_FEATD:
05509          case SIG_SF_FEATD:
05510             res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
05511             if (res > 0)
05512                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
05513             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
05514             break;
05515          case SIG_FEATDMF:
05516          case SIG_E911:
05517          case SIG_SF_FEATDMF:
05518             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
05519             if (res > 0) {
05520                /* if E911, take off hook */
05521                if (p->sig == SIG_E911)
05522                   zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
05523                res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "#", 3000);
05524             }
05525             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
05526             break;
05527          case SIG_FEATB:
05528          case SIG_SF_FEATB:
05529             res = my_getsigstr(chan, dtmfbuf + 1, "#", 3000);
05530             if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
05531             break;
05532          case SIG_EMWINK:
05533             /* if we received a '*', we are actually receiving Feature Group D
05534                dial syntax, so use that mode; otherwise, fall through to normal
05535                mode
05536             */
05537             if (res == '*') {
05538                res = my_getsigstr(chan, dtmfbuf + 1, "*", 3000);
05539                if (res > 0)
05540                   res = my_getsigstr(chan, dtmfbuf + strlen(dtmfbuf), "*", 3000);
05541                if ((res < 1) && (p->dsp)) ast_dsp_digitreset(p->dsp);
05542                break;
05543             }
05544          default:
05545             /* If we got the first digit, get the rest */
05546             len = 1;
05547             dtmfbuf[len] = '\0';
05548             while((len < AST_MAX_EXTENSION-1) && ast_matchmore_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
05549                if (ast_exists_extension(chan, chan->context, dtmfbuf, 1, p->cid_num)) {
05550                   timeout = matchdigittimeout;
05551                } else {
05552                   timeout = gendigittimeout;
05553                }
05554                res = ast_waitfordigit(chan, timeout);
05555                if (res < 0) {
05556                   ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
05557                   ast_hangup(chan);
05558                   return NULL;
05559                } else if (res) {
05560                   dtmfbuf[len++] = res;
05561                   dtmfbuf[len] = '\0';
05562                } else {
05563                   break;
05564                }
05565             }
05566             break;
05567          }
05568       }
05569       if (res == -1) {
05570          ast_log(LOG_WARNING, "getdtmf on channel %d: %s\n", p->channel, strerror(errno));
05571          ast_hangup(chan);
05572          return NULL;
05573       } else if (res < 0) {
05574          ast_log(LOG_DEBUG, "Got hung up before digits finished\n");
05575          ast_hangup(chan);
05576          return NULL;
05577       }
05578       ast_copy_string(exten, dtmfbuf, sizeof(exten));
05579       if (ast_strlen_zero(exten))
05580          ast_copy_string(exten, "s", sizeof(exten));
05581       if (p->sig == SIG_FEATD || p->sig == SIG_EMWINK) {
05582          /* Look for Feature Group D on all E&M Wink and Feature Group D trunks */
05583          if (exten[0] == '*') {
05584             char *stringp=NULL;
05585             ast_copy_string(exten2, exten, sizeof(exten2));
05586             /* Parse out extension and callerid */
05587             stringp=exten2 +1;
05588             s1 = strsep(&stringp, "*");
05589             s2 = strsep(&stringp, "*");
05590             if (s2) {
05591                if (!ast_strlen_zero(p->cid_num))
05592                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
05593                else
05594                   ast_set_callerid(chan, s1, NULL, s1);
05595                ast_copy_string(exten, s2, sizeof(exten));
05596             } else
05597                ast_copy_string(exten, s1, sizeof(exten));
05598          } else if (p->sig == SIG_FEATD)
05599             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
05600       }
05601       if (p->sig == SIG_FEATDMF) {
05602          if (exten[0] == '*') {
05603             char *stringp=NULL;
05604             ast_copy_string(exten2, exten, sizeof(exten2));
05605             /* Parse out extension and callerid */
05606             stringp=exten2 +1;
05607             s1 = strsep(&stringp, "#");
05608             s2 = strsep(&stringp, "#");
05609             if (s2) {
05610                if (!ast_strlen_zero(p->cid_num))
05611                   ast_set_callerid(chan, p->cid_num, NULL, p->cid_num);
05612                else
05613                   if(*(s1 + 2))
05614                      ast_set_callerid(chan, s1 + 2, NULL, s1 + 2);
05615                ast_copy_string(exten, s2 + 1, sizeof(exten));
05616             } else
05617                ast_copy_string(exten, s1 + 2, sizeof(exten));
05618          } else
05619             ast_log(LOG_WARNING, "Got a non-Feature Group D input on channel %d.  Assuming E&M Wink instead\n", p->channel);
05620       }
05621       if (p->sig == SIG_E911) {
05622          if (exten[0] == '*') {
05623             char *stringp=NULL;
05624             ast_copy_string(exten2, exten, sizeof(exten2));
05625             /* Parse out extension and callerid */
05626             stringp=exten2 +1;
05627             s1 = strsep(&stringp, "#");
05628             s2 = strsep(&stringp, "#");
05629             if (s2 && (*(s2 + 1) == '0')) {
05630                if(*(s2 + 2))
05631                   ast_set_callerid(chan, s2 + 2, NULL, s2 + 2);
05632             }
05633             if (s1)  ast_copy_string(exten, s1, sizeof(exten));
05634             else ast_copy_string(exten, "911", sizeof(exten));
05635          } else
05636             ast_log(LOG_WARNING, "Got a non-E911 input on channel %d.  Assuming E&M Wink instead\n", p->channel);
05637       }
05638       if (p->sig == SIG_FEATB) {
05639          if (exten[0] == '*') {
05640             char *stringp=NULL;
05641             ast_copy_string(exten2, exten, sizeof(exten2));
05642             /* Parse out extension and callerid */
05643             stringp=exten2 +1;
05644             s1 = strsep(&stringp, "#");
05645             ast_copy_string(exten, exten2 + 1, sizeof(exten));
05646          } else
05647             ast_log(LOG_WARNING, "Got a non-Feature Group B input on channel %d.  Assuming E&M Wink instead\n", p->channel);
05648       }
05649       if (p->sig == SIG_FEATDMF) {
05650          zt_wink(p, index);
05651       }
05652       zt_enable_ec(p);
05653       if (NEED_MFDETECT(p)) {
05654          if (p->dsp) {
05655             if (!p->hardwaredtmf)
05656                ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax); 
05657             else {
05658                ast_dsp_free(p->dsp);
05659                p->dsp = NULL;
05660             }
05661          }
05662       }
05663 
05664       if (ast_exists_extension(chan, chan->context, exten, 1, chan->cid.cid_num)) {
05665          ast_copy_string(chan->exten, exten, sizeof(chan->exten));
05666          if (p->dsp) ast_dsp_digitreset(p->dsp);
05667          res = ast_pbx_run(chan);
05668          if (res) {
05669             ast_log(LOG_WARNING, "PBX exited non-zero\n");
05670             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05671          }
05672          return NULL;
05673       } else {
05674          if (option_verbose > 2)
05675             ast_verbose(VERBOSE_PREFIX_2 "Unknown extension '%s' in context '%s' requested\n", exten, chan->context);
05676          sleep(2);
05677          res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_INFO);
05678          if (res < 0)
05679             ast_log(LOG_WARNING, "Unable to start special tone on %d\n", p->channel);
05680          else
05681             sleep(1);
05682          res = ast_streamfile(chan, "ss-noservice", chan->language);
05683          if (res >= 0)
05684             ast_waitstream(chan, "");
05685          res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05686          ast_hangup(chan);
05687          return NULL;
05688       }
05689       break;
05690    case SIG_FXOLS:
05691    case SIG_FXOGS:
05692    case SIG_FXOKS:
05693       /* Read the first digit */
05694       timeout = firstdigittimeout;
05695       /* If starting a threeway call, never timeout on the first digit so someone
05696          can use flash-hook as a "hold" feature */
05697       if (p->subs[SUB_THREEWAY].owner) 
05698          timeout = 999999;
05699       while(len < AST_MAX_EXTENSION-1) {
05700          /* Read digit unless it's supposed to be immediate, in which case the
05701             only answer is 's' */
05702          if (p->immediate) 
05703             res = 's';
05704          else
05705             res = ast_waitfordigit(chan, timeout);
05706          timeout = 0;
05707          if (res < 0) {
05708             ast_log(LOG_DEBUG, "waitfordigit returned < 0...\n");
05709             res = tone_zone_play_tone(p->subs[index].zfd, -1);
05710             ast_hangup(chan);
05711             return NULL;
05712          } else if (res)  {
05713             exten[len++]=res;
05714             exten[len] = '\0';
05715          }
05716          if (!ast_ignore_pattern(chan->context, exten))
05717             tone_zone_play_tone(p->subs[index].zfd, -1);
05718          else
05719             tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
05720          if (ast_exists_extension(chan, chan->context, exten, 1, p->cid_num) && strcmp(exten, ast_parking_ext())) {
05721             if (!res || !ast_matchmore_extension(chan, chan->context, exten, 1, p->cid_num)) {
05722                if (getforward) {
05723                   /* Record this as the forwarding extension */
05724                   ast_copy_string(p->call_forward, exten, sizeof(p->call_forward)); 
05725                   if (option_verbose > 2)
05726                      ast_verbose(VERBOSE_PREFIX_3 "Setting call forward to '%s' on channel %d\n", p->call_forward, p->channel);
05727                   res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05728                   if (res)
05729                      break;
05730                   usleep(500000);
05731                   res = tone_zone_play_tone(p->subs[index].zfd, -1);
05732                   sleep(1);
05733                   memset(exten, 0, sizeof(exten));
05734                   res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALTONE);
05735                   len = 0;
05736                   getforward = 0;
05737                } else  {
05738                   res = tone_zone_play_tone(p->subs[index].zfd, -1);
05739                   ast_copy_string(chan->exten, exten, sizeof(chan->exten));
05740                   if (!ast_strlen_zero(p->cid_num)) {
05741                      if (!p->hidecallerid)
05742                         ast_set_callerid(chan, p->cid_num, NULL, p->cid_num); 
05743                      else
05744                         ast_set_callerid(chan, NULL, NULL, p->cid_num); 
05745                   }
05746                   if (!ast_strlen_zero(p->cid_name)) {
05747                      if (!p->hidecallerid)
05748                         ast_set_callerid(chan, NULL, p->cid_name, NULL);
05749                   }
05750                   ast_setstate(chan, AST_STATE_RING);
05751                   zt_enable_ec(p);
05752                   res = ast_pbx_run(chan);
05753                   if (res) {
05754                      ast_log(LOG_WARNING, "PBX exited non-zero\n");
05755                      res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05756                   }
05757                   return NULL;
05758                }
05759             } else {
05760                /* It's a match, but they just typed a digit, and there is an ambiguous match,
05761                   so just set the timeout to matchdigittimeout and wait some more */
05762                timeout = matchdigittimeout;
05763             }
05764          } else if (res == 0) {
05765             ast_log(LOG_DEBUG, "not enough digits (and no ambiguous match)...\n");
05766             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05767             zt_wait_event(p->subs[index].zfd);
05768             ast_hangup(chan);
05769             return NULL;
05770          } else if (p->callwaiting && !strcmp(exten, "*70")) {
05771             if (option_verbose > 2) 
05772                ast_verbose(VERBOSE_PREFIX_3 "Disabling call waiting on %s\n", chan->name);
05773             /* Disable call waiting if enabled */
05774             p->callwaiting = 0;
05775             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05776             if (res) {
05777                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n", 
05778                   chan->name, strerror(errno));
05779             }
05780             len = 0;
05781             ioctl(p->subs[index].zfd,ZT_CONFDIAG,&len);
05782             memset(exten, 0, sizeof(exten));
05783             timeout = firstdigittimeout;
05784                
05785          } else if (!strcmp(exten,ast_pickup_ext())) {
05786             /* Scan all channels and see if any there
05787              * ringing channqels with that have call groups
05788              * that equal this channels pickup group  
05789              */
05790             if (index == SUB_REAL) {
05791                /* Switch us from Third call to Call Wait */
05792                if (p->subs[SUB_THREEWAY].owner) {
05793                   /* If you make a threeway call and the *8# a call, it should actually 
05794                      look like a callwait */
05795                   alloc_sub(p, SUB_CALLWAIT);   
05796                   swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
05797                   unalloc_sub(p, SUB_THREEWAY);
05798                }
05799                zt_enable_ec(p);
05800                if (ast_pickup_call(chan)) {
05801                   ast_log(LOG_DEBUG, "No call pickup possible...\n");
05802                   res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05803                   zt_wait_event(p->subs[index].zfd);
05804                }
05805                ast_hangup(chan);
05806                return NULL;
05807             } else {
05808                ast_log(LOG_WARNING, "Huh?  Got *8# on call not on real\n");
05809                ast_hangup(chan);
05810                return NULL;
05811             }
05812             
05813          } else if (!p->hidecallerid && !strcmp(exten, "*67")) {
05814             if (option_verbose > 2) 
05815                ast_verbose(VERBOSE_PREFIX_3 "Disabling Caller*ID on %s\n", chan->name);
05816             /* Disable Caller*ID if enabled */
05817             p->hidecallerid = 1;
05818             if (chan->cid.cid_num)
05819                free(chan->cid.cid_num);
05820             chan->cid.cid_num = NULL;
05821             if (chan->cid.cid_name)
05822                free(chan->cid.cid_name);
05823             chan->cid.cid_name = NULL;
05824             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05825             if (res) {
05826                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n", 
05827                   chan->name, strerror(errno));
05828             }
05829             len = 0;
05830             memset(exten, 0, sizeof(exten));
05831             timeout = firstdigittimeout;
05832          } else if (p->callreturn && !strcmp(exten, "*69")) {
05833             res = 0;
05834             if (!ast_strlen_zero(p->lastcid_num)) {
05835                res = ast_say_digit_str(chan, p->lastcid_num, "", chan->language);
05836             }
05837             if (!res)
05838                res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05839             break;
05840          } else if (!strcmp(exten, "*78")) {
05841             /* Do not disturb */
05842             if (option_verbose > 2) {
05843                ast_verbose(VERBOSE_PREFIX_3 "Enabled DND on channel %d\n", p->channel);
05844             }
05845             manager_event(EVENT_FLAG_SYSTEM, "DNDState",
05846                      "Channel: Zap/%d\r\n"
05847                      "Status: enabled\r\n", p->channel);
05848             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05849             p->dnd = 1;
05850             getforward = 0;
05851             memset(exten, 0, sizeof(exten));
05852             len = 0;
05853          } else if (!strcmp(exten, "*79")) {
05854             /* Do not disturb */
05855             if (option_verbose > 2)
05856                ast_verbose(VERBOSE_PREFIX_3 "Disabled DND on channel %d\n", p->channel);
05857             manager_event(EVENT_FLAG_SYSTEM, "DNDState",
05858                         "Channel: Zap/%d\r\n"
05859                         "Status: disabled\r\n", p->channel);
05860             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05861             p->dnd = 0;
05862             getforward = 0;
05863             memset(exten, 0, sizeof(exten));
05864             len = 0;
05865          } else if (p->cancallforward && !strcmp(exten, "*72")) {
05866             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05867             getforward = 1;
05868             memset(exten, 0, sizeof(exten));
05869             len = 0;
05870          } else if (p->cancallforward && !strcmp(exten, "*73")) {
05871             if (option_verbose > 2)
05872                ast_verbose(VERBOSE_PREFIX_3 "Cancelling call forwarding on channel %d\n", p->channel);
05873             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05874             memset(p->call_forward, 0, sizeof(p->call_forward));
05875             getforward = 0;
05876             memset(exten, 0, sizeof(exten));
05877             len = 0;
05878          } else if ((p->transfer || p->canpark) && !strcmp(exten, ast_parking_ext()) && 
05879                   p->subs[SUB_THREEWAY].owner &&
05880                   ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
05881             /* This is a three way call, the main call being a real channel, 
05882                and we're parking the first call. */
05883             ast_masq_park_call(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), chan, 0, NULL);
05884             if (option_verbose > 2)
05885                ast_verbose(VERBOSE_PREFIX_3 "Parking call to '%s'\n", chan->name);
05886             break;
05887          } else if (!ast_strlen_zero(p->lastcid_num) && !strcmp(exten, "*60")) {
05888             if (option_verbose > 2)
05889                ast_verbose(VERBOSE_PREFIX_3 "Blacklisting number %s\n", p->lastcid_num);
05890             res = ast_db_put("blacklist", p->lastcid_num, "1");
05891             if (!res) {
05892                res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05893                memset(exten, 0, sizeof(exten));
05894                len = 0;
05895             }
05896          } else if (p->hidecallerid && !strcmp(exten, "*82")) {
05897             if (option_verbose > 2) 
05898                ast_verbose(VERBOSE_PREFIX_3 "Enabling Caller*ID on %s\n", chan->name);
05899             /* Enable Caller*ID if enabled */
05900             p->hidecallerid = 0;
05901             if (chan->cid.cid_num)
05902                free(chan->cid.cid_num);
05903             chan->cid.cid_num = NULL;
05904             if (chan->cid.cid_name)
05905                free(chan->cid.cid_name);
05906             chan->cid.cid_name = NULL;
05907             ast_set_callerid(chan, p->cid_num, p->cid_name, NULL);
05908             res = tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_DIALRECALL);
05909             if (res) {
05910                ast_log(LOG_WARNING, "Unable to do dial recall on channel %s: %s\n", 
05911                   chan->name, strerror(errno));
05912             }
05913             len = 0;
05914             memset(exten, 0, sizeof(exten));
05915             timeout = firstdigittimeout;
05916          } else if (!strcmp(exten, "*0")) {
05917             struct ast_channel *nbridge = 
05918                p->subs[SUB_THREEWAY].owner;
05919             struct zt_pvt *pbridge = NULL;
05920               /* set up the private struct of the bridged one, if any */
05921             if (nbridge && ast_bridged_channel(nbridge)) 
05922                pbridge = ast_bridged_channel(nbridge)->tech_pvt;
05923             if (nbridge && pbridge && 
05924                 (!strcmp(nbridge->type,"Zap")) && 
05925                (!strcmp(ast_bridged_channel(nbridge)->type, "Zap")) &&
05926                 ISTRUNK(pbridge)) {
05927                int func = ZT_FLASH;
05928                /* Clear out the dial buffer */
05929                p->dop.dialstr[0] = '\0';
05930                /* flash hookswitch */
05931                if ((ioctl(pbridge->subs[SUB_REAL].zfd,ZT_HOOK,&func) == -1) && (errno != EINPROGRESS)) {
05932                   ast_log(LOG_WARNING, "Unable to flash external trunk on channel %s: %s\n", 
05933                      nbridge->name, strerror(errno));
05934                }
05935                swap_subs(p, SUB_REAL, SUB_THREEWAY);
05936                unalloc_sub(p, SUB_THREEWAY);
05937                p->owner = p->subs[SUB_REAL].owner;
05938                if (ast_bridged_channel(p->subs[SUB_REAL].owner))
05939                   ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
05940                ast_hangup(chan);
05941                return NULL;
05942             } else {
05943                tone_zone_play_tone(p->subs[index].zfd, ZT_TONE_CONGESTION);
05944                zt_wait_event(p->subs[index].zfd);
05945                tone_zone_play_tone(p->subs[index].zfd, -1);
05946                swap_subs(p, SUB_REAL, SUB_THREEWAY);
05947                unalloc_sub(p, SUB_THREEWAY);
05948                p->owner = p->subs[SUB_REAL].owner;
05949                ast_hangup(chan);
05950                return NULL;
05951             }              
05952          } else if (!ast_canmatch_extension(chan, chan->context, exten, 1, chan->cid.cid_num) &&
05953                      ((exten[0] != '*') || (strlen(exten) > 2))) {
05954             if (option_debug)
05955                ast_log(LOG_DEBUG, "Can't match %s from '%s' in context %s\n", exten, chan->cid.cid_num ? chan->cid.cid_num : "<Unknown Caller>", chan->context);
05956             break;
05957          }
05958          if (!timeout)
05959             timeout = gendigittimeout;
05960          if (len && !ast_ignore_pattern(chan->context, exten))
05961             tone_zone_play_tone(p->subs[index].zfd, -1);
05962       }
05963       break;
05964    case SIG_FXSLS:
05965    case SIG_FXSGS:
05966    case SIG_FXSKS:
05967 #ifdef ZAPATA_PRI
05968       if (p->pri) {
05969          /* This is a GR-303 trunk actually.  Wait for the first ring... */
05970          struct ast_frame *f;
05971          int res;
05972          time_t start;
05973 
05974          time(&start);
05975          ast_setstate(chan, AST_STATE_RING);
05976          while(time(NULL) < start + 3) {
05977             res = ast_waitfor(chan, 1000);
05978             if (res) {
05979                f = ast_read(chan);
05980                if (!f) {
05981                   ast_log(LOG_WARNING, "Whoa, hangup while waiting for first ring!\n");
05982                   ast_hangup(chan);
05983                   return NULL;
05984                } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RING)) {
05985                   res = 1;
05986                } else
05987                   res = 0;
05988                ast_frfree(f);
05989                if (res) {
05990                   ast_log(LOG_DEBUG, "Got ring!\n");
05991                   res = 0;
05992                   break;
05993                }
05994             }
05995          }
05996       }
05997 #endif
05998       /* If we want caller id, we're in a prering state due to a polarity reversal
05999        * and we're set to use a polarity reversal to trigger the start of caller id,
06000        * grab the caller id and wait for ringing to start... */
06001       if (p->use_callerid && (chan->_state == AST_STATE_PRERING && p->cid_start == CID_START_POLARITY)) {
06002          /* If set to use DTMF CID signalling, listen for DTMF */
06003          if (p->cid_signalling == CID_SIG_DTMF) {
06004             int i = 0;
06005             cs = NULL;
06006             ast_log(LOG_DEBUG, "Receiving DTMF cid on "
06007                "channel %s\n", chan->name);
06008             zt_setlinear(p->subs[index].zfd, 0);
06009             res = 2000;
06010             for (;;) {
06011                struct ast_frame *f;
06012                res = ast_waitfor(chan, res);
06013                if (res <= 0) {
06014                   ast_log(LOG_WARNING, "DTMFCID timed out waiting for ring. "
06015                      "Exiting simple switch\n");
06016                   ast_hangup(chan);
06017                   return NULL;
06018                } 
06019                f = ast_read(chan);
06020                if (f->frametype == AST_FRAME_DTMF) {
06021                   dtmfbuf[i++] = f->subclass;
06022                   ast_log(LOG_DEBUG, "CID got digit '%c'\n", f->subclass);
06023                   res = 2000;
06024                }
06025                ast_frfree(f);
06026                if (chan->_state == AST_STATE_RING ||
06027                    chan->_state == AST_STATE_RINGING) 
06028                   break; /* Got ring */
06029             }
06030             dtmfbuf[i] = 0;
06031             zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
06032             /* Got cid and ring. */
06033             ast_log(LOG_DEBUG, "CID got string '%s'\n", dtmfbuf);
06034             callerid_get_dtmf(dtmfbuf, dtmfcid, &flags);
06035             ast_log(LOG_DEBUG, "CID is '%s', flags %d\n", 
06036                dtmfcid, flags);
06037             /* If first byte is NULL, we have no cid */
06038             if (dtmfcid[0]) 
06039                number = dtmfcid;
06040             else
06041                number = 0;
06042          /* If set to use V23 Signalling, launch our FSK gubbins and listen for it */
06043          } else if (p->cid_signalling == CID_SIG_V23) {
06044             cs = callerid_new(p->cid_signalling);
06045             if (cs) {
06046                samples = 0;
06047 #if 1
06048                bump_gains(p);
06049 #endif            
06050                /* Take out of linear mode for Caller*ID processing */
06051                zt_setlinear(p->subs[index].zfd, 0);
06052                
06053                /* First we wait and listen for the Caller*ID */
06054                for(;;) {   
06055                   i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
06056                   if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i)))  {
06057                      ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
06058                      callerid_free(cs);
06059                      ast_hangup(chan);
06060                      return NULL;
06061                   }
06062                   if (i & ZT_IOMUX_SIGEVENT) {
06063                      res = zt_get_event(p->subs[index].zfd);
06064                      ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
06065                      res = 0;
06066                      break;
06067                   } else if (i & ZT_IOMUX_READ) {
06068                      res = read(p->subs[index].zfd, buf, sizeof(buf));
06069                      if (res < 0) {
06070                         if (errno != ELAST) {
06071                            ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
06072                            callerid_free(cs);
06073                            ast_hangup(chan);
06074                            return NULL;
06075                         }
06076                         break;
06077                      }
06078                      samples += res;
06079                      res = callerid_feed(cs, buf, res, AST_LAW(p));
06080                      if (res < 0) {
06081                         ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
06082                         break;
06083                      } else if (res)
06084                         break;
06085                      else if (samples > (8000 * 10))
06086                         break;
06087                   }
06088                }
06089                if (res == 1) {
06090                   callerid_get(cs, &name, &number, &flags);
06091                   if (option_debug)
06092                      ast_log(LOG_DEBUG, "CallerID number: %s, name: %s, flags=%d\n", number, name, flags);
06093                }
06094                if (res < 0) {
06095                   ast_log(LOG_WARNING, "CallerID returned with error on channel '%s'\n", chan->name);
06096                }
06097 
06098                /* Finished with Caller*ID, now wait for a ring to make sure there really is a call coming */ 
06099                res = 2000;
06100                for (;;) {
06101                   struct ast_frame *f;
06102                   res = ast_waitfor(chan, res);
06103                   if (res <= 0) {
06104                      ast_log(LOG_WARNING, "CID timed out waiting for ring. "
06105                         "Exiting simple switch\n");
06106                      ast_hangup(chan);
06107                      return NULL;
06108                   } 
06109                   f = ast_read(chan);
06110                   ast_frfree(f);
06111                   if (chan->_state == AST_STATE_RING ||
06112                       chan->_state == AST_STATE_RINGING) 
06113                      break; /* Got ring */
06114                }
06115    
06116                /* We must have a ring by now, so, if configured, lets try to listen for
06117                 * distinctive ringing */ 
06118                if (p->usedistinctiveringdetection == 1) {
06119                   len = 0;
06120                   distMatches = 0;
06121                   /* Clear the current ring data array so we dont have old data in it. */
06122                   for (receivedRingT=0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
06123                      curRingData[receivedRingT] = 0;
06124                   receivedRingT = 0;
06125                   counter = 0;
06126                   counter1 = 0;
06127                   /* Check to see if context is what it should be, if not set to be. */
06128                   if (strcmp(p->context,p->defcontext) != 0) {
06129                      ast_copy_string(p->context, p->defcontext, sizeof(p->context));
06130                      ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
06131                   }
06132       
06133                   for(;;) {   
06134                      i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
06135                      if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i)))  {
06136                         ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
06137                         callerid_free(cs);
06138                         ast_hangup(chan);
06139                         return NULL;
06140                      }
06141                      if (i & ZT_IOMUX_SIGEVENT) {
06142                         res = zt_get_event(p->subs[index].zfd);
06143                         ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
06144                         res = 0;
06145                         /* Let us detect distinctive ring */
06146       
06147                         curRingData[receivedRingT] = p->ringt;
06148       
06149                         if (p->ringt < p->ringt_base/2)
06150                            break;
06151                         /* Increment the ringT counter so we can match it against
06152                            values in zapata.conf for distinctive ring */
06153                         if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
06154                            break;
06155                      } else if (i & ZT_IOMUX_READ) {
06156                         res = read(p->subs[index].zfd, buf, sizeof(buf));
06157                         if (res < 0) {
06158                            if (errno != ELAST) {
06159                               ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
06160                               callerid_free(cs);
06161                               ast_hangup(chan);
06162                               return NULL;
06163                            }
06164                            break;
06165                         }
06166                         if (p->ringt) 
06167                            p->ringt--;
06168                         if (p->ringt == 1) {
06169                            res = -1;
06170                            break;
06171                         }
06172                      }
06173                   }
06174                   if(option_verbose > 2)
06175                      /* this only shows up if you have n of the dring patterns filled in */
06176                      ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
06177    
06178                   for (counter=0; counter < 3; counter++) {
06179                      /* Check to see if the rings we received match any of the ones in zapata.conf for this
06180                      channel */
06181                      distMatches = 0;
06182                      for (counter1=0; counter1 < 3; counter1++) {
06183                         if (curRingData[counter1] <= (p->drings.ringnum[counter].ring[counter1]+10) && curRingData[counter1] >=
06184                         (p->drings.ringnum[counter].ring[counter1]-10)) {
06185                            distMatches++;
06186                         }
06187                      }
06188                      if (distMatches == 3) {
06189                         /* The ring matches, set the context to whatever is for distinctive ring.. */
06190                         ast_copy_string(p->context, p->drings.ringContext[counter].contextData, sizeof(p->context));
06191                         ast_copy_string(chan->context, p->drings.ringContext[counter].contextData, sizeof(chan->context));
06192                         if(option_verbose > 2)
06193                            ast_verbose( VERBOSE_PREFIX_3 "Distinctive Ring matched context %s\n",p->context);
06194                         break;
06195                      }
06196                   }
06197                }
06198                /* Restore linear mode (if appropriate) for Caller*ID processing */
06199                zt_setlinear(p->subs[index].zfd, p->subs[index].linear);
06200 #if 1
06201                restore_gains(p);
06202 #endif            
06203             } else
06204                ast_log(LOG_WARNING, "Unable to get caller ID space\n");       
06205          } else {
06206             ast_log(LOG_WARNING, "Channel %s in prering "
06207                "state, but I have nothing to do. "
06208                "Terminating simple switch, should be "
06209                "restarted by the actual ring.\n", 
06210                chan->name);
06211             ast_hangup(chan);
06212             return NULL;
06213          }
06214       } else if (p->use_callerid && p->cid_start == CID_START_RING) {
06215          /* FSK Bell202 callerID */
06216          cs = callerid_new(p->cid_signalling);
06217          if (cs) {
06218 #if 1
06219             bump_gains(p);
06220 #endif            
06221             samples = 0;
06222             len = 0;
06223             distMatches = 0;
06224             /* Clear the current ring data array so we dont have old data in it. */
06225             for (receivedRingT=0; receivedRingT < (sizeof(curRingData) / sizeof(curRingData[0])); receivedRingT++)
06226                curRingData[receivedRingT] = 0;
06227             receivedRingT = 0;
06228             counter = 0;
06229             counter1 = 0;
06230             /* Check to see if context is what it should be, if not set to be. */
06231             if (strcmp(p->context,p->defcontext) != 0) {
06232                ast_copy_string(p->context, p->defcontext, sizeof(p->context));
06233                ast_copy_string(chan->context,p->defcontext,sizeof(chan->context));
06234             }
06235 
06236             /* Take out of linear mode for Caller*ID processing */
06237             zt_setlinear(p->subs[index].zfd, 0);
06238             for(;;) {   
06239                i = ZT_IOMUX_READ | ZT_IOMUX_SIGEVENT;
06240                if ((res = ioctl(p->subs[index].zfd, ZT_IOMUX, &i)))  {
06241                   ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
06242                   callerid_free(cs);
06243                   ast_hangup(chan);
06244                   return NULL;
06245                }
06246                if (i & ZT_IOMUX_SIGEVENT) {
06247                   res = zt_get_event(p->subs[index].zfd);
06248                   ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
06249                   res = 0;
06250                   /* Let us detect callerid when the telco uses distinctive ring */
06251 
06252                   curRingData[receivedRingT] = p->ringt;
06253 
06254                   if (p->ringt < p->ringt_base/2)
06255                      break;
06256                   /* Increment the ringT counter so we can match it against
06257                      values in zapata.conf for distinctive ring */
06258                   if (++receivedRingT == (sizeof(curRingData) / sizeof(curRingData[0])))
06259                      break;
06260                } else if (i & ZT_IOMUX_READ) {
06261                   res = read(p->subs[index].zfd, buf, sizeof(buf));
06262                   if (res < 0) {
06263                      if (errno != ELAST) {
06264                         ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
06265                         callerid_free(cs);
06266                         ast_hangup(chan);
06267                         return NULL;
06268                      }
06269                      break;
06270                   }
06271                   if (p->ringt) 
06272                      p->ringt--;
06273                   if (p->ringt == 1) {
06274                      res = -1;
06275                      break;
06276                   }
06277                   samples += res;
06278                   res = callerid_feed(cs, buf, res, AST_LAW(p));
06279                   if (res < 0) {
06280                      ast_log(LOG_WARNING, "CallerID feed failed: %s\n", strerror(errno));
06281                      break;
06282                   } else if (res)
06283                      break;
06284                   else if (samples > (8000 * 10))
06285                      break;
06286                }
06287             }
06288             if (p->usedistinctiveringdetection == 1) {
06289                if(option_verbose > 2)
06290                   /* this only shows up if you have n of the dring patterns filled in */
06291                   ast_verbose( VERBOSE_PREFIX_3 "Detected ring pattern: %d,%d,%d\n",curRingData[0],curRingData[1],curRingData[2]);
06292 
06293